Sobes.tech
Middle

How to get the book with the highest price — using MAX(price) or sorting with LIMIT 1?

sobes.tech AI

Answer from AI

Both options — using MAX(price) and sorting with LIMIT 1 — can yield the desired result, but there are nuances:

  • MAX(price) returns the maximum price value but not the entire book record. To get the full record with the maximum price, an additional query or subquery is needed.

  • Sorting by price in descending order with LIMIT 1 immediately returns the full record of the book with the highest price.

Example with sorting:

SELECT * FROM books ORDER BY price DESC LIMIT 1;

Example with MAX and a subquery:

SELECT * FROM books WHERE price = (SELECT MAX(price) FROM books);

If the maximum price is unique, both options are equivalent. If multiple books share the maximum price, the second option will return all such books, while sorting with LIMIT 1 will return only one.

In terms of performance, sorting with LIMIT 1 is usually faster if there is an index on the price, as it does not require a full table scan.

How to get the book with the highest price — using… - sobes.tech