Loading

T11 SQL · Lesson 2

SELECT and filtering

Ask a table exactly what you want: choose and compute columns, give them names with AS, keep only the rows that fit with WHERE, combine tests with AND, OR and NOT, match with BETWEEN, IN and LIKE, find the missing values with IS NULL, and drop repeats with DISTINCT.

  • choose columns, compute new ones from them and name them with AS
  • keep only the rows that fit with WHERE and the comparison operators
  • combine tests with AND, OR and NOT, with brackets where they matter
  • match ranges, lists and patterns with BETWEEN, IN and LIKE
  • find missing values with IS NULL, and say why = NULL never finds them
  • drop repeated rows from an answer with DISTINCT
About 70 minutesChecked against SQLite's command-line shell, sqlite3, the "sqlite-tools-linux-x64-3540100.zip" of sqlite.org (the kit compares every SQL block with it, in its sandbox; the page runs the small sqlite3 of plan 34) 3.54.1 (2026-11-21); GNU Bash on the laptop (the kit compares every shell block with it, in a sandbox) 5.3.9 (2026-11-21)Play this lesson's games

The back cover

Asking a table for everything is like asking a librarian for every book in the building when you wanted one shelf. Real questions are narrow: only the Engine Hall's gauges, only the readings above ten, only the names, each once.

These pages make SELECT exact. They compute new columns and name them, and keep only the rows that pass a test with WHERE. They join tests with AND, OR and NOT, and match ranges, lists and patterns. They also meet NULL's strange rule: an unknown value is equal to nothing, not even another unknown one. And they meet the test that finds it anyway.

Before you start

The story: A whole page for one line

Word of the ruled page spreads, and the halls start asking questions. The Engine Hall wants only its own gauges. The Clock Tower wants every gauge that reads above ten. A courier wants the names alone, without the halls and the units.

Each time, a clerk copies out the whole page and hands it over, and the asker has to hunt through it. By noon the hall is full of copied pages, and one of them, copied in a hurry, is missing a line.

Registrar Nadia Folio stops the copying. "Ask the ledger, not your memory," she says, "and ask it exactly. Say which columns you want, and which lines. The page will hand over nothing else."

Lesson 01 asked the gauges table for everything, or for whole columns. That is like asking a librarian for every book in the building when you wanted one shelf. Real questions are narrower: only the Engine Hall's gauges, only the readings above ten, only the names.

This lesson makes SELECT exact. It chooses and computes columns, and names them. It keeps only the rows that pass a test, with WHERE. It joins tests together with AND, OR and NOT, matches ranges, lists and patterns, finds the missing values, and drops repeated rows.

It builds on these ideas. Each one has a tiny example, so you can check that you remember it.

What you already knowA tiny exampleWhere it comes back
SELECT reads columns from a table.SELECT name FROM gauges;Every query of this lesson.
The gauges table of lesson 01.boiler, pump, fan, chimney, pendulumThe rows we filter.
NULL means not known.the chimney's readingIS NULL.
Text in single quotes.'Engine Hall'Comparing with text.
Comparisons in JavaScript.reading > 10SQL's comparisons look the same.
And, or and not in JavaScript.a && b, a || b, !aSQL spells them AND, OR and NOT.
Arithmetic.96.5 * 2Columns computed from others.
Wildcards in bash.ls *.txtLIKE's % and _.
The order of operations.2 + 3 * 4AND before OR.
Reading an error message.near "<": syntax errorMistakes in WHERE.

By the end of this lesson you will be able to:

  • choose columns, compute new ones from them and name them with AS;
  • keep only the rows that fit with WHERE and the comparison operators;
  • combine tests with AND, OR and NOT, with brackets where they matter;
  • match ranges, lists and patterns with BETWEEN, IN and LIKE;
  • find missing values with IS NULL, and say why = NULL never finds them;
  • drop repeated rows from an answer with DISTINCT.

How to follow this lesson

As in lesson 01, each block is a file of SQL, query.sql, and the command sqlite3 ledger.db < query.sql. The file ledger.db already holds lesson 01's gauges table. Press Run, then change the WHERE and run it again: the quickest way to learn a filter is to break it on purpose and watch the answer change.

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

SELECT chooses the columns of an answer and WHERE chooses its rows; this lesson makes both exact.

Choosing and computing columns

At a glance

A SELECT list can hold calculations as well as columns, each worked out afresh for every row.

Arithmetic uses + - * / and %, and two whole numbers divide to a whole number. Two bars, ||, join text end to end. Functions such as upper() and length() take a value and give back another. AS names a column of the answer, which is called an alias. DISTINCT, right after SELECT, keeps each different row once. None of these changes the table itself.

Take a guess: What does SQLite do with the fraction in 7.5 % 2, the remainder of a number that is not whole?

Lesson 01 chose columns by name. A SELECT can do more than pick: each item in its list can be a calculation, worked out afresh for every row. Suppose the Engine Hall wants every reading doubled, to check a new gauge that counts in half-degrees. Nobody needs to change the table. Ask for the calculation:

query.sql (ledger.db holds the gauges table of lesson 01)

SELECT name, reading * 2 FROM gauges;

Terminal: sqlite3 ledger.db < query.sql

╭──────────┬─────────────╮
│   name   │ reading * 2 │
╞══════════╪═════════════╡
│ boiler   │       193.0 │
│ pump     │         8.4 │
│ fan      │      2400.0 │
│ chimney  │ NULL        │
│ pendulum │         4.0 │
╰──────────┴─────────────╯

For each row, SQLite took the reading and multiplied it by 2. The table itself still holds 96.5 for the boiler: the doubling happened only in the answer. And notice the chimney. Its reading is NULL, and NULL times 2 is NULL: a value that is not known, doubled, is still not known. NULL spreads through arithmetic like this every time.

Naming a column with AS

The doubled column came back titled reading * 2, the calculation itself. That is honest but clumsy. The keyword AS gives a column in the answer a name of your choosing, called an alias:

query.sql (ledger.db holds the gauges table of lesson 01)

SELECT name, reading * 2 AS doubled FROM gauges;

Terminal: sqlite3 ledger.db < query.sql

╭──────────┬─────────╮
│   name   │ doubled │
╞══════════╪═════════╡
│ boiler   │   193.0 │
│ pump     │     8.4 │
│ fan      │  2400.0 │
│ chimney  │ NULL    │
│ pendulum │     4.0 │
╰──────────┴─────────╯

Read it aloud: "select the name, and the reading times two as doubled." The alias names only the answer's column. The table has no column called doubled, and never will. An alias is a label on the answer, like a heading written on a photocopy.

The arithmetic operators

OperatorMeansExampleAnswer
+addreading + 197.5 for the boiler
-subtractreading - 195.5
*multiplyreading * 2193.0
/dividereading / 248.25
%the remainder after dividing7 % 21

Division has a trap. When both numbers are whole numbers, SQLite gives a whole-number answer and throws the rest away, as integer division does in many languages. Put a decimal point on either number, and the answer keeps its fraction:

query.sql (ledger.db holds the gauges table of lesson 01)

SELECT name, reading / 2 AS half, 7 / 2 AS whole, 7.0 / 2 AS real FROM gauges WHERE id = 1;

Terminal: sqlite3 ledger.db < query.sql

╭────────┬───────┬───────┬──────╮
│  name  │ half  │ whole │ real │
╞════════╪═══════╪═══════╪══════╡
│ boiler │ 48.25 │     3 │  3.5 │
╰────────┴───────┴───────┴──────╯

The boiler's reading is a real number, 96.5, so half of it kept its fraction, 48.25. But 7 / 2 gave 3, not 3.5, because 7 and 2 are both integers. 7.0 / 2 gave 3.5. The WHERE id = 1 at the end kept the answer to one row; WHERE is the next section.

Joining text with ||

Two bars, ||, join pieces of text end to end. SQL calls this concatenation. It is how you build a sentence out of columns:

query.sql (ledger.db holds the gauges table of lesson 01)

SELECT name || ' in ' || hall AS place FROM gauges;

Terminal: sqlite3 ledger.db < query.sql

╭───────────────────────────╮
│           place           │
╞═══════════════════════════╡
│ boiler in Engine Hall     │
│ pump in Engine Hall       │
│ fan in Engine Hall        │
│ chimney in Couriers' Yard │
│ pendulum in Clock Tower   │
╰───────────────────────────╯

Each row joined three pieces: the name, the text ' in ' with a space on each side, and the hall. A common mistake is to forget those spaces and get boilerinEngine Hall. Another is to use + as JavaScript does: in SQL, + always means adding numbers.

Functions

SQLite has many built-in functions, each a name followed by brackets holding its input. You met typeof() in lesson 01. Two more: upper() turns text into capitals, and length() counts its characters.

query.sql (ledger.db holds the gauges table of lesson 01)

SELECT upper(name) AS big, length(name) AS letters FROM gauges;

Terminal: sqlite3 ledger.db < query.sql

╭──────────┬─────────╮
│   big    │ letters │
╞══════════╪═════════╡
│ BOILER   │       6 │
│ PUMP     │       4 │
│ FAN      │       3 │
│ CHIMNEY  │       7 │
│ PENDULUM │       8 │
╰──────────┴─────────╯

Like every calculation in a SELECT, a function runs once for each row and changes nothing in the table. Lesson 04 adds functions of a different kind, which work across many rows at once.

Dropping repeats with DISTINCT

Ask for the halls, and you get one line per gauge, so the Engine Hall comes back three times:

query.sql (ledger.db holds the gauges table of lesson 01)

SELECT hall FROM gauges;

Terminal: sqlite3 ledger.db < query.sql

╭────────────────╮
│      hall      │
╞════════════════╡
│ Engine Hall    │
│ Engine Hall    │
│ Engine Hall    │
│ Couriers' Yard │
│ Clock Tower    │
╰────────────────╯

To ask "which halls have gauges?", put DISTINCT right after SELECT. It keeps each different row once:

query.sql (ledger.db holds the gauges table of lesson 01)

SELECT DISTINCT hall FROM gauges;

Terminal: sqlite3 ledger.db < query.sql

╭────────────────╮
│      hall      │
╞════════════════╡
│ Engine Hall    │
│ Couriers' Yard │
│ Clock Tower    │
╰────────────────╯

DISTINCT looks at whole rows of the answer, not at single columns. With two columns, SELECT DISTINCT hall, unit keeps every different pair: the Engine Hall in C and the Engine Hall in bar are different rows, so both stay.

Worked example 1

The Clock Tower wants a list of every gauge as a label such as boiler (C), with the column titled label. Write the query.

What we have: The name and unit columns, and the || operator.

What we need: One column, titled label, holding name (unit) for every gauge.

The plan: Join the name, the text ' (', the unit and the text ')'; name the result with AS.

  1. The pieces in order: name, then ' (' with its space, then unit, then ')'.
  2. Join them with ||: name || ' (' || unit || ')'.
  3. Name the answer's column: add AS label.

query.sql (ledger.db holds the gauges table of lesson 01)

SELECT name || ' (' || unit || ')' AS label FROM gauges;

Terminal: sqlite3 ledger.db < query.sql

╭──────────────╮
│    label     │
╞══════════════╡
│ boiler (C)   │
│ pump (bar)   │
│ fan (rpm)    │
│ chimney (C)  │
│ pendulum (s) │
╰──────────────╯

SELECT name || ' (' || unit || ')' AS label FROM gauges;

Check: Every gauge appears once, with its unit in brackets, under the title label. The table is unchanged: run SELECT * FROM gauges; and the columns are as they were.

A path that fails: Writing SELECT name + ' (' + unit + ')' as JavaScript would. SQL's + adds numbers, and text that does not look like a number counts as 0, so every row answers 0.

When you are stuck: calculated columns

If a calculation gives NULL, look for a NULL among its inputs: NULL times anything, and NULL joined to any text, is NULL.

If a division loses its fraction, both numbers were whole numbers; write one of them with a decimal point, such as 7.0.

A common mistake

Thinking AS renames a column of the table. An alias names a column of one answer only; the next query sees the table's own names again.

Your turn

Write a query that lists every gauge's name and its reading plus 10, titled raised.Tap to reveal
  1. A calculation in the SELECT list, then AS.

SELECT name, reading + 10 AS raised FROM gauges;

What does SELECT 9 / 2, 9 % 2; print in its one row?Tap to reveal
  1. Both numbers are whole numbers.
  2. % gives the remainder.

4 and 1: integer division drops the half, and 9 divided by 2 leaves 1 over.

Which units do the gauges use? Write a query that lists each unit once.Tap to reveal
  1. Repeated rows go with one word after SELECT.

SELECT DISTINCT unit FROM gauges; gives C, bar, rpm and s.

Did you know?

The remainder throws fractions away first

SQLite's % operator works only with whole numbers. Its documentation says % casts both of its operands to INTEGER first, and then computes the remainder after dividing the left integer by the right one. So 7.5 % 2 is worked out from 7 and 2, and sqlite3 prints 1.0, not 1.5.

Why it fits here: It answers the topic's question and stretches its arithmetic: % drops the fraction before it divides.

Source: SQLite: SQL Language Expressions

DISTINCT keeps one NULL

When SELECT DISTINCT meets several NULLs, it keeps just one, as if they were equal, though NULL equals nothing. SQLite's page on NULLs says it was changed to do this, making NULLs indistinct for SELECT DISTINCT, to match other engines, and admits that this seems somewhat arbitrary.

Why it fits here: It shows a corner of DISTINCT from this topic: repeated NULLs count as one row, by a choice made for compatibility.

Source: SQLite: NULL Handling in SQLite Versus Other Database Engines

In one line

Each item in a SELECT list can be a column, a calculation or a function, worked out per row; AS names the answer's column, || joins text, whole numbers divide to whole numbers, and DISTINCT drops repeated rows.

Keeping the rows that fit: WHERE

At a glance

WHERE keeps only the rows whose test is true, and drops the rest.

It comes after FROM, so a query reads: which columns, from which table, for which rows. The comparison operators are =, != or <>, <, <=, > and >=. Text goes in single quotes and must match exactly, capital letters included. A test that matches nothing gives an empty answer, which is not an error but the true answer to a question that found no rows at all.

Take a guess: Why does SQL have two ways to write not-equal, and which one is the standard?

SELECT's list chooses the columns. WHERE chooses the rows. It comes after FROM, and it holds a test. SQLite tries the test on every row of the table, keeps the rows where the test is true and drops the rest. Which gauges read above ten?

query.sql (ledger.db holds the gauges table of lesson 01)

SELECT name, reading FROM gauges WHERE reading > 10;

Terminal: sqlite3 ledger.db < query.sql

╭────────┬─────────╮
│  name  │ reading │
╞════════╪═════════╡
│ boiler │    96.5 │
│ fan    │  1200.0 │
╰────────┴─────────╯

Read it aloud: "select the name and reading from gauges where the reading is greater than ten." SQLite went down the table. The boiler's 96.5 passed, and so did the fan's 1200. The pump's 4.2 and the pendulum's 2.0 did not. The chimney's reading is NULL, and NULL is not greater than ten; it is not known, so the row is not kept. The NULL section explains this carefully.

The order of the parts is fixed: SELECT, then FROM, then WHERE. Read together they say: which columns, from which table, for which rows.

The comparison operators

OperatorMeansExampleRows kept
=equal toid = 3the fan
!= or <>not equal tounit != 'C'pump, fan, pendulum
<less thanreading < 10pump, pendulum
<=less than or equal toreading <= 4.2pump, pendulum
>greater thanreading > 10boiler, fan
>=greater than or equal toreading >= 96.5boiler, fan

Two differences from JavaScript catch people. SQL's equals is a single =, not ===. And not-equal has two spellings, != and <>; <> is the one in the SQL standard, and both work in SQLite.

An equals test on the id finds exactly one row, because each id names exactly one row:

query.sql (ledger.db holds the gauges table of lesson 01)

SELECT name, unit FROM gauges WHERE id = 3;

Terminal: sqlite3 ledger.db < query.sql

╭──────┬──────╮
│ name │ unit │
╞══════╪══════╡
│ fan  │ rpm  │
╰──────┴──────╯

Comparing text

A test can compare text too. The text goes in single quotes, as always:

query.sql (ledger.db holds the gauges table of lesson 01)

SELECT name, hall FROM gauges WHERE hall = 'Engine Hall';

Terminal: sqlite3 ledger.db < query.sql

╭────────┬─────────────╮
│  name  │    hall     │
╞════════╪═════════════╡
│ boiler │ Engine Hall │
│ pump   │ Engine Hall │
│ fan    │ Engine Hall │
╰────────┴─────────────╯

Text compared with = must match exactly, letter for letter, and that includes capital letters. Keywords and names ignore case, as lesson 01 showed, but the text inside quotes does not:

query.sql (ledger.db holds the gauges table of lesson 01)

SELECT name FROM gauges WHERE hall = 'engine hall';

Terminal: sqlite3 ledger.db < query.sql

╭──────╮
│ name │
╘══════╛

No row has the hall engine hall in small letters, so the answer is empty: only its title came back. An empty answer is not an error. It is the true answer to a question that matched nothing, and it is worth checking your spelling before believing it.

The opposite question uses != and keeps every row that fails the match:

query.sql (ledger.db holds the gauges table of lesson 01)

SELECT name, hall FROM gauges WHERE hall != 'Engine Hall';

Terminal: sqlite3 ledger.db < query.sql

╭──────────┬────────────────╮
│   name   │      hall      │
╞══════════╪════════════════╡
│ chimney  │ Couriers' Yard │
│ pendulum │ Clock Tower    │
╰──────────┴────────────────╯

Worked example 2

Which gauges read 4.2 or less? Write the query, and check the answer against the table.

What we have: The gauges table, with readings 96.5, 4.2, 1200.0, NULL and 2.0.

What we need: The names and readings of the gauges whose reading is at most 4.2.

The plan: "Or less" includes 4.2 itself, so the test is less than or equal: <=.

  1. The columns: SELECT name, reading. The table: FROM gauges.
  2. The test: WHERE reading <= 4.2, with <= so that the pump's 4.2 itself is kept.

query.sql (ledger.db holds the gauges table of lesson 01)

SELECT name, reading FROM gauges WHERE reading <= 4.2;

Terminal: sqlite3 ledger.db < query.sql

╭──────────┬─────────╮
│   name   │ reading │
╞══════════╪═════════╡
│ pump     │     4.2 │
│ pendulum │     2.0 │
╰──────────┴─────────╯

The pump (4.2) and the pendulum (2.0).

Check: Go down the table by hand: 96.5 is too big, 4.2 is equal and kept, 1200.0 is too big, NULL is not known and dropped, and 2.0 is smaller and kept. Two rows, as SQLite said.

A path that fails: Writing reading < 4.2. The pump's reading is exactly 4.2, which is not less than 4.2, so the pump disappears from the answer.

Worked example 3

Which halls have at least one gauge reading below 100? Name each hall once.

What we have: The gauges table, the halls of its gauges, and DISTINCT from the columns section.

What we need: A list of halls, each once, that have a gauge reading below 100.

The plan: Keep the rows below 100 with WHERE, show only their halls, and drop the repeats with DISTINCT.

  1. First see the halls of the rows that pass the test, repeats and all:

query.sql (ledger.db holds the gauges table of lesson 01)

SELECT hall FROM gauges WHERE reading < 100;

Terminal: sqlite3 ledger.db < query.sql

╭─────────────╮
│    hall     │
╞═════════════╡
│ Engine Hall │
│ Engine Hall │
│ Clock Tower │
╰─────────────╯
  1. The boiler and the pump are both in the Engine Hall, so it appears twice. Add DISTINCT after SELECT:

query.sql (ledger.db holds the gauges table of lesson 01)

SELECT DISTINCT hall FROM gauges WHERE reading < 100;

Terminal: sqlite3 ledger.db < query.sql

╭─────────────╮
│    hall     │
╞═════════════╡
│ Engine Hall │
│ Clock Tower │
╰─────────────╯

The Engine Hall and the Clock Tower.

Check: The rows below 100 are the boiler (96.5), the pump (4.2) and the pendulum (2.0); their halls, each once, are the Engine Hall and the Clock Tower. The Couriers' Yard is missing because its only gauge, the chimney, has no reading.

A path that fails: Putting DISTINCT after WHERE, as in SELECT hall FROM gauges WHERE DISTINCT reading < 100. DISTINCT belongs right after SELECT; anywhere else it is a syntax error.

When you are stuck: WHERE

If an answer comes back empty, test the test: run SELECT * FROM the table and look at the exact values, capitals and spaces included, then compare them with what your WHERE asks for.

If SQLite says no such column after WHERE, you probably left the quotes off a piece of text: WHERE name = boiler looks for a column called boiler.

A common mistake

Writing == or === for equals. SQLite happens to accept ==, but the SQL standard and most databases accept only the single =. Use = always.

Your turn

Write a query for the names of the gauges in the Clock Tower.Tap to reveal
  1. The hall column, and text in single quotes.

SELECT name FROM gauges WHERE hall = 'Clock Tower';

Why does WHERE reading > 10 leave out the chimney?Tap to reveal
  1. What is the chimney's reading?

Its reading is NULL, which is not known, so it is not greater than 10, and the row is not kept.

Write a query for every gauge whose unit is not C.Tap to reveal
  1. Not equal: != or <>.

SELECT name FROM gauges WHERE unit != 'C'; gives pump, fan and pendulum.

Did you know?

Two ways to say not equal

PostgreSQL's documentation says that <> is the standard SQL notation for not equal, and that != is only an alias, converted to <> at a very early stage of parsing. SQLite's documentation lists both too, and adds a second equals: in SQLite, equals can be either = or ==.

Why it fits here: It answers the topic's question: <> is the standard not-equal, and != is a friendlier spelling that databases accept.

Sources: PostgreSQL: Comparison Functions and Operators; SQLite: SQL Language Expressions

Capitals come before small letters

When SQLite compares two pieces of text, it uses a collating function, and every column's is BINARY unless the table says otherwise. BINARY compares text with memcmp(), byte by byte. In those bytes every capital letter comes before every small one, so to SQLite 'Z' is less than 'a', and a test such as name < 'b' keeps every name that starts with a capital.

Why it fits here: It explains why text tests are exact about capitals: SQLite compares the bytes, and a capital's byte differs from a small letter's.

Source: SQLite: Datatypes In SQLite

In one line

WHERE comes after FROM and keeps only the rows whose test is true: = != <> < <= > >=, with text in single quotes matched exactly, capitals included; an empty answer means nothing matched.

Combining tests: AND, OR and NOT

At a glance

AND, OR and NOT join tests together, much as &&, || and ! do in a JavaScript program.

AND keeps a row only when both of its tests are true. OR keeps it when at least one is. NOT turns a test round. When AND and OR appear in one test, SQL works out AND first, just as arithmetic works out times before plus, so a test that means "this, and one of those two" needs brackets around its OR.

Take a guess: Which values does SQLite treat as true when a WHERE test is not a comparison at all?

One test is often not enough. The boiler-keepers want gauges measured in degrees C that read above 50: two tests, and a row must pass both. AND joins two tests so that a row is kept only when both are true:

query.sql (ledger.db holds the gauges table of lesson 01)

SELECT name, unit, reading FROM gauges WHERE unit = 'C' AND reading > 50;

Terminal: sqlite3 ledger.db < query.sql

╭────────┬──────┬─────────╮
│  name  │ unit │ reading │
╞════════╪══════╪═════════╡
│ boiler │ C    │    96.5 │
╰────────┴──────┴─────────╯

Two gauges are measured in C, the boiler and the chimney. The boiler reads 96.5, above 50, so it passes both tests. The chimney's reading is NULL, so its second test is not true, and AND drops it. Only the boiler is left.

OR: either test will do

OR keeps a row when at least one of its tests is true. Which gauges are measured in C or in seconds?

query.sql (ledger.db holds the gauges table of lesson 01)

SELECT name, unit FROM gauges WHERE unit = 'C' OR unit = 's';

Terminal: sqlite3 ledger.db < query.sql

╭──────────┬──────╮
│   name   │ unit │
╞══════════╪══════╡
│ boiler   │ C    │
│ chimney  │ C    │
│ pendulum │ s    │
╰──────────┴──────╯

The boiler and the chimney pass the first test, the pendulum the second. A row that passes both would be kept once, not twice: OR chooses rows, it does not copy them.

NOT: the opposite

NOT turns a test round: true becomes false and false becomes true. NOT hall = 'Engine Hall' keeps the rows that are not in the Engine Hall, the same rows as hall != 'Engine Hall':

query.sql (ledger.db holds the gauges table of lesson 01)

SELECT name, hall FROM gauges WHERE NOT hall = 'Engine Hall';

Terminal: sqlite3 ledger.db < query.sql

╭──────────┬────────────────╮
│   name   │      hall      │
╞══════════╪════════════════╡
│ chimney  │ Couriers' Yard │
│ pendulum │ Clock Tower    │
╰──────────┴────────────────╯
KeywordKeeps a row whenJavaScript's spelling
a AND bboth a and b are truea && b
a OR ba is true, or b is true, or botha || b
NOT aa is false!a

Which goes first: AND or OR?

Mixing AND and OR without brackets is where most filtering mistakes are born. SQL works out AND before OR, as arithmetic does times before plus. Here is a query meant to find the Engine Hall's gauges that read above 4 or are measured in seconds:

query.sql (ledger.db holds the gauges table of lesson 01)

SELECT name FROM gauges WHERE hall = 'Engine Hall' AND reading > 4 OR unit = 's';

Terminal: sqlite3 ledger.db < query.sql

╭──────────╮
│   name   │
╞══════════╡
│ boiler   │
│ pump     │
│ fan      │
│ pendulum │
╰──────────╯

The pendulum has crept in, though it hangs in the Clock Tower. Because AND goes first, SQLite read the test as two groups: (Engine Hall AND above 4) OR (in seconds). The pendulum fails the first group but passes the second, so it is kept.

Brackets make SQLite read the test the way you meant it, exactly as they do in arithmetic:

query.sql (ledger.db holds the gauges table of lesson 01)

SELECT name FROM gauges WHERE hall = 'Engine Hall' AND (reading > 4 OR unit = 's');

Terminal: sqlite3 ledger.db < query.sql

╭────────╮
│  name  │
╞════════╡
│ boiler │
│ pump   │
│ fan    │
╰────────╯

Now every row must be in the Engine Hall, and then pass one of the two inner tests. The pendulum is gone. A memory aid: AND binds tighter, like times; when a query mixes AND with OR, put brackets around the OR.

Worked example 4

Which gauges read more than 2 but less than 100? Write the query, and check each row by hand.

What we have: The readings 96.5, 4.2, 1200.0, NULL and 2.0.

What we need: The gauges whose reading lies strictly between 2 and 100.

The plan: Two tests that must both be true, joined with AND: above 2, and below 100.

  1. The first test: reading > 2. The second: reading < 100.
  2. Both must hold, so join them with AND.

query.sql (ledger.db holds the gauges table of lesson 01)

SELECT name, reading FROM gauges WHERE reading > 2 AND reading < 100;

Terminal: sqlite3 ledger.db < query.sql

╭────────┬─────────╮
│  name  │ reading │
╞════════╪═════════╡
│ boiler │    96.5 │
│ pump   │     4.2 │
╰────────┴─────────╯

The boiler (96.5) and the pump (4.2).

Check: By hand: 96.5 is above 2 and below 100, kept. 4.2, kept. 1200.0 is not below 100. NULL is not known, dropped. 2.0 is not above 2, since it is equal. Two rows.

Another way: The next section writes ranges with BETWEEN. Note that BETWEEN includes both ends, so it would keep the pendulum's 2.0, which this query does not.

A path that fails: Writing reading > 2 AND < 100. Each test needs its own column; SQLite cannot guess which column the second comparison is about, and reports a syntax error near the less-than sign.

When you are stuck: AND, OR and NOT

If an answer has rows that should not be there, look for an OR without brackets next to an AND, and put brackets around the OR.

Test one condition at a time: run the query with only the first test, then only the second, and see which rows each one keeps.

A common mistake

Using OR when you mean AND, in a sentence such as "the gauges in the Engine Hall and the Clock Tower". No gauge stands in both halls at once, so hall = 'Engine Hall' AND hall = 'Clock Tower' keeps nothing. The English word and here means either one: write OR.

Your turn

Write a query for the gauges in the Engine Hall that read less than 10.Tap to reveal
  1. Two tests, both true.

SELECT name FROM gauges WHERE hall = 'Engine Hall' AND reading < 10; gives the pump.

Without running it, which gauges does WHERE unit = 'rpm' OR reading < 3 keep?Tap to reveal
  1. A row needs only one of the two tests.

The fan (rpm) and the pendulum (2.0).

Add brackets to WHERE a OR b AND c so that it means: a or b, and also c.Tap to reveal
  1. AND binds tighter than OR.

WHERE (a OR b) AND c

Did you know?

What counts as true

A WHERE test does not have to be a comparison. SQLite turns whatever the test gives into a number: zero is false, NULL stays NULL, and every other value is true. Its documentation lists the surprises: the text 'english' and the text '0' both count as false, while '1english' counts as true, because it turns into the number 1.

Why it fits here: It shows how this topic's tests are judged: every result becomes a number, and only non-zero numbers keep a row.

Source: SQLite: SQL Language Expressions

When not known is good enough

AND and OR can sometimes answer even with a NULL inside. SQLite's documentation says that, when paired with NULL, AND gives false if the other test is false, and OR gives true if the other test is true. One false is enough to sink an AND, and one true to float an OR, whatever the unknown side holds.

Why it fits here: It joins this topic to NULL: AND and OR still give a firm answer when the known side settles it.

Source: SQLite: SQL Language Expressions

In one line

AND keeps a row when both tests are true, OR when at least one is, NOT turns a test round; AND binds tighter than OR, so put brackets around an OR that sits beside an AND.

Ranges, lists and patterns: BETWEEN, IN and LIKE

At a glance

Three short words stand for common tests: BETWEEN for a range, IN for a list, LIKE for a pattern.

BETWEEN 2 AND 100 keeps both of its ends. IN ('C', 'bar') keeps any value in the list, and NOT IN the rest. LIKE matches text against a pattern in which % stands for any run of characters and _ for exactly one. In SQLite, LIKE ignores capital letters for English letters; in PostgreSQL it does not, and ILIKE ignores them instead.

Take a guess: Does SQLite's LIKE ignore capital letters in every alphabet, or only in some?

Three tests come up so often that SQL gives each one its own short word. None of them can do anything that AND, OR and = cannot; they make a query shorter and easier to read.

BETWEEN: a range, both ends included

reading BETWEEN 2 AND 100 keeps the rows whose reading is from 2 to 100, with both 2 and 100 themselves kept. It means exactly reading >= 2 AND reading <= 100.

query.sql (ledger.db holds the gauges table of lesson 01)

SELECT name, reading FROM gauges WHERE reading BETWEEN 2 AND 100;

Terminal: sqlite3 ledger.db < query.sql

╭──────────┬─────────╮
│   name   │ reading │
╞══════════╪═════════╡
│ boiler   │    96.5 │
│ pump     │     4.2 │
│ pendulum │     2.0 │
╰──────────┴─────────╯

The pendulum's 2.0 is kept, because BETWEEN includes its ends; the AND query of the last section, with > and <, left it out. Write the smaller number first. BETWEEN 100 AND 2 asks for a reading that is at least 100 and at most 2 at the same time, and nothing is.

IN: one of a list

unit IN ('C', 'bar') keeps a row whose unit is any one of the values in the brackets. It means unit = 'C' OR unit = 'bar', and it stays short however long the list grows.

query.sql (ledger.db holds the gauges table of lesson 01)

SELECT name, unit FROM gauges WHERE unit IN ('C', 'bar');

Terminal: sqlite3 ledger.db < query.sql

╭─────────┬──────╮
│  name   │ unit │
╞═════════╪══════╡
│ boiler  │ C    │
│ pump    │ bar  │
│ chimney │ C    │
╰─────────┴──────╯

NOT IN keeps the rest:

query.sql (ledger.db holds the gauges table of lesson 01)

SELECT name, unit FROM gauges WHERE unit NOT IN ('C', 'bar');

Terminal: sqlite3 ledger.db < query.sql

╭──────────┬──────╮
│   name   │ unit │
╞══════════╪══════╡
│ fan      │ rpm  │
│ pendulum │ s    │
╰──────────┴──────╯

LIKE: a pattern

LIKE matches text against a pattern, a piece of text with two special characters in it, called wildcards, much like the * and ? of bash in T6:

WildcardMatchesPatternMatches these names
%any number of characters, even none'p%'pump, pendulum
_exactly one character'_an'fan

Which gauges have names that start with p?

query.sql (ledger.db holds the gauges table of lesson 01)

SELECT name FROM gauges WHERE name LIKE 'p%';

Terminal: sqlite3 ledger.db < query.sql

╭──────────╮
│   name   │
╞══════════╡
│ pump     │
│ pendulum │
╰──────────╯

The p must come first; the % then matches any rest: ump, endulum. Put the % first to match the end of a name instead:

query.sql (ledger.db holds the gauges table of lesson 01)

SELECT name FROM gauges WHERE name LIKE '%er';

Terminal: sqlite3 ledger.db < query.sql

╭────────╮
│  name  │
╞════════╡
│ boiler │
╰────────╯

A % at both ends finds a letter anywhere in the name. Each underscore stands for exactly one character, so '_an' matches a three-letter name ending in an, and nothing longer:

query.sql (ledger.db holds the gauges table of lesson 01)

SELECT name FROM gauges WHERE name LIKE '%n%';

Terminal: sqlite3 ledger.db < query.sql

╭──────────╮
│   name   │
╞══════════╡
│ fan      │
│ chimney  │
│ pendulum │
╰──────────╯

query.sql (ledger.db holds the gauges table of lesson 01)

SELECT name FROM gauges WHERE name LIKE '_an';

Terminal: sqlite3 ledger.db < query.sql

╭──────╮
│ name │
╞══════╡
│ fan  │
╰──────╯

LIKE and capital letters

In SQLite, LIKE ignores the difference between capital and small letters, at least for the letters of English. So LIKE '%yard' finds Couriers' Yard, capital Y and all, where an = test would have needed the capital:

query.sql (ledger.db holds the gauges table of lesson 01)

SELECT name, hall FROM gauges WHERE hall LIKE '%yard';

Terminal: sqlite3 ledger.db < query.sql

╭─────────┬────────────────╮
│  name   │      hall      │
╞═════════╪════════════════╡
│ chimney │ Couriers' Yard │
╰─────────┴────────────────╯

This is one of the places where databases differ. In PostgreSQL, LIKE does care about capitals, and a separate keyword, ILIKE, ignores them. When T12 moves to PostgreSQL, a LIKE that worked here may suddenly find fewer rows. When capitals matter to a question, say so in the query: compare lower(hall) with a pattern written in small letters, and the answer is the same in every database.

Worked example 5

The Couriers' Yard wants every gauge whose name has exactly four letters. Write the query with LIKE.

What we have: The names boiler, pump, fan, chimney and pendulum, and LIKE's two wildcards.

What we need: The names of exactly four characters.

The plan: One underscore matches one character, so four underscores match four, and nothing else is allowed.

  1. Four characters: '____', four underscores and no %.
  2. Without a %, the pattern must match the whole name: four characters exactly.

query.sql (ledger.db holds the gauges table of lesson 01)

SELECT name FROM gauges WHERE name LIKE '____';

Terminal: sqlite3 ledger.db < query.sql

╭──────╮
│ name │
╞══════╡
│ pump │
╰──────╯

Only the pump.

Check: Count the letters: boiler 6, pump 4, fan 3, chimney 7, pendulum 8. Only pump has four.

Another way: WHERE length(name) = 4 gives the same answer with the length function of the columns section, and says what it means more plainly.

A path that fails: Writing '%%%%' for four characters. Each % matches any number of characters, even none, so '%%%%' matches every name.

When you are stuck: LIKE patterns

Read your pattern aloud, one character at a time: % is "anything", _ is "one character", any other letter is itself. 'p%' reads "p, then anything".

Remember that a pattern without % must match the whole text: LIKE 'pump' matches only pump, as = would, apart from capitals.

A common mistake

Using * and ? from bash in a LIKE pattern. LIKE's wildcards are % and _; a * in a pattern matches only a real star.

Your turn

Write a query for the gauges whose reading is from 4 to 1200, both included.Tap to reveal
  1. BETWEEN includes both ends.

SELECT name FROM gauges WHERE reading BETWEEN 4 AND 1200; gives boiler, pump and fan.

Write a query for the gauges in the Engine Hall or the Clock Tower, using IN.Tap to reveal
  1. A list of the two halls, in single quotes.

SELECT name FROM gauges WHERE hall IN ('Engine Hall', 'Clock Tower');

Which names does LIKE '%m%' match?Tap to reveal
  1. An m anywhere in the name.

pump, chimney and pendulum.

Did you know?

Only English letters fold

SQLite's LIKE ignores capitals only for the letters of ASCII, the basic English alphabet. Its documentation gives the example that 'a' LIKE 'A' is true, but 'æ' LIKE 'Æ' is false, because SQLite understands upper and lower case only for ASCII characters by default. Accented letters, such as the ä of German, keep their case.

Why it fits here: It answers the topic's question: LIKE's case rule covers English letters only, so other alphabets match exactly.

Source: SQLite: SQL Language Expressions

A pattern with bash's wildcards

SQLite has a second pattern test for people who know the shell. GLOB works like LIKE but, in the words of its documentation, uses the Unix file globbing syntax for its wildcards: the * and ? of bash. GLOB is also case sensitive, unlike LIKE. So name GLOB 'p*' finds pump and pendulum, while GLOB 'P*' finds nothing.

Why it fits here: It extends this topic's patterns: GLOB matches with the shell's * and ?, and cares about capitals.

Source: SQLite: SQL Language Expressions

In one line

BETWEEN a AND b keeps a range with both ends, IN keeps any value of a list, LIKE matches a pattern where % is any run of characters and _ is exactly one; SQLite's LIKE ignores capitals, PostgreSQL's does not.

Finding missing values: IS NULL

At a glance

A test in SQL has three results, not two: true, false and not known.

Any comparison with NULL gives not known. An unknown value cannot be said to equal anything, not even another unknown one. WHERE keeps only rows whose test is true, so WHERE reading = NULL finds nothing at all. IS NULL asks whether a value is missing, and always answers yes or no. IS NOT NULL finds the rest. A test such as != also drops the NULL rows quietly.

Take a guess: How did SQLite's authors decide how NULL should behave, when the SQL standards left the question unclear?

Which gauges have no reading yet? It seems an easy question, and the obvious query gives the wrong answer:

query.sql (ledger.db holds the gauges table of lesson 01)

SELECT name FROM gauges WHERE reading = NULL;

Terminal: sqlite3 ledger.db < query.sql

╭──────╮
│ name │
╘══════╛

Nothing came back, though the chimney's reading is NULL. No error, no warning: an empty answer that looks right and is wrong. This is one of the best-known traps in SQL, and the reason is worth understanding, not only memorising.

True, false, and not known

Remember what NULL means: not known. Now ask whether the chimney's reading equals NULL. That is asking: is an unknown number equal to another unknown number? Nobody can say yes, and nobody can say no. The honest answer is "not known", and that is exactly what SQL answers: the comparison itself gives NULL.

So a test in SQL has three possible results, not two: true, false and not known. WHERE keeps a row only when its test is true. "Not known" is not true, so the row is dropped. Any comparison with NULL, using =, !=, < or >, gives not known.

You can watch it happen. In SQLite, a comparison shown as a column prints 1 for true and 0 for false, and NULL for not known:

query.sql (ledger.db holds the gauges table of lesson 01)

SELECT NULL = NULL, NULL IS NULL, 1 = 1, 1 = 2;

Terminal: sqlite3 ledger.db < query.sql

╭─────────────┬──────────────┬───────┬───────╮
│ NULL = NULL │ NULL IS NULL │ 1 = 1 │ 1 = 2 │
╞═════════════╪══════════════╪═══════╪═══════╡
│ NULL        │            1 │     1 │     0 │
╰─────────────┴──────────────┴───────┴───────╯

1 = 1 is true, so 1. 1 = 2 is false, so 0. NULL = NULL is not known, so NULL. And the second column shows the way out: IS NULL asks a different question, "is this value missing?", and that question always has a yes or no answer.

IS NULL and IS NOT NULL

query.sql (ledger.db holds the gauges table of lesson 01)

SELECT name, reading FROM gauges WHERE reading IS NULL;

Terminal: sqlite3 ledger.db < query.sql

╭─────────┬─────────╮
│  name   │ reading │
╞═════════╪═════════╡
│ chimney │ NULL    │
╰─────────┴─────────╯

There is the chimney. IS NOT NULL keeps the opposite rows, every gauge whose reading is known:

query.sql (ledger.db holds the gauges table of lesson 01)

SELECT name, reading FROM gauges WHERE reading IS NOT NULL;

Terminal: sqlite3 ledger.db < query.sql

╭──────────┬─────────╮
│   name   │ reading │
╞══════════╪═════════╡
│ boiler   │    96.5 │
│ pump     │     4.2 │
│ fan      │  1200.0 │
│ pendulum │     2.0 │
╰──────────┴─────────╯

A memory aid: NULL is never equal to anything, not even NULL. To find it, ask IS NULL; to find everything else, ask IS NOT NULL.

NULL hides from other tests too

The trap is not only in = NULL. Every test on a column with NULLs drops the NULL rows quietly. Here is a comparison shown as a column, for every gauge:

query.sql (ledger.db holds the gauges table of lesson 01)

SELECT name, reading > 10 AS above FROM gauges;

Terminal: sqlite3 ledger.db < query.sql

╭──────────┬───────╮
│   name   │ above │
╞══════════╪═══════╡
│ boiler   │     1 │
│ pump     │     0 │
│ fan      │     1 │
│ chimney  │ NULL  │
│ pendulum │     0 │
╰──────────┴───────╯

The chimney's line says NULL, not 0. Its reading is not known, so whether it is above 10 is not known either. That is why WHERE reading > 10 dropped the chimney in the WHERE section. It also explains a surprise with !=. "Every gauge except the pump" seems to be reading != 4.2:

query.sql (ledger.db holds the gauges table of lesson 01)

SELECT name, reading FROM gauges WHERE reading != 4.2;

Terminal: sqlite3 ledger.db < query.sql

╭──────────┬─────────╮
│   name   │ reading │
╞══════════╪═════════╡
│ boiler   │    96.5 │
│ fan      │  1200.0 │
│ pendulum │     2.0 │
╰──────────┴─────────╯

The chimney is missing again. Is an unknown reading different from 4.2? Not known, so the row is dropped. If a question means to include the missing values, say so with OR:

Worked example 6

List every gauge except the pump, using its reading of 4.2, and keep the gauges whose reading is not known.

What we have: A test on reading, and one row, the chimney, whose reading is NULL.

What we need: Every gauge whose reading is not 4.2, the chimney included.

The plan: != drops the NULL row, so add it back with OR reading IS NULL.

  1. The first test: reading != 4.2. It keeps the boiler, the fan and the pendulum, and drops the chimney as not known.
  2. Add the missing ones: OR reading IS NULL. The chimney passes this test.

query.sql (ledger.db holds the gauges table of lesson 01)

SELECT name FROM gauges WHERE reading != 4.2 OR reading IS NULL;

Terminal: sqlite3 ledger.db < query.sql

╭──────────╮
│   name   │
╞══════════╡
│ boiler   │
│ fan      │
│ chimney  │
│ pendulum │
╰──────────╯

boiler, fan, chimney and pendulum: four gauges, every one but the pump.

Check: Count: the table has five gauges, and the answer has every one except the pump.

Another way: Ask by name instead, WHERE name != 'pump', since every gauge has a name. Testing a column that is never NULL avoids the problem.

A path that fails: Writing OR reading = NULL for the second test. It is never true, so the chimney stays out.

When you are stuck: NULL

If a row you expected is missing from an answer, check whether the column you tested is NULL in that row: SELECT * and look for NULL.

Say the question in words with "not known" in place of NULL. Is an unknown reading above 10? Not known, so not kept.

A common mistake

Writing = NULL or != NULL. They are always "not known", so = NULL finds nothing and != NULL also finds nothing. Use IS NULL and IS NOT NULL.

Your turn

Write a query for the gauges that have a unit but no reading.Tap to reveal
  1. Two tests on two columns, both true.

SELECT name FROM gauges WHERE unit IS NOT NULL AND reading IS NULL; gives the chimney.

What does SELECT NULL = 5; print in its one row?Tap to reveal
  1. Is an unknown value equal to 5?

NULL: the comparison is not known.

Why does WHERE reading < 50 leave out the chimney, though its reading is not big?Tap to reveal
  1. What is its reading?

Its reading is not known, so whether it is less than 50 is not known, and WHERE keeps only rows whose test is true.

Did you know?

Decided by experiment

SQLite's page on NULLs says the SQL standards seemed ambiguous about how to handle them. So popular SQL engines were tested instead, with a script run by volunteers in May 2002. SQLite had first been written to answer yes to every question in the chart. None of the other engines worked that way, so SQLite was changed to work like Oracle, PostgreSQL and DB2.

Why it fits here: It answers the topic's question: NULL's rules in SQLite came from testing other engines, because the standards were unclear.

Source: SQLite: NULL Handling in SQLite Versus Other Database Engines

A test that never says not known

IS is more than a way to find NULL. SQLite's documentation says IS and IS NOT work like = and != except when one or both sides are NULL. Two NULLs are IS-equal, and a NULL and a value are not. An IS or IS NOT test can never give NULL, so reading IS 4.2 always gives a firm answer.

Why it fits here: It widens this topic's IS NULL: IS compares any two values without ever answering not known.

Source: SQLite: SQL Language Expressions

In one line

A comparison with NULL is not known, never true, so WHERE drops those rows. Find missing values with IS NULL and the rest with IS NOT NULL; add OR column IS NULL when a question must include them.

Where it is used

Nearly every screen that shows you a list is running a filter behind it.

Search boxes and shop filters

Type part of a word into an app's search box, and somewhere a query like WHERE name LIKE '%' || :typed || '%' looks for it. Tick a price range and a few brands on a shopping site, and the filter becomes WHERE price BETWEEN 500 AND 2000 AND brand IN (...). The words on the screen change; the SQL underneath is this lesson's.

Reports

A report is a question with a filter: this month's orders, the customers in Pune, the readings above the safe limit. DISTINCT answers questions such as "which cities do our customers live in?", and AS gives each column of the report a name that a manager can read.

Finding gaps

IS NULL is how people find missing data: the forms left half-filled, the parcels with no delivery date, the gauges nobody has read. Cleaning a table often starts with a count of its NULLs, a query lesson 04 can write.

On the screenIn the query
A search boxLIKE '%word%'
A price sliderBETWEEN low AND high
Tick boxes for brandsIN ('a', 'b', 'c')
"Show only unread"WHERE read_at IS NULL
A list of choices without repeatsSELECT DISTINCT city

Mistakes and how to find them

A filter can go wrong in two ways. It can fail loudly, with an error message. Or, far worse, it can run without complaint and give the wrong rows. This file holds four mistakes: two of each kind.

query.sql (ledger.db holds the gauges table of lesson 01)

SELECT name FROM gauges WHERE hall = Engine;
SELECT name FROM gauges WHERE name LIKE 'p*';
SELECT name FROM gauges WHERE reading > 10 AND < 100;
SELECT name FROM gauges WHERE unit = 'c';

Terminal: sqlite3 ledger.db < query.sql

Parse error near line 1: no such column: Engine
  SELECT name FROM gauges WHERE hall = Engine;
                         error here ---^
╭──────╮
│ name │
╘══════╛
Parse error near line 3: near "<": syntax error
  SELECT name FROM gauges WHERE reading > 10 AND < 100;
                                   error here ---^
╭──────╮
│ name │
╘══════╛

Line 1 forgot the quotes, so SQLite looked for a column called Engine: a loud mistake, easy to fix. Line 3 left the column out of its second comparison: loud again, with the caret at the less-than sign.

Lines 2 and 4 are the dangerous ones. They ran, and answered with empty tables, and an empty table looks like a real answer. Line 2 used bash's * instead of LIKE's %, so it looked for names made of a p and a real star. Line 4 asked for the unit c in small letters, and = is exact; the units are written C.

The quiet mistakes

The queryWhat it really doesWhat was meant
WHERE reading = NULLnever true: finds nothingWHERE reading IS NULL
WHERE a AND b OR c(a AND b) OR cWHERE a AND (b OR c), if that was the question
WHERE reading != 4.2drops the NULL rows tooadd OR reading IS NULL to keep them
WHERE name LIKE 'p*'a p, then a real starWHERE name LIKE 'p%'
WHERE unit = 'c'an exact match, capitals includedWHERE unit = 'C'
SELECT 7 / 23, as both numbers are wholeSELECT 7.0 / 2 for 3.5
SELECT name + unitadds them as numbers: 0SELECT name || unit

A way to check a filter

  1. Run the query without its WHERE first, and look at every row and its values.
  2. Say, for each row, whether it should be in the answer, and why.
  3. Add the WHERE back, one test at a time, and watch which rows each test removes.
  4. Look hard at any NULL in a column you test: it is dropped by every comparison.
  5. Be suspicious of an empty answer: check spelling, capitals and wildcards before you believe it.

The debugging corner: show the test as a column

Put the test itself in the SELECT list, such as SELECT name, reading > 10 FROM gauges;. Each row then shows 1, 0 or NULL: exactly what WHERE sees, 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 of lesson 01)

SELECT name, reading FROM gauges WHERE unit = 'C' AND (reading > 50 OR reading IS NULL);

Terminal: sqlite3 ledger.db < query.sql

╭─────────┬─────────╮
│  name   │ reading │
╞═════════╪═════════╡
│ boiler  │    96.5 │
│ chimney │ NULL    │
╰─────────┴─────────╯
To do thisWrite this
Compute a columnSELECT reading * 2 FROM gauges;
Name a column of the answerSELECT reading * 2 AS doubled ...
Join textname || ' in ' || hall
Keep the rows that pass a test... WHERE reading > 10;
Compare= != <> < <= > >=
Both tests, either test, the oppositeAND, OR, NOT
Group testsa AND (b OR c)
A range, both ends includedBETWEEN 2 AND 100
One of a listIN ('C', 'bar')
A patternLIKE 'p%', LIKE '_an'
Missing valuesIS NULL, IS NOT NULL
Each different row onceSELECT DISTINCT hall FROM gauges;

Words to know: WHERE, comparison operator, AND, OR, NOT, alias, AS, concatenation, function, integer division, BETWEEN, IN, LIKE, wildcard, pattern, IS NULL, DISTINCT, not known.

Self-check

Say each answer aloud before you open it.

In which order do SELECT, FROM and WHERE come, and what does each choose?Tap to reveal
  1. Columns, table, rows.

SELECT chooses the columns, FROM names the table, WHERE chooses the rows.

Why does WHERE reading = NULL find nothing?Tap to reveal
  1. What does a comparison with NULL give?

A comparison with NULL is not known, never true, so WHERE keeps no row. Use IS NULL.

Which goes first, AND or OR?Tap to reveal
  1. Like times and plus.

AND, so put brackets around an OR that sits beside an AND.

What do % and _ match in a LIKE pattern?Tap to reveal
  1. One is many, one is one.

% matches any run of characters, even none; _ matches exactly one character.

What does DISTINCT do?Tap to reveal
  1. Think of the halls.

It keeps each different row of the answer once.

The story: Exactly what was asked

By evening the questions come in on small cards, each one exact: these columns, from the gauges, where the hall is the Engine Hall. A clerk reads the card to the page, and the page hands back only the lines that fit, with only the columns asked for.

One card asks for the gauges whose reading is unknown. The clerk writes it the careful way, is null, because an unknown reading is not equal to anything, not even to another unknown one.

The Registrar reads the answers and nods. "Every question with its own answer," she says. "Tomorrow we put the answers in order."

Reagents gathered: WHERE, AND, LIKE, IS NULL, DISTINCT, AS.

Sources