4. Sorting & Limiting
ORDER BY, LIMIT, and asking for "the top five".
The lesson
Sorting & Limiting
So far you've asked which rows and which columns. But there's a third question a shopkeeper asks constantly: in what order — and a fourth: how many. Databases don't guarantee any row order, so if the answer matters, you have to say so. That's the job of ORDER BY and LIMIT.
ORDER BY: putting rows in order
The clause comes at the very end of the query, after FROM and any WHERE:
SELECT title, duration_sec
FROM tracks
ORDER BY duration_sec;
Now the tracks come back sorted by duration, from the shortest (Copper Wire, 176 seconds) to the longest (Nocturne No. 2, 402). This order is ascending, smallest value first, and it's the default — the query above is identical to ORDER BY duration_sec ASC.
DESC: biggest first
The store's "wall of fame" wants the newest hire on top, so the order has to flip:
SELECT first_name, last_name, hire_date
FROM employees
ORDER BY hire_date DESC;
DESC means descending, largest value first — Ken Ito (2022) at the top, Jane Foster (2016) at the bottom. It works on any comparable column: numbers, dates, text. Dates, as you know, are stored as 'YYYY-MM-DD' text, which sorts chronologically for free.
More than one sort key
What if ties need breaking? The album shelf is sorted by artist, and within each artist by year:
SELECT title, artist_id, release_year
FROM albums
ORDER BY artist_id, release_year;
The first key (artist_id) does the main sorting; the second (release_year) only decides among rows that share the first. So The Amber Lines' albums come in 2003, 2007 — ordered by year inside the artist. You can chain as many keys as you like, and each one gets its own direction: ORDER BY genre_id, unit_price DESC, title.
Ordering by things you compute
Sorting isn't limited to columns that physically exist. Remember the minutes alias from chapter one? You can sort by it too:
SELECT title, duration_sec / 60.0 AS minutes
FROM tracks
ORDER BY minutes DESC;
ORDER BY runs after SELECT has computed its columns, so you can reference the alias — or repeat the whole expression. The result is the tracks arranged from longest to shortest, in the human units customers actually want. (A useful quirk to remember: the order of rows and the order of columns in the result have nothing to do with each other.)
Where do the NULLs go?
Sorting raises a question the data has been saving for you: where do missing values land? The album Crossroads Live has no release_year at all. Sort ascending and watch:
SELECT title, release_year
FROM albums
ORDER BY release_year;
Crossroads Live is first. SQLite treats NULL as the smallest possible value, so in ascending order the NULLs lead the pack, and in descending order they trail at the end. It's a rule, not a bug — but it's worth knowing, because a "sort by year" that silently puts your mystery albums at the top might surprise the boss.
LIMIT: just the top few
Sorting puts the interesting rows at the top; LIMIT chops the answer after a chosen number of rows:
SELECT title, duration_sec
FROM tracks
ORDER BY duration_sec DESC
LIMIT 3;
The three longest tracks — Nocturne No. 2, Nocturne No. 1 and Crossroads (Live). That's the whole "top five" pattern: sort first, then cut. Order matters: LIMIT without ORDER BY is a gamble, because the database may return rows in any order it likes.
OFFSET: paging through results
LIMIT alone gives you page one. Add OFFSET to skip a number of rows before taking the rest — the classic paging pair. The website shows five tracks per page, longest first; page two means skip the five longest, then show five:
SELECT title, duration_sec
FROM tracks
ORDER BY duration_sec DESC
LIMIT 5 OFFSET 5;
Page two is The Long Room, Rivers Run, Sweet Magnolia (Live), Green in Blue and midnight train. Turn any list into pages: page n is LIMIT 5 OFFSET (n-1)*5.
Putting it all together
The three clauses meet in the classic question: the top N of a filtered group — the three longest Rock tracks:
SELECT title
FROM tracks
WHERE genre_id = 1
ORDER BY duration_sec DESC
LIMIT 3;
First WHERE narrows to Rock, then ORDER BY ranks them longest-first, then LIMIT keeps the podium: Crossroads (Live), Sweet Magnolia (Live), midnight train. Filter, sort, cut — in that order, every time.
What you just learned
ORDER BYsorts the result; ascending is the default,DESCflips it.- Multiple keys sort one at a time: first key, then ties broken by the next.
- You can order by computed columns, alias or expression.
- In SQLite, NULLs sort first in ascending order, last in descending.
LIMIT nkeeps n rows;OFFSET mskips m first; together they page.- The winning pattern is
WHERE→ORDER BY→LIMIT.
Dialect note. The NULL placement is where databases disagree. SQLite puts NULLs first in ascending order; PostgreSQL puts them last by default (and lets you fine-tune with
NULLS FIRST/NULLS LAST); MySQL agrees with SQLite. Also, every database phrases limits differently: PostgreSQL and MySQL acceptLIMITandOFFSETlike here, while SQL Server wantsTOP nor the verboseOFFSET ... ROWS FETCH NEXT ... ROWS ONLY. The idea is the same everywhere — only the spelling changes.
The store's answers are sorted and trimmed now. Go arrange some shelves — each exercise is a minute or two if you've read this far.