Memra

Sorting and limiting

◈ 2 cards

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.

sortcutbooks10 rows, no orderORDER BY price DESC10 rows, sortedLIMIT 1The Long Count · 28.00
ORDER BY sorts the whole result; LIMIT then cuts it. Sorting first is what makes "the most expensive book" a one-row answer — swap the two and you would cut an arbitrary row instead.
NORMAL ~/memra/learn/postgresql/order-by-and-limit utf-8 LF