Memra

Sorting and limiting

Control row order and take just the top few.

Order the answer

Rows come back in no guaranteed order. ORDER BY sorts them — ascending by default, or DESC for descending:

SELECT title, price
FROM books
ORDER BY price DESC;

LIMIT then takes only the first N rows. Combine them to answer "the most expensive book":

SELECT title, price
FROM books
ORDER BY price DESC
LIMIT 1;

You can sort by several columns — ORDER BY genre, price DESC sorts by genre, then by price within each genre.

NORMAL ~/memra/learn/postgresql/order-by-and-limit utf-8 LF