T11 SQL · Lesson 3
Sorting and limiting
Put an answer in the order you need with ORDER BY, highest or lowest first, settle ties with a second column, decide where the missing values go, keep only the first few rows with LIMIT and the next few with OFFSET, and sort or label rows by rules of your own with CASE.
- sort an answer with ORDER BY, lowest first or with DESC highest first
- sort by several columns, so that a second column settles ties
- say where NULL goes in a sorted answer, and move it with NULLS FIRST or NULLS LAST
- keep only the first rows with LIMIT, and later ones with OFFSET
- write a CASE expression that labels or sorts rows by your own rules
- explain why LIMIT without ORDER BY gives rows that are not promised
The back cover
A table keeps its rows in no promised order, like papers dropped into a box. Yet almost every list on a screen is in order: the newest message first, the cheapest price first, the top ten scores. Somebody asked for that order.
These pages ask for it. They sort an answer with ORDER BY, upward or downward, and settle ties with a second column. They decide where the missing values go, which databases do not agree on. They keep only the first few rows with LIMIT, and the next few with OFFSET, which is how a long list becomes pages. And they sort and label rows by rules of their own, with CASE.
Before you start
The story: Answers in a heap
The Registrar has added three gauges to the ruled page: a kettle, a bell and a valve. Now the halls want answers in order. The Engine Hall asks for its gauges from the highest reading down. The Clock Tower wants only the three hottest. A clerk wants every name from a to z.
Each answer still comes back in whatever order the lines were written. The askers sort the slips by hand on their desks, and two clerks argue about whether the pump or the valve comes first, as both read 4.2.
Registrar Nadia Folio taps the page. "Ask the ledger, not your memory," she says. "If you want an order, ask for it, and say what settles a tie. If you want only the first few, say how many."
Lessons 01 and 02 asked which rows and which columns. They never asked in what order. Lesson 01 warned that, without being told, SQL promises no order at all. This lesson tells it.
It sorts answers with ORDER BY, lowest first or highest first, settles ties with a second column, and decides where the missing values go. It keeps only the first few rows with LIMIT, and later ones with OFFSET. And it meets CASE, which gives each row a label by rules of your own, and can sort by them too.
The Registrar has added three gauges since lesson 02: a kettle in the Couriers' Yard, a bell in the Clock Tower and a valve in the Engine Hall. Here is the table every block of this lesson reads:
query.sql (ledger.db holds the gauges table, now eight gauges)
SELECT * FROM gauges;
Terminal: sqlite3 ledger.db < query.sql
╭────┬──────────┬────────────────┬──────┬─────────╮
│ id │ name │ hall │ unit │ reading │
╞════╪══════════╪════════════════╪══════╪═════════╡
│ 1 │ boiler │ Engine Hall │ C │ 96.5 │
│ 2 │ pump │ Engine Hall │ bar │ 4.2 │
│ 3 │ fan │ Engine Hall │ rpm │ 1200.0 │
│ 4 │ chimney │ Couriers' Yard │ C │ NULL │
│ 5 │ pendulum │ Clock Tower │ s │ 2.0 │
│ 6 │ kettle │ Couriers' Yard │ C │ 88.0 │
│ 7 │ bell │ Clock Tower │ Hz │ 440.0 │
│ 8 │ valve │ Engine Hall │ bar │ 4.2 │
╰────┴──────────┴────────────────┴──────┴─────────╯
Notice that the valve reads 4.2, exactly as the pump does, and that three gauges are measured in C. Ties like these are where sorting gets interesting.
This lesson builds on these ideas. Each one has a tiny example, so you can check that you remember it.
| What you already know | A tiny example | Where it comes back |
|---|---|---|
| SELECT, FROM and WHERE. | SELECT name FROM gauges WHERE reading > 10; | ORDER BY comes after them. |
| The order of rows is not promised without being asked. | lesson 01 | This lesson asks. |
| Text compares by its bytes, capitals first. | 'Z' < 'a' | Sorting text. |
| NULL is not known. | the chimney's reading | Where NULL sorts. |
| AS names a column of the answer. | reading * 2 AS doubled | Sorting by a computed column. |
| Functions such as lower(). | lower(unit) | Sorting without minding capitals. |
| Comparisons give true or false. | reading > 100 | The tests inside CASE. |
| A for loop's counter. | for (i = 0; i < 3; i++) | Pages of three rows. |
| Sorting an array in JavaScript. | [3, 1, 2].sort() | Sorting rows in SQL. |
| if and else. | if (a) ... else ... | CASE WHEN ... ELSE ... END. |
By the end of this lesson you will be able to:
- sort an answer with ORDER BY, lowest first or with DESC highest first;
- sort by several columns, so that a second column settles ties;
- say where NULL goes in a sorted answer, and move it with NULLS FIRST or NULLS LAST;
- keep only the first rows with LIMIT, and later ones with OFFSET;
- write a CASE expression that labels or sorts rows by your own rules;
- explain why LIMIT without ORDER BY gives rows that are not promised.
How to follow this lesson
As before, each block is a file of SQL and the command sqlite3 ledger.db < query.sql, and ledger.db holds the eight gauges above. Change the ORDER BY and run it again; sorting is easiest to learn by watching rows move.
Every block was also run with the real sqlite3 3.54.1 in a real terminal, and printed exactly what you see.
In one line
ORDER BY puts an answer in the order you ask for, LIMIT keeps only as many rows as you need, and CASE labels rows by your own rules.
Sorting with ORDER BY
At a glance
ORDER BY sorts an answer by a column, a calculation or an alias, after WHERE has chosen the rows.
Lowest first is the usual direction, called ascending; DESC after a column turns it round. Numbers sort by size and text letter by letter, as in a dictionary. SQLite compares text by its bytes, though, so every capital letter comes before every small one, and sorting by lower() of a column gives the order a person expects. A sort only shapes the answer. The table's rows stay as they were.
Take a guess: How does SQLite sort the rows of an answer when no index already holds them in order?
ORDER BY sorts an answer by a column. It comes at the end of a query, after WHERE if there is one. Here are the gauges from the lowest reading to the highest:
query.sql (ledger.db holds the gauges table, now eight gauges)
SELECT name, reading FROM gauges ORDER BY reading;
Terminal: sqlite3 ledger.db < query.sql
╭──────────┬─────────╮
│ name │ reading │
╞══════════╪═════════╡
│ chimney │ NULL │
│ pendulum │ 2.0 │
│ pump │ 4.2 │
│ valve │ 4.2 │
│ kettle │ 88.0 │
│ boiler │ 96.5 │
│ bell │ 440.0 │
│ fan │ 1200.0 │
╰──────────┴─────────╯
Read it aloud: "select the name and reading from gauges, ordered by reading." The rows came back from 2.0 up to 1200.0. Lowest first is the usual direction, called ascending; you may write ASC after the column to say so, but it changes nothing.
Two things stand out. The chimney, whose reading is NULL, came first; the NULL section explains why. And the pump and the valve, which both read 4.2, sit next to each other in an order nobody chose; the next section settles that.
Highest first: DESC
Add DESC, short for descending, after the column to sort from the highest down:
query.sql (ledger.db holds the gauges table, now eight gauges)
SELECT name, reading FROM gauges ORDER BY reading DESC;
Terminal: sqlite3 ledger.db < query.sql
╭──────────┬─────────╮
│ name │ reading │
╞══════════╪═════════╡
│ fan │ 1200.0 │
│ bell │ 440.0 │
│ boiler │ 96.5 │
│ kettle │ 88.0 │
│ pump │ 4.2 │
│ valve │ 4.2 │
│ pendulum │ 2.0 │
│ chimney │ NULL │
╰──────────┴─────────╯
The fan now leads, and the chimney has moved to the very end. DESC belongs to the one column it follows. With several columns, each one gets its own ASC or DESC, as the next section shows.
Sorting text
Text sorts in alphabetical order, letter by letter, as in a dictionary:
query.sql (ledger.db holds the gauges table, now eight gauges)
SELECT name FROM gauges ORDER BY name;
Terminal: sqlite3 ledger.db < query.sql
╭──────────╮
│ name │
╞══════════╡
│ bell │
│ boiler │
│ chimney │
│ fan │
│ kettle │
│ pendulum │
│ pump │
│ valve │
╰──────────╯
bell comes before boiler because their second letters, e and o, are in that order. That is the dictionary rule: compare the first letters, and only when they match, look at the next ones.
Capital letters, though, are a surprise. SQLite compares text by its bytes, and in those bytes every capital letter comes before every small letter. So the units, sorted, put C and Hz ahead of bar:
query.sql (ledger.db holds the gauges table, now eight gauges)
SELECT DISTINCT unit FROM gauges ORDER BY unit;
Terminal: sqlite3 ledger.db < query.sql
╭──────╮
│ unit │
╞══════╡
│ C │
│ Hz │
│ bar │
│ rpm │
│ s │
╰──────╯
To sort the way a person expects, sort by the text in small letters with lower(). The answer still shows each unit as it is stored; only the sorting used the small-letter copy:
query.sql (ledger.db holds the gauges table, now eight gauges)
SELECT DISTINCT unit FROM gauges ORDER BY lower(unit);
Terminal: sqlite3 ledger.db < query.sql
╭──────╮
│ unit │
╞══════╡
│ bar │
│ C │
│ Hz │
│ rpm │
│ s │
╰──────╯
Sorting by a calculation
ORDER BY can sort by any expression, a calculation or a function, and also by a column's alias from the SELECT list:
query.sql (ledger.db holds the gauges table, now eight gauges)
SELECT name, reading * 2 AS doubled FROM gauges ORDER BY doubled DESC LIMIT 2;
Terminal: sqlite3 ledger.db < query.sql
╭──────┬─────────╮
│ name │ doubled │
╞══════╪═════════╡
│ fan │ 2400.0 │
│ bell │ 880.0 │
╰──────┴─────────╯
The LIMIT 2 at the end kept only the first two rows; LIMIT has a section of its own. Notice the order of the parts: SELECT, FROM, WHERE, ORDER BY, LIMIT. Each one works on what the one before it handed over.
Worked example 1
The Engine Hall wants to know which of its gauges reads highest. Write a query that answers with that one gauge.
What we have: The gauges table; four gauges stand in the Engine Hall.
What we need: One row: the Engine Hall's gauge with the highest reading.
The plan: Keep the Engine Hall's rows with WHERE, sort them highest first with ORDER BY ... DESC, and keep the first with LIMIT 1.
- Only the Engine Hall:
WHERE hall = 'Engine Hall'. - Highest first:
ORDER BY reading DESC. - Only the first row:
LIMIT 1.
query.sql (ledger.db holds the gauges table, now eight gauges)
SELECT name, reading FROM gauges WHERE hall = 'Engine Hall' ORDER BY reading DESC LIMIT 1;
Terminal: sqlite3 ledger.db < query.sql
╭──────┬─────────╮
│ name │ reading │
╞══════╪═════════╡
│ fan │ 1200.0 │
╰──────┴─────────╯
The fan, at 1200.0.
Check: The Engine Hall's readings are 96.5, 4.2, 1200.0 and 4.2. The highest is 1200.0, the fan's. Run the query without LIMIT 1 to see all four in order.
A path that fails: Writing ORDER BY before WHERE: SELECT ... FROM gauges ORDER BY reading DESC WHERE hall = 'Engine Hall'. The parts have a fixed order, and SQLite reports a syntax error near WHERE.
When you are stuck: ORDER BY
If the rows come back in the wrong direction, check for DESC: without it, the lowest come first.
If text sorts strangely, look for capital letters: they all come before small ones. Sort by lower(column) to ignore the difference.
A common mistake
Expecting ORDER BY to change the table. Like everything in a SELECT, it only shapes the answer; the next query sees the rows in no promised order again.
Your turn
Write a query that lists the gauges' names from z to a.Tap to reveal
- Text, sorted, highest first.
SELECT name FROM gauges ORDER BY name DESC; starts with valve and ends with bell.
Where does ORDER BY go in a query that also has WHERE?Tap to reveal
- The parts have a fixed order.
After WHERE: SELECT ... FROM ... WHERE ... ORDER BY ...
Why does ORDER BY unit put C before bar?Tap to reveal
- Think of capitals and bytes.
Every capital letter comes before every small letter, so C sorts ahead of b; ORDER BY lower(unit) gives bar, C, Hz, rpm, s.
Did you know?
A sort builds an index of its own
When no index already holds the rows in the order asked for, SQLite sorts by building a temporary one. Its documentation says it stores each row in a transient index whose key is the ORDER BY terms. When the query has run, SQLite walks that index from beginning to end and hands the rows back in the desired order.
Why it fits here: It answers the topic's question: a sort is a temporary index, keyed on the ORDER BY terms, read from start to end.
How ORDER BY reads a word in quotes
SQLite reads each ORDER BY term by fixed rules. A name that matches an alias of the answer's columns sorts by that column. Any other expression, its documentation says, is evaluated, and the value it gives is used to order the rows. So ORDER BY 'reading', in single quotes, is a piece of text, the same for every row, and the rows do not move.
Why it fits here: It explains the quiet mistake of this topic's lesson: a quoted name is evaluated as text, so every row gets the same sort value.
Source: SQLite: SELECT
In one line
ORDER BY sorts an answer by a column or an expression, lowest first unless DESC follows it; text sorts letter by letter with every capital before every small letter, so sort by lower() to ignore case.
Several columns, and settling ties
At a glance
ORDER BY can take a list of sort keys, with commas between them, each with its own direction.
The first key decides. Only where two rows tie on it does the second key look at them, and so on. DESC belongs to the one key it follows, so ORDER BY unit, reading DESC sorts the units upward and the readings downward. Rows that tie on every key come back in no promised order, so a list that must stay put ends with a key that cannot tie, such as a name or an id.
Take a guess: When an answer is cut short, is there a way to keep every row that ties for the last place?
Sorting by one column leaves a question open: what happens to rows that tie? The pump and the valve both read 4.2, and so far they have come back pump first, then valve, only because that is the order SQLite happened to meet them. Nothing promised it.
ORDER BY can take a list of columns, with commas between them. SQLite sorts by the first column; only where two rows tie on it does it look at the second, and so on. Each column is called a sort key, and each one takes its own ASC or DESC.
query.sql (ledger.db holds the gauges table, now eight gauges)
SELECT name, unit, reading FROM gauges ORDER BY unit, reading DESC;
Terminal: sqlite3 ledger.db < query.sql
╭──────────┬──────┬─────────╮
│ name │ unit │ reading │
╞══════════╪══════╪═════════╡
│ boiler │ C │ 96.5 │
│ kettle │ C │ 88.0 │
│ chimney │ C │ NULL │
│ bell │ Hz │ 440.0 │
│ pump │ bar │ 4.2 │
│ valve │ bar │ 4.2 │
│ fan │ rpm │ 1200.0 │
│ pendulum │ s │ 2.0 │
╰──────────┴──────┴─────────╯
Read it aloud: "ordered by unit, then by reading, highest first." The units came out in their byte order, C, Hz, bar, rpm and s. Inside the three C gauges, the second key took over: the boiler's 96.5, then the kettle's 88.0, then the chimney's NULL. The DESC belonged only to the reading; the units still ran upward.
A tie that is settled on purpose
Sorted by reading alone, the pump and the valve tie. Add a second key, the name, and the tie is settled the same way every time:
query.sql (ledger.db holds the gauges table, now eight gauges)
SELECT name, reading FROM gauges ORDER BY reading DESC, name;
Terminal: sqlite3 ledger.db < query.sql
╭──────────┬─────────╮
│ name │ reading │
╞══════════╪═════════╡
│ fan │ 1200.0 │
│ bell │ 440.0 │
│ boiler │ 96.5 │
│ kettle │ 88.0 │
│ pump │ 4.2 │
│ valve │ 4.2 │
│ pendulum │ 2.0 │
│ chimney │ NULL │
╰──────────┴─────────╯
The answer looks the same as before, and that is the point. Before, pump came before valve by luck. Now it comes first because p is before v. If a gauge called alarm were added at 4.2 tomorrow, it would go first among the three, every time. A good rule: when the order of an answer matters, end the ORDER BY with a column that cannot tie, such as the name or the id.
| ORDER BY | Sorts by | Ties settled by |
|---|---|---|
reading | reading, lowest first | nothing: tied rows come in no promised order |
reading DESC, name | reading, highest first | the name, a to z |
unit, reading DESC | unit, a to z | the reading, highest first |
hall, name, id | hall, then name | the id, which never ties |
Sorting by a column's place
ORDER BY also accepts a number, meaning that column of the SELECT list: 1 is the first, 2 the second.
query.sql (ledger.db holds the gauges table, now eight gauges)
SELECT name, unit FROM gauges ORDER BY 2, 1;
Terminal: sqlite3 ledger.db < query.sql
╭──────────┬──────╮
│ name │ unit │
╞══════════╪══════╡
│ boiler │ C │
│ chimney │ C │
│ kettle │ C │
│ bell │ Hz │
│ pump │ bar │
│ valve │ bar │
│ fan │ rpm │
│ pendulum │ s │
╰──────────┴──────╯
ORDER BY 2, 1 means by unit, then by name. It is short, but it breaks quietly when someone adds a column to the start of the list: 2 then means something else. Use names in anything you keep; numbers are for quick questions at the prompt.
Worked example 2
The Clock Tower wants every gauge listed by hall, a to z, and inside each hall from the highest reading down. Write the query.
What we have: The hall and reading columns, and ORDER BY's list of keys.
What we need: Rows grouped by hall in alphabetical order, each hall's gauges from the highest reading to the lowest.
The plan: Two keys: hall first, ascending; then reading, descending.
- The first key:
hall, ascending, which needs no word. - The second key:
reading DESC, which only matters inside a hall.
query.sql (ledger.db holds the gauges table, now eight gauges)
SELECT hall, name, reading FROM gauges ORDER BY hall, reading DESC;
Terminal: sqlite3 ledger.db < query.sql
╭────────────────┬──────────┬─────────╮
│ hall │ name │ reading │
╞════════════════╪══════════╪═════════╡
│ Clock Tower │ bell │ 440.0 │
│ Clock Tower │ pendulum │ 2.0 │
│ Couriers' Yard │ kettle │ 88.0 │
│ Couriers' Yard │ chimney │ NULL │
│ Engine Hall │ fan │ 1200.0 │
│ Engine Hall │ boiler │ 96.5 │
│ Engine Hall │ pump │ 4.2 │
│ Engine Hall │ valve │ 4.2 │
╰────────────────┴──────────┴─────────╯
Clock Tower first (bell, pendulum), then Couriers' Yard (kettle, chimney), then Engine Hall (fan, boiler, pump, valve).
Check: Inside each hall the readings fall. In the Engine Hall, the pump and the valve still tie at 4.2; add , name at the end to settle them for good.
A path that fails: Writing ORDER BY hall DESC, reading when only the reading should run downward. DESC belongs to the one key it follows, so this sorts the halls from z to a and the readings upward.
When you are stuck: several sort keys
Read the keys from left to right: the first decides, and each later key only breaks the ties left by the keys before it.
If two rows swap places between runs, they tie on every key you gave. Add a key that cannot tie, such as the name or the id.
A common mistake
Putting one DESC at the end and expecting it to cover every key. In ORDER BY unit, reading DESC, only the reading runs downward.
Your turn
Write a query that lists the gauges by unit, and inside each unit by name.Tap to reveal
- Two keys, both ascending.
SELECT name, unit FROM gauges ORDER BY unit, name;
In ORDER BY reading, name DESC, which key runs downward?Tap to reveal
- DESC belongs to the key it follows.
Only the name; the reading runs upward.
Why add a key that cannot tie at the end of an ORDER BY?Tap to reveal
- Think of the pump and the valve.
Rows that tie on every key come back in no promised order; a key that cannot tie, such as the id, fixes their order for good.
Did you know?
Columns counted from 1
SQLite accepts ORDER BY 2, 1. Its documentation says a constant whole number K in ORDER BY is taken as the K-th column of the answer, with the columns numbered from left to right starting with 1. A JavaScript array counts its places from 0, so ORDER BY 1 is the first column, not the second.
Why it fits here: It explains this topic's ORDER BY 2, 1: a number names a column of the answer, counted from 1.
Source: SQLite: SELECT
Keeping the ties: WITH TIES
PostgreSQL can cut an answer short without splitting a tie. Its documentation says the WITH TIES option of FETCH FIRST returns any additional rows that tie for the last place, according to the ORDER BY clause, which is then required. Asked for the top three readings, it would also keep a fourth gauge tied with the third.
Why it fits here: It answers the topic's question: ties can be kept whole when an answer is cut, with the standard's WITH TIES.
Source: PostgreSQL: SELECT
In one line
ORDER BY takes a list of sort keys, each with its own ASC or DESC; the first decides and each later key only settles ties, so end with a key that cannot tie when the order matters.
Where NULL goes when you sort
At a glance
NULL is equal to nothing, yet a sort must still put it somewhere, so every database has a rule.
SQLite counts NULL as smaller than any other value, so NULLs come first in an upward sort and last in a downward one. PostgreSQL does the opposite. Writing NULLS FIRST or NULLS LAST after a sort key says where they go, and gives the same answer in both. An older way works in every database: sort first by column IS NULL, then by the column. A sort never drops a row.
Take a guess: In which year did SQLite learn to say NULLS FIRST and NULLS LAST?
Lesson 02 found that NULL is never equal to anything and never greater or less. Yet ORDER BY must put the chimney somewhere. It cannot leave a row out, so it needs a rule, and every database has one.
SQLite's rule is that NULL counts as smaller than any other value when it sorts. So in an ascending sort the NULLs come first, and in a descending sort they come last. Sort the Couriers' Yard's two gauges by reading, and the chimney leads:
query.sql (ledger.db holds the gauges table, now eight gauges)
SELECT name, reading FROM gauges WHERE hall = 'Couriers'' Yard' ORDER BY reading;
Terminal: sqlite3 ledger.db < query.sql
╭─────────┬─────────╮
│ name │ reading │
╞═════════╪═════════╡
│ chimney │ NULL │
│ kettle │ 88.0 │
╰─────────┴─────────╯
That is rarely what a reader wants. A list of readings from the lowest up usually means "the lowest known reading first", with the unknown ones at the bottom. Say so with NULLS LAST after the sort key:
query.sql (ledger.db holds the gauges table, now eight gauges)
SELECT name, reading FROM gauges ORDER BY reading NULLS LAST;
Terminal: sqlite3 ledger.db < query.sql
╭──────────┬─────────╮
│ name │ reading │
╞══════════╪═════════╡
│ pendulum │ 2.0 │
│ pump │ 4.2 │
│ valve │ 4.2 │
│ kettle │ 88.0 │
│ boiler │ 96.5 │
│ bell │ 440.0 │
│ fan │ 1200.0 │
│ chimney │ NULL │
╰──────────┴─────────╯
NULLS FIRST does the opposite. In a list of the highest readings, the gauges nobody has read can go to the top, to catch someone's eye:
query.sql (ledger.db holds the gauges table, now eight gauges)
SELECT name, reading FROM gauges ORDER BY reading DESC NULLS FIRST;
Terminal: sqlite3 ledger.db < query.sql
╭──────────┬─────────╮
│ name │ reading │
╞══════════╪═════════╡
│ chimney │ NULL │
│ fan │ 1200.0 │
│ bell │ 440.0 │
│ boiler │ 96.5 │
│ kettle │ 88.0 │
│ pump │ 4.2 │
│ valve │ 4.2 │
│ pendulum │ 2.0 │
╰──────────┴─────────╯
| ORDER BY | Where NULLs go in SQLite |
|---|---|
reading | first, as NULL counts as the smallest |
reading DESC | last |
reading NULLS LAST | last |
reading DESC NULLS FIRST | first |
Databases disagree
Here databases differ, as they did over LIKE. PostgreSQL counts NULL as larger than any other value, so it puts NULLs last in an ascending sort and first in a descending one: the opposite of SQLite. A query that relies on the default will move its NULLs when it moves to T12's PostgreSQL. Writing NULLS FIRST or NULLS LAST yourself gives the same answer in both.
The older way
NULLS FIRST and NULLS LAST arrived in SQLite only with version 3.30, in 2019, and some databases still lack them. You will meet queries that sort NULLs with a trick instead: sort first by whether the value is NULL, then by the value itself.
query.sql (ledger.db holds the gauges table, now eight gauges)
SELECT name, reading FROM gauges ORDER BY reading IS NULL, reading;
Terminal: sqlite3 ledger.db < query.sql
╭──────────┬─────────╮
│ name │ reading │
╞══════════╪═════════╡
│ pendulum │ 2.0 │
│ pump │ 4.2 │
│ valve │ 4.2 │
│ kettle │ 88.0 │
│ boiler │ 96.5 │
│ bell │ 440.0 │
│ fan │ 1200.0 │
│ chimney │ NULL │
╰──────────┴─────────╯
The first key, reading IS NULL, is 0 for a known reading and 1 for a missing one, so the known readings sort ahead. The second key then sorts them among themselves. The answer is the same as NULLS LAST, written in a way every database understands.
Worked example 3
The Couriers' Yard wants its gauges from the highest reading down, with any unread gauge at the very top, so that someone goes to read it. Write the query.
What we have: The Couriers' Yard's gauges: the kettle at 88.0 and the chimney, unread.
What we need: The chimney first, then the readings from the highest down.
The plan: Keep the yard's rows, sort by reading DESC, and move the NULLs to the top with NULLS FIRST.
- The rows:
WHERE hall = 'Couriers'' Yard', with the apostrophe doubled. - Highest first:
ORDER BY reading DESC. On its own, that would put the chimney last. - Add
NULLS FIRSTafter DESC.
query.sql (ledger.db holds the gauges table, now eight gauges)
SELECT name, reading FROM gauges WHERE hall = 'Couriers'' Yard' ORDER BY reading DESC NULLS FIRST;
Terminal: sqlite3 ledger.db < query.sql
╭─────────┬─────────╮
│ name │ reading │
╞═════════╪═════════╡
│ chimney │ NULL │
│ kettle │ 88.0 │
╰─────────┴─────────╯
The chimney, then the kettle.
Check: Run it once without NULLS FIRST: the chimney drops to the end, after the kettle, because NULL counts as the smallest and DESC puts the smallest last. NULLS FIRST is what lifts it to the top.
A path that fails: Writing WHERE reading = NULL to bring the chimney forward. As lesson 02 showed, that test is never true and drops every row.
When you are stuck: NULL in a sort
If unread gauges sit in an awkward place, add NULLS LAST or NULLS FIRST after the key, and say which you want.
If a sort must work in any database, use the older way: ORDER BY column IS NULL, column.
A common mistake
Thinking ORDER BY drops NULL rows, as WHERE does. A sort never removes a row; it only places it. The chimney is always in the answer, first or last.
Your turn
In SQLite, where does the chimney go in ORDER BY reading DESC?Tap to reveal
- NULL counts as the smallest.
Last: the smallest comes last in a descending sort.
Write the gauges sorted by reading, lowest first, with the chimney last, without NULLS LAST.Tap to reveal
- Sort first by whether the reading is NULL.
SELECT name, reading FROM gauges ORDER BY reading IS NULL, reading;
A query sorted by reading puts the chimney first in SQLite. Where would PostgreSQL put it?Tap to reveal
- PostgreSQL counts NULL as the largest.
Last, so write NULLS FIRST or NULLS LAST to get the same answer in both.
Did you know?
Smallest here, largest there
Two well-known databases sort NULL at opposite ends. SQLite's documentation says it considers NULL values to be smaller than any other values for sorting. PostgreSQL's says its null values sort as if larger than any non-null value, so NULLS FIRST is its default for DESC order and NULLS LAST otherwise.
Why it fits here: It shows why this topic says to write NULLS FIRST or NULLS LAST: the defaults of the two databases are opposites.
Sources: SQLite: SELECT; PostgreSQL: Sorting Rows (ORDER BY)
NULLS LAST arrived in 2019
SQLite has not always understood NULLS FIRST and NULLS LAST. Its list of changes puts them in version 3.30.0, released on 2019-10-04, in a line that reads: add support for the NULLS FIRST and NULLS LAST syntax in ORDER BY clauses. So a query that must run on an older SQLite sorts its NULLs with the IS NULL key instead.
Why it fits here: It answers the topic's question, and explains why older queries use the IS NULL key in place of NULLS LAST.
Source: SQLite: Release History
In one line
SQLite sorts NULL as smaller than every value, so it comes first in ASC and last in DESC; PostgreSQL does the opposite, so say NULLS FIRST or NULLS LAST, or sort by column IS NULL first.
Only the first few: LIMIT and OFFSET
At a glance
LIMIT keeps at most a given number of rows of the answer, and OFFSET skips rows before it starts counting.
LIMIT is the last part of a query, after ORDER BY. LIMIT 3 OFFSET 3 skips three rows and keeps the next three, which is how an app shows a long list a page at a time: page p of n rows has offset (p − 1) × n. LIMIT only means something after an ORDER BY that cannot tie. SQLite also takes two numbers with a comma, and then the first is the offset.
Take a guess: Why does SQLite's LIMIT 3, 2 put the offset first, the opposite of LIMIT 2 OFFSET 3?
Often you want only the top of a sorted answer: the three hottest gauges, the five newest parcels, the one best seller. LIMIT keeps at most that many rows. It is the last part of a query, after ORDER BY:
query.sql (ledger.db holds the gauges table, now eight gauges)
SELECT name, reading FROM gauges ORDER BY reading DESC, name LIMIT 3;
Terminal: sqlite3 ledger.db < query.sql
╭────────┬─────────╮
│ name │ reading │
╞════════╪═════════╡
│ fan │ 1200.0 │
│ bell │ 440.0 │
│ boiler │ 96.5 │
╰────────┴─────────╯
SQLite sorted all eight gauges, then handed back the first three. LIMIT counts rows of the answer; if the answer has fewer rows than the limit, you get them all, and no error.
The next few: OFFSET
OFFSET skips rows before LIMIT starts counting. LIMIT 3 OFFSET 3 skips the first three rows and keeps the next three. This is how an app shows a long list a page at a time:
query.sql (ledger.db holds the gauges table, now eight gauges)
SELECT name, reading FROM gauges ORDER BY reading DESC, name LIMIT 3 OFFSET 3;
Terminal: sqlite3 ledger.db < query.sql
╭────────┬─────────╮
│ name │ reading │
╞════════╪═════════╡
│ kettle │ 88.0 │
│ pump │ 4.2 │
│ valve │ 4.2 │
╰────────┴─────────╯
That is page 2. Page 3 skips six rows, and finds only two left, so it shows two:
query.sql (ledger.db holds the gauges table, now eight gauges)
SELECT name, reading FROM gauges ORDER BY reading DESC, name LIMIT 3 OFFSET 6;
Terminal: sqlite3 ledger.db < query.sql
╭──────────┬─────────╮
│ name │ reading │
╞══════════╪═════════╡
│ pendulum │ 2.0 │
│ chimney │ NULL │
╰──────────┴─────────╯
| Page | OFFSET | Rows shown |
|---|---|---|
| 1 | 0 (or none) | rows 1 to 3 |
| 2 | 3 | rows 4 to 6 |
| 3 | 6 | rows 7 to 9, if they exist |
| page p | (p − 1) × 3 | the p-th set of three |
The page number and the offset are one apart, as a for loop's counter starts at 0: page 1 skips nothing. In SQLite, OFFSET only comes after a LIMIT; on its own it is a syntax error. To skip rows with no upper bound, SQLite accepts a negative limit, such as LIMIT -1 OFFSET 6, which means no limit at all.
LIMIT needs an ORDER BY
LIMIT keeps the first rows of the answer. Without ORDER BY, the answer has no promised order, so "the first three" means whichever three the database met first:
query.sql (ledger.db holds the gauges table, now eight gauges)
SELECT name FROM gauges LIMIT 3;
Terminal: sqlite3 ledger.db < query.sql
╭────────╮
│ name │
╞════════╡
│ boiler │
│ pump │
│ fan │
╰────────╯
Today that gives the first three ids. After a few changes to the table, or in another database, it may give three others, and nothing will warn you. PostgreSQL's documentation says the same about its own LIMIT: without an ORDER BY that puts the rows in a unique order, you get an unpredictable subset. So pair LIMIT with ORDER BY, and end the ORDER BY with a key that cannot tie, as the name does in every block above.
The comma form, and its trap
SQLite also accepts two numbers after LIMIT, separated by a comma. The trap: the first number is the offset and the second is the limit, the reverse of the order in LIMIT ... OFFSET.
query.sql (ledger.db holds the gauges table, now eight gauges)
SELECT name, reading FROM gauges ORDER BY reading DESC, name LIMIT 3, 2;
Terminal: sqlite3 ledger.db < query.sql
╭────────┬─────────╮
│ name │ reading │
╞════════╪═════════╡
│ kettle │ 88.0 │
│ pump │ 4.2 │
╰────────┴─────────╯
LIMIT 3, 2 skipped three rows and kept two. SQLite's own documentation calls this counter-intuitive, and keeps it only so that queries from other databases still run. Write LIMIT and OFFSET as words, and nobody has to remember which number is which.
Worked example 4
The Clock Tower shows the gauges two at a time, sorted by name. Which query gives the second page, and what does it show?
What we have: Eight gauges, sorted by name: bell, boiler, chimney, fan, kettle, pendulum, pump, valve.
What we need: The second page of two: the third and fourth names.
The plan: Sort by name, skip one page of two rows with OFFSET 2, and keep two with LIMIT 2.
- Sort:
ORDER BY name. Names never tie here, so the order is fixed. - Page 2 skips one page: OFFSET is (2 − 1) × 2 = 2.
- Keep a page:
LIMIT 2.
query.sql (ledger.db holds the gauges table, now eight gauges)
SELECT name FROM gauges ORDER BY name LIMIT 2 OFFSET 2;
Terminal: sqlite3 ledger.db < query.sql
╭─────────╮
│ name │
╞═════════╡
│ chimney │
│ fan │
╰─────────╯
chimney and fan.
Check: Counting by hand: page 1 is bell and boiler, page 2 is chimney and fan, page 3 is kettle and pendulum, page 4 is pump and valve. Four pages of two hold all eight.
Another way: LIMIT 2, 2 gives the same rows with the comma form, offset first; it works in SQLite but is easy to misread.
A path that fails: Writing LIMIT 2 OFFSET 4 for page 2, as if OFFSET were the last row to show. That skips four rows and shows page 3, kettle and pendulum.
Worked example 5
Which gauge has the second highest reading? Write a query that answers with that one gauge.
What we have: Eight gauges; the chimney's reading is not known.
What we need: One row: the gauge whose reading comes second from the top.
The plan: Sort highest first, skip the top row with OFFSET 1, and keep one row with LIMIT 1.
- Highest first:
ORDER BY reading DESC. The chimney's NULL goes to the end, so it cannot take a place at the top. - Skip the top row:
OFFSET 1. - Keep one row:
LIMIT 1, written before the OFFSET.
query.sql (ledger.db holds the gauges table, now eight gauges)
SELECT name, reading FROM gauges ORDER BY reading DESC LIMIT 1 OFFSET 1;
Terminal: sqlite3 ledger.db < query.sql
╭──────┬─────────╮
│ name │ reading │
╞══════╪═════════╡
│ bell │ 440.0 │
╰──────┴─────────╯
The bell, at 440.0.
Check: From the top, the readings are 1200.0, 440.0, 96.5 and so on, so 440.0 is second. OFFSET counts rows, not values: if two gauges shared the top reading, OFFSET 1 would give the second of them, at that same reading.
A path that fails: Writing LIMIT 2 to get the second gauge. That keeps the top two rows, the fan and the bell, not the second one alone.
When you are stuck: LIMIT and OFFSET
If a page shows the wrong rows, work out the offset by hand: (page − 1) × rows per page. Page 1 has offset 0.
If the first rows change from one run to the next, the ORDER BY is missing or ends in a key that ties.
A common mistake
Using LIMIT to pick "the top" without ORDER BY. LIMIT only cuts the answer short; it is ORDER BY that decides what the top is.
Your turn
Write a query for the two gauges with the lowest known readings.Tap to reveal
- Sort upward, keep the NULLs out of the way, settle ties, keep two.
SELECT name, reading FROM gauges ORDER BY reading NULLS LAST, name LIMIT 2; gives the pendulum and the pump. The pump and the valve tie at 4.2, so the name settles which one makes the cut.
Pages hold 5 rows. What is the OFFSET of page 4?Tap to reveal
- (page − 1) × rows per page.
(4 − 1) × 5 = 15.
In SQLite, which rows does LIMIT 10, 5 keep?Tap to reveal
- In the comma form, the first number is the offset.
It skips 10 rows and keeps 5: the same as LIMIT 5 OFFSET 10.
Did you know?
Offset first, on purpose
SQLite's documentation admits that its comma form of LIMIT is counter-intuitive: with the comma, the first number is the offset and the second the limit, the reverse of LIMIT with OFFSET. It calls the reversal intentional, because it maximizes compatibility with other SQL database systems, whose queries can then run unchanged.
Why it fits here: It answers the topic's question: the comma form copies other databases, and SQLite kept it knowing it confuses.
Source: SQLite: SELECT
LIMIT is not in the standard
The word most people learn for cutting an answer short is not standard SQL. PostgreSQL's documentation calls LIMIT and OFFSET PostgreSQL-specific syntax, also used by MySQL. It says the SQL:2008 standard brought in its own clauses for the same job, OFFSET with FETCH FIRST, which IBM's DB2 also uses.
Why it fits here: It places this topic's LIMIT among databases: common and convenient, but not the standard's own spelling.
Source: PostgreSQL: SELECT
The skipped rows still cost work
OFFSET does not jump straight to page 5000. PostgreSQL's documentation warns that the rows skipped by an OFFSET clause still have to be computed inside the server, so a large OFFSET might be inefficient. To show rows 1,00,001 to 1,00,020, the database first works out the 1,00,000 rows before them.
Why it fits here: It shows the cost behind this topic's pages: every skipped row is still found and sorted.
Source: PostgreSQL: LIMIT and OFFSET
In one line
LIMIT n keeps the first n rows and OFFSET skips rows before them, so page p is LIMIT n OFFSET (p − 1) × n; always pair LIMIT with an ORDER BY that cannot tie.
Rules of your own: CASE
At a glance
A CASE expression works out a value for each row from a list of tests, as if and else do in a program.
CASE WHEN test THEN value, as many times as needed, then ELSE and END. SQLite tries the tests from the top and stops at the first true one, so the strictest test goes first. A NULL makes a test not known, which is not true, so give NULL its own WHEN. The short form, CASE column WHEN value, compares with =. A CASE in ORDER BY sorts by an order of your own.
Take a guess: Does SQLite have a shorter way to write a CASE that chooses between two values?
Sometimes a reader wants a word, not a number: is the boiler running high, warm or low? A CASE expression works out a value for each row from a list of tests, as if and else do in JavaScript. Here it labels every gauge:
query.sql (ledger.db holds the gauges table, now eight gauges)
SELECT name, reading,
CASE
WHEN reading > 100 THEN 'high'
WHEN reading > 10 THEN 'warm'
ELSE 'low'
END AS level
FROM gauges;
Terminal: sqlite3 ledger.db < query.sql
╭──────────┬─────────┬───────╮
│ name │ reading │ level │
╞══════════╪═════════╪═══════╡
│ boiler │ 96.5 │ warm │
│ pump │ 4.2 │ low │
│ fan │ 1200.0 │ high │
│ chimney │ NULL │ low │
│ pendulum │ 2.0 │ low │
│ kettle │ 88.0 │ warm │
│ bell │ 440.0 │ high │
│ valve │ 4.2 │ low │
╰──────────┴─────────┴───────╯
Read the CASE aloud: "when the reading is above 100, the answer is high; when it is above 10, warm; otherwise, low." SQLite tries the WHEN tests in order, top to bottom, and stops at the first one that is true. The fan's 1200.0 passes the first test, so it is high and the second test is never tried. The boiler's 96.5 fails the first and passes the second, so it is warm. The pump passes neither, so ELSE gives it low.
The order of the WHEN tests matters. Put reading > 10 first, and the fan would be called warm, because 1200.0 is above 10 too and the first true test wins. Write the strictest test first.
CASE and NULL
Look at the chimney: low. Its reading is not known, so both tests were not true, and ELSE caught it. A gauge nobody has read is not low; it is unknown. Give NULL its own WHEN, first:
query.sql (ledger.db holds the gauges table, now eight gauges)
SELECT name,
CASE
WHEN reading IS NULL THEN 'unknown'
WHEN reading > 100 THEN 'high'
WHEN reading > 10 THEN 'warm'
ELSE 'low'
END AS level
FROM gauges;
Terminal: sqlite3 ledger.db < query.sql
╭──────────┬─────────╮
│ name │ level │
╞══════════╪═════════╡
│ boiler │ warm │
│ pump │ low │
│ fan │ high │
│ chimney │ unknown │
│ pendulum │ low │
│ kettle │ warm │
│ bell │ high │
│ valve │ low │
╰──────────┴─────────╯
Now the chimney says unknown. This is lesson 02's NULL trap again, in a new place: an ELSE quietly catches every row whose tests were not known. Whenever a CASE tests a column that can be NULL, decide what NULL should say, and say it first, where a reader sees it at once. A CASE with no ELSE gives NULL for a row that matches no WHEN.
The short form: CASE on one value
When every test compares the same column with =, CASE has a shorter form: name the column once, after CASE, and give each WHEN a value to match.
query.sql (ledger.db holds the gauges table, now eight gauges)
SELECT name, unit,
CASE unit
WHEN 'C' THEN 'heat'
WHEN 'bar' THEN 'pressure'
ELSE 'other'
END AS kind
FROM gauges;
Terminal: sqlite3 ledger.db < query.sql
╭──────────┬──────┬──────────╮
│ name │ unit │ kind │
╞══════════╪══════╪══════════╡
│ boiler │ C │ heat │
│ pump │ bar │ pressure │
│ fan │ rpm │ other │
│ chimney │ C │ heat │
│ pendulum │ s │ other │
│ kettle │ C │ heat │
│ bell │ Hz │ other │
│ valve │ bar │ pressure │
╰──────────┴──────┴──────────╯
CASE unit WHEN 'C' means CASE WHEN unit = 'C'. Being an = test, the short form can never match NULL; use the long form, with IS NULL, when NULL needs its own answer.
Sorting by your own order
A CASE can sit in ORDER BY too, and that solves a problem no plain sort can: an order that is not alphabetical or numerical. The Clock Tower wants its own gauges first, then the Engine Hall's, then the rest. Give each hall a number with CASE, and sort by the number:
query.sql (ledger.db holds the gauges table, now eight gauges)
SELECT name, hall FROM gauges
ORDER BY
CASE hall
WHEN 'Clock Tower' THEN 1
WHEN 'Engine Hall' THEN 2
ELSE 3
END,
name;
Terminal: sqlite3 ledger.db < query.sql
╭──────────┬────────────────╮
│ name │ hall │
╞══════════╪════════════════╡
│ bell │ Clock Tower │
│ pendulum │ Clock Tower │
│ boiler │ Engine Hall │
│ fan │ Engine Hall │
│ pump │ Engine Hall │
│ valve │ Engine Hall │
│ chimney │ Couriers' Yard │
│ kettle │ Couriers' Yard │
╰──────────┴────────────────╯
The CASE turned each hall into 1, 2 or 3, and the sort used those numbers; the numbers themselves never appear in the answer. The second key, name, then ordered the gauges inside each hall.
Worked example 6
Label each gauge's reading as ok when it is from 2 to 100, out of range otherwise, and not read when it is NULL. Show the name and the label, sorted by name.
What we have: The readings, one of them NULL, and the range from 2 to 100, both ends included.
What we need: A column titled check holding not read, ok or out of range, with the gauges sorted by name.
The plan: The long form of CASE: the NULL test first, then BETWEEN for the range, then ELSE; ORDER BY name at the end.
- NULL first:
WHEN reading IS NULL THEN 'not read'. - The range:
WHEN reading BETWEEN 2 AND 100 THEN 'ok', both ends included. - Everything else:
ELSE 'out of range', thenEND AS "check", with the title in double quotes.
query.sql (ledger.db holds the gauges table, now eight gauges)
SELECT name,
CASE
WHEN reading IS NULL THEN 'not read'
WHEN reading BETWEEN 2 AND 100 THEN 'ok'
ELSE 'out of range'
END AS "check"
FROM gauges
ORDER BY name;
Terminal: sqlite3 ledger.db < query.sql
╭──────────┬──────────────╮
│ name │ check │
╞══════════╪══════════════╡
│ bell │ out of range │
│ boiler │ ok │
│ chimney │ not read │
│ fan │ out of range │
│ kettle │ ok │
│ pendulum │ ok │
│ pump │ ok │
│ valve │ ok │
╰──────────┴──────────────╯
bell and fan are out of range, the chimney is not read, and the other five are ok.
Check: By hand: 440.0 and 1200.0 are above 100, so out of range; 2.0, 4.2, 4.2, 88.0 and 96.5 are inside the range; the chimney is NULL. Notice the alias in double quotes, "check": CHECK is one of SQL's own words, and without the quotes SQLite reports a syntax error near "check". Double quotes mark a name, so SQLite takes it as the column's title.
A path that fails: Writing the NULL test as WHEN reading = NULL THEN 'not read'. As lesson 02 showed, = NULL is never true, so the chimney would fall through every WHEN to ELSE and be called out of range.
When you are stuck: CASE
If a row gets the wrong label, read the WHEN tests from the top, as SQLite does, and find the first one that is true for that row.
If a CASE gives NULL, the row matched no WHEN and there is no ELSE. Add an ELSE, or a WHEN for the rows you missed.
A common mistake
Forgetting END. Every CASE ends with the word END, and without it SQLite reports a syntax error near the next word, such as AS or FROM.
Your turn
Write a CASE that says even for gauges with an even id and odd for the rest.Tap to reveal
- id % 2 is 0 for an even id.
CASE WHEN id % 2 = 0 THEN 'even' ELSE 'odd' END
Which label does the first CASE of this section give a reading of exactly 100?Tap to reveal
- 100 is not above 100.
warm: it fails reading > 100 and passes reading > 10.
What does a CASE with no ELSE give for a row that matches no WHEN?Tap to reveal
- Nothing was chosen for it.
NULL.
Did you know?
iif(): a CASE written short
SQLite has a shorter way to write a two-way choice: iif(test, yes, no). Its documentation says iif() is really a short-hand notation for a CASE expression, and generates the same bytecode as CASE WHEN X THEN Y ELSE Z END. It arrived in version 3.32.0, on 2020-05-22, and a later version also allowed the spelling if().
Why it fits here: It answers the topic's question: iif() is a CASE written short, the same work inside.
Sources: SQLite: Built-In Scalar SQL Functions; SQLite: Release History
The short form compares with =
The short form, CASE unit WHEN 'C', is an = test inside. SQLite's documentation says the same NULL-handling rules apply as for an = operator, so a NULL base value never matches a WHEN: it always gets the ELSE, or NULL when there is none. The one difference it names between the two forms: the short form works out the value only once.
Why it fits here: It explains this topic's short form: it is an = test inside, which is why it can never match NULL.
Source: SQLite: SQL Language Expressions
In one line
CASE WHEN test THEN value ... ELSE value END gives each row the value of its first true test; give NULL its own WHEN first, end with END, and use CASE in ORDER BY for an order of your own.
Where it is used
Almost every list on a screen has an ORDER BY behind it, and most long ones have a LIMIT too.
Top lists and newest first
A game's leaderboard is a sort and a limit: ORDER BY score DESC LIMIT 10. A news feed, a chat, or your e-mail shows the newest first, which is ORDER BY sent_at DESC on the time each item arrived. The words on the screen change; the query underneath is this lesson's.
Pages of results
A shop with a lakh of products shows twenty at a time. Page 1 is LIMIT 20, page 2 is LIMIT 20 OFFSET 20, and so on. The database still has to find and sort the rows that OFFSET skips, so page 5000 takes longer than page 1; PostgreSQL's documentation warns that a large OFFSET can be slow. Big sites often fetch the next page by remembering the last row shown instead, with a WHERE such as WHERE id > 120, a trick for later tracks.
Labels and orders of your own
CASE is how a report turns numbers into words a manager can read: in stock, low, sold out. And a to-do app that shows urgent tasks first, then normal ones, then the rest, is sorting by a CASE that gives each priority a number.
| On the screen | In the query |
|---|---|
| Top 10 | ORDER BY score DESC LIMIT 10 |
| Newest first | ORDER BY sent_at DESC |
| Price, low to high | ORDER BY price |
| Page 3, twenty a page | LIMIT 20 OFFSET 40 |
| Urgent first | ORDER BY CASE priority WHEN 'urgent' THEN 1 ELSE 2 END |
| A label beside each number | CASE WHEN stock = 0 THEN 'sold out' ELSE 'in stock' END |
Mistakes and how to find them
A sort can go wrong in the same two ways a filter can: loudly, with an error message, or quietly, with an answer that looks right and is not. This file holds four mistakes: two of each kind.
query.sql (ledger.db holds the gauges table, now eight gauges)
SELECT name FROM gauges ORDER BY name WHERE hall = 'Engine Hall';
SELECT name, reading FROM gauges ORDER BY 'reading' DESC LIMIT 3;
SELECT name FROM gauges OFFSET 2;
SELECT name, reading FROM gauges ORDER BY reading LIMIT 3;
Terminal: sqlite3 ledger.db < query.sql
Parse error near line 1: near "WHERE": syntax error
SELECT name FROM gauges ORDER BY name WHERE hall = 'Engine Hall';
error here ---^
╭────────┬─────────╮
│ name │ reading │
╞════════╪═════════╡
│ boiler │ 96.5 │
│ pump │ 4.2 │
│ fan │ 1200.0 │
╰────────┴─────────╯
Parse error near line 3: near "2": syntax error
SELECT name FROM gauges OFFSET 2;
error here ---^
╭──────────┬─────────╮
│ name │ reading │
╞══════════╪═════════╡
│ chimney │ NULL │
│ pendulum │ 2.0 │
│ pump │ 4.2 │
╰──────────┴─────────╯
Line 1 put ORDER BY before WHERE. The parts of a query have a fixed order, and SQLite stopped at the WHERE it did not expect there.
Line 3 used OFFSET with no LIMIT before it. The error points at the 2, not at OFFSET, and the reason is a surprise. SQLite read the word OFFSET as a second name for the table, the way AS gives a column a second name. Then it could make no sense of the 2. When an error points somewhere odd, look just before it.
Lines 2 and 4 are the dangerous ones. Line 2 put the column's name in single quotes, which makes it a piece of text: every row was sorted by the same word, reading, so nothing moved, and the first three ids came back looking like an answer. Line 4 wanted the three lowest readings, and the chimney, which has no reading at all, took one of the three places, because NULL sorts as the smallest.
The quiet mistakes
| The query | What it really does | What was meant |
|---|---|---|
ORDER BY 'reading' | sorts by a fixed piece of text: no sort | ORDER BY reading |
ORDER BY reading LIMIT 3 | lets NULLs take the first places | ORDER BY reading NULLS LAST LIMIT 3 |
ORDER BY unit, reading DESC | only the reading runs downward | ORDER BY unit DESC, reading DESC, if both should |
SELECT ... LIMIT 3 | any three rows, in no promised order | add an ORDER BY that cannot tie |
LIMIT 10, 5 | skips 10 and keeps 5 | LIMIT 5 OFFSET 10, which says so |
ORDER BY name | every capital before every small letter | ORDER BY lower(name) |
ORDER BY price, price stored as text | '10', '100', '9', as text sorts letter by letter | store numbers in an INTEGER or REAL column |
CASE WHEN reading > 10 ... ELSE 'low' END | calls an unknown reading low | a first WHEN reading IS NULL |
A way to check a sort
- Run the query without its LIMIT first, and look at the whole sorted answer.
- Read the ORDER BY keys from left to right, and say which key puts each row after the one above it.
- Look for rows that tie on every key: they come in no promised order. Add a key that cannot tie.
- Find every NULL in a sort key, and check that it went where you meant.
- Add the LIMIT and OFFSET back last, and count the rows they keep by hand.
The debugging corner: show the sort key as a column
When an order looks wrong, put each sort key in the SELECT list, such as SELECT name, reading IS NULL, reading FROM gauges ORDER BY reading IS NULL, reading;. A CASE in an ORDER BY can be shown the same way, with an alias. You then see the very values the sort compared, row by row.
Quick card
The whole lesson on one card. Come back to it whenever you need a reminder.
query.sql (ledger.db holds the gauges table, now eight gauges)
SELECT name, reading FROM gauges ORDER BY reading DESC NULLS LAST, name LIMIT 3;
Terminal: sqlite3 ledger.db < query.sql
╭────────┬─────────╮
│ name │ reading │
╞════════╪═════════╡
│ fan │ 1200.0 │
│ bell │ 440.0 │
│ boiler │ 96.5 │
╰────────┴─────────╯
| To do this | Write this |
|---|---|
| Sort, lowest first | ORDER BY reading |
| Sort, highest first | ORDER BY reading DESC |
| Several keys, each with its direction | ORDER BY hall, reading DESC |
| Settle ties for good | end with name or id |
| Ignore capitals | ORDER BY lower(unit) |
| Choose where NULLs go | NULLS LAST, NULLS FIRST |
| NULLs last in any database | ORDER BY reading IS NULL, reading |
| Only the first rows | LIMIT 3 |
| A page: page 3, three a page | LIMIT 3 OFFSET 6 |
| A label from tests | CASE WHEN reading > 100 THEN 'high' ELSE 'low' END |
| A label from one value | CASE unit WHEN 'C' THEN 'heat' ELSE 'other' END |
| An order of your own | ORDER BY CASE hall WHEN 'Clock Tower' THEN 1 ELSE 2 END |
Words to know: ORDER BY, ascending, ASC, descending, DESC, sort key, tie, NULLS FIRST, NULLS LAST, LIMIT, OFFSET, page, CASE expression, WHEN, THEN, ELSE, END.
Self-check
Say each answer aloud before you open it.
In which order do the parts of a query come?Tap to reveal
- Five parts, the last one keeps only a few rows.
SELECT, FROM, WHERE, ORDER BY, LIMIT, with OFFSET after LIMIT.
Where does SQLite put NULL in ORDER BY reading, and how do you move it?Tap to reveal
- NULL counts as the smallest.
First, because NULL sorts as the smallest. NULLS LAST moves it to the end.
What does a second sort key do?Tap to reveal
- Think of the pump and the valve.
It only settles the ties the first key leaves.
Which rows does LIMIT 5 OFFSET 10 keep?Tap to reveal
- Skip first, then keep.
Rows 11 to 15 of the sorted answer.
Why give NULL its own WHEN in a CASE?Tap to reveal
- Where else would a NULL row land?
Otherwise the ELSE catches it and gives it a label it does not deserve, such as low.
The story: First things first
By evening each question card ends with an order: by reading, highest first, then by name to settle ties. The page hands back its lines already sorted, and the pump and the valve stand in the same order every time.
A card that asks for the three hottest gets three lines and no more. Another asks for the next three, and gets the fourth, fifth and sixth. A third card sorts the missing readings to the end, where they belong.
The Registrar nods at the neat answers. "Order, and only as much as you need," she says. "Tomorrow we count and add."
Reagents gathered: ORDER BY, DESC, LIMIT, OFFSET, NULLS LAST, CASE.
Sources
- SQLite's documentation (the SQL language, the command-line shell, the file format, the datatypes) (Public domain: all of SQLite's code and documentation (sqlite.org/copyright.html, read 2026-11-21); reused with credit)
- The PostgreSQL documentation (The PostgreSQL Licence, which covers the software and its documentation (its licence page, read 2026-10-26); reused with credit)