ORDER BY, LIMIT & OFFSET
Sort results, break ties, choose where NULLs land, and fetch one page of rows with LIMIT and OFFSET.
Order and page a result
ORDER BY sorts the result. ASC (small to large) is the default, and DESC flips it. You can list several columns: later ones break ties in earlier ones, and each column has its own direction.
By default NULL counts as larger than any value. So NULLs come last in ASC order and first in DESC order. Add NULLS FIRST or NULLS LAST to choose.
LIMIT caps how many rows come back. OFFSET skips rows before the result starts. The skipped rows are removed first, then LIMIT counts.
Lists need an order and a size
Without ORDER BY, PostgreSQL may return rows in any order, and that order can change from one run to the next. A leaderboard, a search page or a page of results all need an explicit order.
LIMIT and OFFSET turn a long result into pages, so a screen shows ten rows instead of ten thousand.
Sort, break ties, take page 2
Page 2 of the leaderboard, three players per page, best score first, players with no points last:
SELECT name, points
FROM players
ORDER BY points DESC NULLS LAST, id
LIMIT 3 OFFSET 3;The id after points is a tie-break. Without it, players with the same points could appear in a different order each time, and a player could be repeated or missed between pages.
Sort, tie-break and page the players
Choose a sort column, flip the direction, move the NULLs, add a tie-break and turn on LIMIT and OFFSET.
| idinteger | nametext | teamtext | pointsinteger |
|---|---|---|---|
| 2 | Ben | Blue | 17 |
| 8 | Hana | Blue | 17 |
| 4 | Dara | Green | 24 |
| 6 | Fay | Red | 24 |
| 1 | Asha | Red | 31 |
| 7 | Gus | Green | 40 |
| 3 | Chen | Red | NULL |
| 5 | Eli | Blue | NULL |
NULL counts as the largest value, so it comes last in ASC order. Use NULLS FIRST or NULLS LAST to choose.
Check yourself
Pick an answer to lock it in, then read why. Getting one wrong is part of how it sticks.
Remember this
- ORDER BY sorts ASC by default, and each column can have its own direction.
- NULL counts as the largest value: last in ASC, first in DESC, unless NULLS FIRST or NULLS LAST is used.
- Without ORDER BY the order of rows is not promised, and LIMIT then returns an arbitrary few.
- For paging, end ORDER BY with a unique column so the order is the same every time.
Done with this concept?
Mark it complete to track your progress. No login needed.