T11 SQL · Lesson 4
Aggregates and grouping
Turn many rows into one answer: count them with COUNT, add them with SUM, average them with AVG, find the smallest and largest with MIN and MAX, and round the result with ROUND; then split the rows into groups with GROUP BY, one answer per group, and keep only the groups you want with HAVING.
- count rows with COUNT(*), and values with COUNT(column), and say why they differ
- total, average, and find the smallest and largest values with SUM, AVG, MIN and MAX
- explain how aggregates treat NULL, and what they give for no rows at all
- round a result with ROUND
- give one answer per group with GROUP BY
- keep only some groups with HAVING, and say how it differs from WHERE
The back cover
A list of eight gauges is easy to read. A list of eight lakh orders is not. Nobody reads that list; they ask it questions. How many orders came today? What did they add up to? What was the largest, and what was the average? Each answer is one number made from many rows.
These pages turn rows into numbers. They count rows and values with COUNT, add them with SUM, average them with AVG, find the smallest and largest with MIN and MAX, and round the results. Then they split the rows into groups with GROUP BY, one answer per group, and keep only the groups that matter with HAVING.
Before you start
The story: Counting by hand
The halls have stopped asking for lists. They want numbers. How many gauges does the Engine Hall keep? What is the highest reading in the Clock Tower? What does a gauge in the whole works read, on average?
A clerk runs a finger down the page and counts eight lines. A second clerk counts the readings and gets seven, because the chimney's line has none. A third adds the readings on a slate, loses count at the fan's 1200.0, and starts again.
Registrar Nadia Folio closes the slate. "Ask the ledger, not your memory," she says. "It can count, add and compare faster than any finger, and it never loses its place. Tell it what to total, and how to group the lines."
Every query so far has answered with rows: some of the table's rows, some of their columns, in some order. This lesson asks a different kind of question, one whose answer is a single number made from many rows: how many, how much in all, what on average, the smallest, the largest.
The tools are called aggregate functions, because they gather many values into one: COUNT, SUM, AVG, MIN and MAX. Then GROUP BY splits the rows into groups, such as one group per hall, and gives one answer for each group. And HAVING keeps only the groups you want, as WHERE keeps only the rows you want.
The table is the same as in lesson 03: eight gauges in three halls, and the chimney still unread.
query.sql (ledger.db holds the eight gauges of lesson 03)
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 │
╰────┴──────────┴────────────────┴──────┴─────────╯
Count the rows yourself before the lesson does: eight gauges, four of them in the Engine Hall, seven with a reading. Keep those numbers in mind; the first blocks will check them.
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; | WHERE chooses the rows that are counted. |
| ORDER BY and LIMIT. | ORDER BY reading DESC LIMIT 1 | Sorting groups, and a second way to find the largest. |
| NULL is not known. | the chimney's reading | What aggregates do with it. |
| AS names a column of the answer. | COUNT(*) AS gauges | Naming totals. |
| DISTINCT keeps each value once. | SELECT DISTINCT hall | Counting different values. |
| Functions take values and give one back. | lower(unit) | ROUND. |
| Two whole numbers divide to a whole number. | 7 / 2 is 3 | Averages done by hand. |
| Comparisons give true or false. | reading > 100 | The tests in HAVING. |
| A loop that adds up an array in JavaScript. | for (const x of xs) total += x; | SUM does this for you. |
| Grouping things by hand, such as sorting coins into piles. | one pile per coin | GROUP BY. |
By the end of this lesson you will be able to:
- count rows with COUNT(*), and values with COUNT(column), and say why they differ;
- total, average, and find the smallest and largest values with SUM, AVG, MIN and MAX;
- explain how aggregates treat NULL, and what they give for no rows at all;
- round a result with ROUND;
- give one answer per group with GROUP BY;
- keep only some groups with HAVING, and say how it differs from WHERE.
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. Before you run a block, guess the number it will print; the guess is half of the learning.
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
Aggregate functions turn many rows into one value, GROUP BY gives one value per group, and HAVING keeps only the groups you want.
Counting: COUNT
At a glance
COUNT answers the oldest question about any collection: how many?
COUNT(*) counts the rows, whatever they hold. COUNT(column) counts only the values in that column that are not NULL, so it can give a smaller number than COUNT(*). COUNT(DISTINCT column) counts each different value once. WHERE chooses the rows before they are counted, and the count of no rows at all is 0. The answer is one row holding one number. Functions like these, which turn many rows into one value, are called aggregate functions.
Take a guess: Can one query count all the gauges and, beside that, only the hot ones, without a second query?
The simplest question about a table is "how many?". COUNT(*) answers it: it counts the rows.
query.sql (ledger.db holds the eight gauges of lesson 03)
SELECT COUNT(*) FROM gauges;
Terminal: sqlite3 ledger.db < query.sql
╭──────────╮
│ COUNT(*) │
╞══════════╡
│ 8 │
╰──────────╯
Read it aloud: "count every row of gauges." The star inside the brackets means whole rows, whatever they hold. The answer is a table of one row and one column, and its title is the expression itself, COUNT(*). Eight, as you counted by hand.
COUNT is an aggregate function: it takes a whole column of rows and gives back one value. Every function you met in lesson 02, such as upper(), worked on one row at a time and gave one answer per row. An aggregate works on all the rows at once.
Counting values: COUNT(column)
Put a column's name inside the brackets, and COUNT counts the values in that column that are not NULL:
query.sql (ledger.db holds the eight gauges of lesson 03)
SELECT COUNT(reading) FROM gauges;
Terminal: sqlite3 ledger.db < query.sql
╭────────────────╮
│ COUNT(reading) │
╞════════════════╡
│ 7 │
╰────────────────╯
Seven: the chimney's reading is NULL, so it was not counted. This is the clerks' argument from the opening scene. One counted rows and got eight; the other counted readings and got seven. Both were right, because they counted different things.
One more form: COUNT(DISTINCT column) counts the different values, each once, as DISTINCT did in lesson 02. All three can sit in one SELECT list:
query.sql (ledger.db holds the eight gauges of lesson 03)
SELECT COUNT(*), COUNT(reading), COUNT(DISTINCT unit) FROM gauges;
Terminal: sqlite3 ledger.db < query.sql
╭──────────┬────────────────┬──────────────────────╮
│ COUNT(*) │ COUNT(reading) │ COUNT(DISTINCT unit) │
╞══════════╪════════════════╪══════════════════════╡
│ 8 │ 7 │ 5 │
╰──────────┴────────────────┴──────────────────────╯
Five different units: C, bar, rpm, s and Hz. C is used three times and bar twice, but each is counted once.
| You write | It counts | For the gauges |
|---|---|---|
COUNT(*) | every row | 8 |
COUNT(reading) | the values of reading that are not NULL | 7 |
COUNT(DISTINCT unit) | the different values of unit, NULL left out | 5 |
Counting some of the rows
WHERE chooses the rows first, and COUNT counts what is left. How many gauges stand in the Engine Hall?
query.sql (ledger.db holds the eight gauges of lesson 03)
SELECT COUNT(*) FROM gauges WHERE hall = 'Engine Hall';
Terminal: sqlite3 ledger.db < query.sql
╭──────────╮
│ COUNT(*) │
╞══════════╡
│ 4 │
╰──────────╯
A count can have a name, like any column, with AS. Here are the gauges reading above 100, counted under the title hot:
query.sql (ledger.db holds the eight gauges of lesson 03)
SELECT COUNT(*) AS hot FROM gauges WHERE reading > 100;
Terminal: sqlite3 ledger.db < query.sql
╭─────╮
│ hot │
╞═════╡
│ 2 │
╰─────╯
And when no row passes the test? There is no Attic in the works:
query.sql (ledger.db holds the eight gauges of lesson 03)
SELECT COUNT(*) FROM gauges WHERE hall = 'Attic';
Terminal: sqlite3 ledger.db < query.sql
╭──────────╮
│ COUNT(*) │
╞══════════╡
│ 0 │
╰──────────╯
The answer is a row holding 0, not an empty table. A query with an aggregate and no GROUP BY answers with exactly one row, because it is asking one question about the whole set of rows, even an empty set. A count of nothing is zero.
Worked example 1
How many gauges are measured in C, and how many of those have a reading?
What we have: The gauges table; the unit column holds C for three gauges, one of them the unread chimney.
What we need: Two numbers: the gauges in C, and the readings among them.
The plan: Keep the rows in C with WHERE; count the rows with COUNT(*) and the readings with COUNT(reading), in one SELECT.
- The rows:
WHERE unit = 'C', with a capital C, as = is exact. - Every row:
COUNT(*). - Only the readings:
COUNT(reading), which skips NULL.
query.sql (ledger.db holds the eight gauges of lesson 03)
SELECT COUNT(*), COUNT(reading) FROM gauges WHERE unit = 'C';
Terminal: sqlite3 ledger.db < query.sql
╭──────────┬────────────────╮
│ COUNT(*) │ COUNT(reading) │
╞══════════╪════════════════╡
│ 3 │ 2 │
╰──────────┴────────────────╯
3 gauges in C, and 2 of them have a reading.
Check: By hand: the boiler reads 96.5, the kettle 88.0, and the chimney has no reading. Three rows, two values.
A path that fails: Counting with COUNT(reading) alone and calling it the number of gauges. It says 2, and the unread chimney quietly goes missing from the count.
When you are stuck: COUNT
If a count is one less than you expected, ask whether you counted rows or values: COUNT(column) skips the NULLs.
If a count is too large, check the WHERE: COUNT counts every row that WHERE lets through.
A common mistake
Writing COUNT(reading) to count the gauges. Use COUNT(*) for rows, and a column's name only when you mean its values.
Your turn
Write a query that counts the gauges in the Clock Tower.Tap to reveal
- WHERE first, then COUNT(*).
SELECT COUNT(*) FROM gauges WHERE hall = 'Clock Tower'; prints 2.
What does SELECT COUNT(DISTINCT hall) FROM gauges; print?Tap to reveal
- Each different hall once.
3: the Engine Hall, the Clock Tower and the Couriers' Yard.
Why does COUNT(*) WHERE hall = 'Attic' print 0 and not an empty table?Tap to reveal
- How many rows does an aggregate with no GROUP BY give?
An aggregate with no GROUP BY gives one row, and the count of no rows is 0.
Did you know?
Two counts in one pass: FILTER
An aggregate in SQLite can take a FILTER clause. Its documentation says that if a FILTER clause is provided, only the rows for which its test is true are included in the aggregate. So COUNT(*) FILTER (WHERE reading > 100) counts the 2 hot gauges, while a plain COUNT(*) beside it in the same SELECT still counts all 8.
Why it fits here: It answers the topic's question: a FILTER clause lets one aggregate count some rows while another counts all.
DISTINCT works inside other aggregates too
DISTINCT is not only for COUNT. SQLite's documentation says that in any aggregate function that takes a single argument, the argument can be preceded by DISTINCT, and duplicate elements are filtered before they reach the function. SUM(DISTINCT reading) adds the pump's and the valve's 4.2 only once, and gives 1830.7 in place of 1834.9.
Why it fits here: It widens this topic's COUNT(DISTINCT): any one-argument aggregate can drop repeats first, sometimes by mistake.
In one line
COUNT(*) counts rows, COUNT(column) counts the values that are not NULL, and COUNT(DISTINCT column) counts the different values; WHERE chooses the rows first, and a count of nothing is 0.
Adding up: SUM, AVG and ROUND
At a glance
SUM adds a column's values, AVG averages them, and ROUND trims the result to the places you need.
Both SUM and AVG skip NULL. AVG divides by the number of values it found, so a missing reading is left out, not counted as zero. SUM of no rows is NULL, while COUNT is 0; SQLite's own total() gives 0.0 instead. ROUND(x, n) rounds to n places after the point, and a half goes away from zero. SUM of whole numbers stays whole, but AVG always keeps its fraction.
Take a guess: What does ROUND do with a negative number of places, such as ROUND(1234.567, -2)?
SUM adds the values of a column over all the rows, as a loop that adds up an array would. Like COUNT(column), it skips the NULLs.
query.sql (ledger.db holds the eight gauges of lesson 03)
SELECT SUM(reading) FROM gauges;
Terminal: sqlite3 ledger.db < query.sql
╭──────────────╮
│ SUM(reading) │
╞══════════════╡
│ 1834.9 │
╰──────────────╯
The seven readings add up to 1834.9. Adding readings in different units, degrees and bars and seconds together, means nothing in real life; it is only a sum to learn from. A real report would add like with like, such as one hall's temperatures.
AVG gives the average, also called the mean: the sum divided by how many values there are.
query.sql (ledger.db holds the eight gauges of lesson 03)
SELECT AVG(reading) FROM gauges;
Terminal: sqlite3 ledger.db < query.sql
╭────────────────────╮
│ AVG(reading) │
╞════════════════════╡
│ 262.12857142857143 │
╰────────────────────╯
1834.9 ÷ 7 = 262.128..., and SQLite prints the number with all its digits. Notice the 7. AVG skips the chimney entirely: an unknown reading is not a reading of zero. Divide by all eight rows instead, and the chimney counts as a zero:
query.sql (ledger.db holds the eight gauges of lesson 03)
SELECT SUM(reading) / COUNT(*) AS average FROM gauges;
Terminal: sqlite3 ledger.db < query.sql
╭──────────╮
│ average │
╞══════════╡
│ 229.3625 │
╰──────────╯
229.3625 is the average you would get if the chimney read 0. Neither answer is wrong in itself; they answer different questions. But a reader who sees "average reading" expects the first, so use AVG, and say in words that unread gauges were left out.
Rounding: ROUND
262.12857142857143 has more digits than anyone needs. ROUND(x, n) rounds x to n places after the decimal point:
query.sql (ledger.db holds the eight gauges of lesson 03)
SELECT ROUND(AVG(reading), 2) FROM gauges;
Terminal: sqlite3 ledger.db < query.sql
╭──────────────────────╮
│ ROUND(AVG(reading... │
╞══════════════════════╡
│ 262.13 │
╰──────────────────────╯
262.13. The title, though, was cut short with three dots: the box shortens a long title to keep the table narrow. Give the column a name with AS, and the title is short and clear:
query.sql (ledger.db holds the eight gauges of lesson 03)
SELECT ROUND(AVG(reading), 2) AS average FROM gauges;
Terminal: sqlite3 ledger.db < query.sql
╭─────────╮
│ average │
╞═════════╡
│ 262.13 │
╰─────────╯
With no second number, ROUND rounds to a whole number, and still answers with a real number, so it prints a .0. A half goes away from zero, up for a positive number and down for a negative one:
query.sql (ledger.db holds the eight gauges of lesson 03)
SELECT ROUND(2.5), ROUND(3.5), ROUND(-2.5), ROUND(2.4);
Terminal: sqlite3 ledger.db < query.sql
╭────────────┬────────────┬─────────────┬────────────╮
│ ROUND(2.5) │ ROUND(3.5) │ ROUND(-2.5) │ ROUND(2.4) │
╞════════════╪════════════╪═════════════╪════════════╡
│ 3.0 │ 4.0 │ -3.0 │ 2.0 │
╰────────────┴────────────┴─────────────┴────────────╯
When there is nothing to add
COUNT of no rows is 0. SUM and AVG of no rows, though, are NULL: there is no total and no average of nothing. SQLite also has its own function total(), which adds like SUM but gives 0.0 for no rows:
query.sql (ledger.db holds the eight gauges of lesson 03)
SELECT SUM(reading), total(reading), COUNT(*), AVG(reading) FROM gauges WHERE hall = 'Attic';
Terminal: sqlite3 ledger.db < query.sql
╭──────────────┬────────────────┬──────────┬──────────────╮
│ SUM(reading) │ total(reading) │ COUNT(*) │ AVG(reading) │
╞══════════════╪════════════════╪══════════╪══════════════╡
│ NULL │ 0.0 │ 0 │ NULL │
╰──────────────┴────────────────┴──────────┴──────────────╯
The same happens when every value is NULL: SUM over the chimney's row alone is NULL. If a report must show 0 there, use total() in place of SUM().
Whole numbers
Lesson 02 found that two whole numbers divide to a whole number: 7 / 2 is 3. Aggregates are kinder. SUM of whole numbers stays whole, and AVG answers with a real number whenever it has values to average:
query.sql (ledger.db holds the eight gauges of lesson 03)
SELECT SUM(id), AVG(id) FROM gauges;
Terminal: sqlite3 ledger.db < query.sql
╭─────────┬─────────╮
│ SUM(id) │ AVG(id) │
╞═════════╪═════════╡
│ 36 │ 4.5 │
╰─────────┴─────────╯
The ids 1 to 8 add up to 36, and 36 ÷ 8 is 4.5, kept as 4.5, not cut to 4.
Worked example 2
What is the Engine Hall's average reading, rounded to one place after the decimal point?
What we have: The Engine Hall holds four gauges, all read: 96.5, 4.2, 1200.0 and 4.2.
What we need: One number: their average, to one decimal place.
The plan: Keep the Engine Hall's rows with WHERE, take AVG of the reading, round it with ROUND(..., 1), and name it with AS.
- The rows:
WHERE hall = 'Engine Hall'. - The average:
AVG(reading). - One place:
ROUND(AVG(reading), 1), namedAS average.
query.sql (ledger.db holds the eight gauges of lesson 03)
SELECT ROUND(AVG(reading), 1) AS average FROM gauges WHERE hall = 'Engine Hall';
Terminal: sqlite3 ledger.db < query.sql
╭─────────╮
│ average │
╞═════════╡
│ 326.2 │
╰─────────╯
326.2.
Check: By hand: 96.5 + 4.2 + 1200.0 + 4.2 = 1304.9, and 1304.9 ÷ 4 = 326.225, which rounds to 326.2 at one place.
A path that fails: Writing ROUND(AVG(reading)) with no second number. It rounds to a whole number and prints 326.0, losing the place that was asked for.
When you are stuck: SUM, AVG and ROUND
If an average looks too small, check whether you divided by COUNT(*): that counts the NULL rows as zeros. AVG leaves them out.
If a title is cut with three dots, name the column with AS.
A common mistake
Expecting SUM of no rows to be 0. It is NULL; total() gives 0.0.
Your turn
Write a query for the total of the Clock Tower's readings.Tap to reveal
- WHERE first, then SUM.
SELECT SUM(reading) FROM gauges WHERE hall = 'Clock Tower'; prints 442.0.
What does ROUND(7.25, 1) print?Tap to reveal
- A half goes away from zero.
7.3: the 5 in the second place rounds the first place up.
Why are AVG(reading) and SUM(reading) / COUNT(*) different here?Tap to reveal
- What does each one divide by?
AVG divides by the 7 readings; COUNT(*) is 8, so the chimney's missing reading counts as a zero.
Did you know?
A sum of nothing is NULL, by the standard
SQLite's documentation admits that NULL is not normally a helpful result for the sum of no rows. But the SQL standard requires it, and most other engines do it, so SQLite's sum() does the same, to be compatible. Its own total() is offered as a convenient way around this design problem: with no rows, sum() returns NULL and total() returns 0.0.
Why it fits here: It explains this topic's NULL from SUM: the standard asks for it, and total() exists to avoid it.
Negative places: two databases, two answers
SQLite's documentation says that if ROUND's second argument is omitted or negative, it is taken to be 0, so ROUND(1234.567, -2) gives 1235.0. PostgreSQL rounds to the left of the point instead: its documentation gives round(1234.56, -1) as 1230. Both break a tie the same way, though: PostgreSQL says ties are broken by rounding away from zero.
Why it fits here: It answers the topic's question, and shows that a function with the same name can differ between databases.
Sources: SQLite: Built-In Scalar SQL Functions; PostgreSQL: Mathematical Functions and Operators
A sum too big to hold
A whole number in SQLite has a largest value, and SUM can run past it. Its documentation says sum() throws an integer overflow exception if all its inputs are whole numbers or NULL and the total overflows at any point. SQLite's total() never throws that error, because its result is always a floating point value; it gives up a little exactness instead.
Why it fits here: It shows a limit behind this topic's SUM of whole numbers, and another difference between sum() and total().
In one line
SUM adds and AVG averages the values that are not NULL, ROUND(x, n) rounds to n places, and SUM or AVG of no rows is NULL while COUNT is 0.
Smallest and largest: MIN and MAX
At a glance
MIN and MAX find the smallest and the largest value in a column, and they skip NULL.
They work on text as well as numbers, in the same order as ORDER BY, so MIN(name) is the first name from a to z. An aggregate can sit inside a calculation, so MAX(reading) minus MIN(reading) is the spread. MAX tells you the largest value, not whose it is. SQLite has a shortcut for that, and the safe way, in any database, is to sort and keep the first row.
Take a guess: Which row does SQLite take a plain column from, when it stands beside MAX in a query?
MIN gives the smallest value of a column, and MAX the largest. Like the other aggregates, they skip NULL.
query.sql (ledger.db holds the eight gauges of lesson 03)
SELECT MIN(reading), MAX(reading) FROM gauges;
Terminal: sqlite3 ledger.db < query.sql
╭──────────────┬──────────────╮
│ MIN(reading) │ MAX(reading) │
╞══════════════╪══════════════╡
│ 2.0 │ 1200.0 │
╰──────────────┴──────────────╯
The pendulum's 2.0 and the fan's 1200.0. The chimney's NULL is neither: it was left out, though lesson 03 found that ORDER BY puts NULL first. Sorting must place every row; MIN only looks at the values there are.
MIN and MAX work on text too, in the same order as ORDER BY, letter by letter with capitals first:
query.sql (ledger.db holds the eight gauges of lesson 03)
SELECT MIN(name), MAX(name) FROM gauges;
Terminal: sqlite3 ledger.db < query.sql
╭───────────┬───────────╮
│ MIN(name) │ MAX(name) │
╞═══════════╪═══════════╡
│ bell │ valve │
╰───────────┴───────────╯
bell is the first name from a to z, and valve the last. An aggregate can also sit inside a calculation. The gap between the largest and the smallest reading, often called the spread or range, is one subtraction:
query.sql (ledger.db holds the eight gauges of lesson 03)
SELECT MAX(reading) - MIN(reading) AS spread FROM gauges;
Terminal: sqlite3 ledger.db < query.sql
╭────────╮
│ spread │
╞════════╡
│ 1198.0 │
╰────────╯
Which gauge holds the largest?
MAX says the largest reading is 1200.0, but not whose it is. SQLite lets you put a plain column beside a single MIN or MAX, and then takes that column from the row that holds the smallest or largest value:
query.sql (ledger.db holds the eight gauges of lesson 03)
SELECT name, MAX(reading) FROM gauges;
Terminal: sqlite3 ledger.db < query.sql
╭──────┬──────────────╮
│ name │ MAX(reading) │
╞══════╪══════════════╡
│ fan │ 1200.0 │
╰──────┴──────────────╯
The fan. This is SQLite's own rule, though, and it works only beside MIN or MAX. Beside COUNT, a plain column comes from some row, with no meaning at all:
query.sql (ledger.db holds the eight gauges of lesson 03)
SELECT name, COUNT(*) FROM gauges;
Terminal: sqlite3 ledger.db < query.sql
╭────────┬──────────╮
│ name │ COUNT(*) │
╞════════╪══════════╡
│ boiler │ 8 │
╰────────┴──────────╯
The boiler has nothing to do with the count of 8; SQLite just took a row. PostgreSQL refuses both queries, because a plain column beside an aggregate has no single value to show. So the safe way to ask whose reading is largest is lesson 03's: sort, and keep the first row.
max() with several values is another tool
With two or more values inside the brackets, max and min are not aggregates at all. They compare those values within one row:
query.sql (ledger.db holds the eight gauges of lesson 03)
SELECT max(2, 7, 3), min(2, 7, 3);
Terminal: sqlite3 ledger.db < query.sql
╭──────────────┬──────────────╮
│ max(2, 7, 3) │ min(2, 7, 3) │
╞══════════════╪══════════════╡
│ 7 │ 2 │
╰──────────────┴──────────────╯
Same names, different jobs: MAX(reading) looks down a column across many rows, while max(2, 7, 3) looks across the values it is given.
| You write | It looks at | Gives |
|---|---|---|
MAX(reading) | one column, over every row | the largest reading: 1200.0 |
MIN(name) | one column of text | the first name from a to z: bell |
MAX(reading) - MIN(reading) | two aggregates, then a subtraction | the spread: 1198.0 |
max(2, 7, 3) | the values in its brackets, in one row | 7 |
Worked example 3
Which gauge in the Clock Tower reads highest, and what does it read? Answer in a way that works in any database, and check it with SQLite's shortcut.
What we have: The Clock Tower holds the pendulum, at 2.0, and the bell, at 440.0.
What we need: One row: the name and the reading of the Clock Tower's highest gauge.
The plan: The way that works everywhere: keep the Clock Tower's rows, sort by reading, highest first, and keep one row. The shortcut: a name beside MAX.
- The rows:
WHERE hall = 'Clock Tower'. - Highest first, one row:
ORDER BY reading DESC LIMIT 1.
query.sql (ledger.db holds the eight gauges of lesson 03)
SELECT name, reading FROM gauges WHERE hall = 'Clock Tower' ORDER BY reading DESC LIMIT 1;
Terminal: sqlite3 ledger.db < query.sql
╭──────┬─────────╮
│ name │ reading │
╞══════╪═════════╡
│ bell │ 440.0 │
╰──────┴─────────╯
- The shortcut, which only SQLite accepts:
query.sql (ledger.db holds the eight gauges of lesson 03)
SELECT name, MAX(reading) FROM gauges WHERE hall = 'Clock Tower';
Terminal: sqlite3 ledger.db < query.sql
╭──────┬──────────────╮
│ name │ MAX(reading) │
╞══════╪══════════════╡
│ bell │ 440.0 │
╰──────┴──────────────╯
The bell, at 440.0.
Check: Both ways agree, and 440.0 is more than 2.0. If two gauges tied for the top, the sort would need a second key, such as the name, to choose between them.
A path that fails: Writing SELECT name, COUNT(*) ... or another aggregate beside the name, and trusting the name. Only MIN and MAX choose the row the name comes from.
When you are stuck: MIN and MAX
If MIN of a column is not the first row of ORDER BY, look for a NULL: ORDER BY puts it first, MIN skips it.
If you need the row that holds the largest value, sort with ORDER BY ... DESC and keep it with LIMIT 1.
A common mistake
Trusting a plain column beside COUNT, SUM or AVG. Its value comes from some row of the table, not from anything the aggregate found.
Your turn
Write a query for the Engine Hall's smallest and largest readings.Tap to reveal
- WHERE, then MIN and MAX in one SELECT.
SELECT MIN(reading), MAX(reading) FROM gauges WHERE hall = 'Engine Hall'; prints 4.2 and 1200.0.
What does SELECT MAX(unit) FROM gauges; print?Tap to reveal
- Text, with capitals before small letters.
s: the small letters come after the capitals, and s comes after bar and rpm.
What is the difference between MAX(reading) and max(4, reading)?Tap to reveal
- One looks down a column, one looks along a row.
MAX(reading) is the largest reading over all rows; max(4, reading) gives, for each row, the larger of 4 and that row's reading.
Did you know?
SQLite's bare columns
A column in an aggregate query that is neither grouped nor inside an aggregate is called a bare column. SQLite's documentation says you usually do not know which input row such a column comes from. With exactly one min() or max() in the query, though, every bare column takes its value from a row that holds that minimum or maximum. That is why SELECT name, MAX(reading) names the fan.
Why it fits here: It answers the topic's question: beside a single MIN or MAX, a bare column comes from the row holding that value.
Source: SQLite: SELECT
One name, two functions
SQLite's documentation notes that max() is a simple function when it has two or more arguments, and an aggregate when it has only one. The two treat NULL differently. MAX(reading) skips the chimney's NULL, but the many-argument max() returns NULL if any of its arguments is NULL, so max(2, NULL) is NULL.
Why it fits here: It sharpens this topic's two kinds of max: one looks down a column and skips NULL, the other looks along a row and does not.
In one line
MIN and MAX give the smallest and largest values of a column, skipping NULL, for numbers and text alike; to know whose value it is, sort with ORDER BY and LIMIT 1.
One answer per group: GROUP BY
At a glance
GROUP BY splits the rows into groups, one for each different value of a column, and the aggregates then give one answer per group.
Picture sorting coins into piles and counting each pile. A query can group by one column, by several, or by an expression. Every other column in its SELECT list must be grouped or inside an aggregate; otherwise SQLite quietly picks some row's value. WHERE removes rows before the groups are made, so a group can vanish. The groups come in no promised order, so add ORDER BY.
Take a guess: Can one query give a total for each hall and also a grand total for the whole works?
So far each aggregate has answered one question about all the rows. Often the question is "how many in each hall?": one answer for every hall. GROUP BY does that. It puts the rows into groups, one group for each different value of a column, and the aggregates then work on each group separately.
query.sql (ledger.db holds the eight gauges of lesson 03)
SELECT hall, COUNT(*) FROM gauges GROUP BY hall;
Terminal: sqlite3 ledger.db < query.sql
╭────────────────┬──────────╮
│ hall │ COUNT(*) │
╞════════════════╪══════════╡
│ Clock Tower │ 2 │
│ Couriers' Yard │ 2 │
│ Engine Hall │ 4 │
╰────────────────┴──────────╯
Read it aloud: "for each hall, the hall and its count of rows." Picture sorting coins into piles, one pile per kind of coin, then counting each pile. The eight rows became three piles: two gauges in the Clock Tower, two in the Couriers' Yard, four in the Engine Hall. Each group gives one row of the answer.
Every aggregate of this lesson works per group. One query can make a small report:
query.sql (ledger.db holds the eight gauges of lesson 03)
SELECT hall, COUNT(*) AS gauges, MAX(reading) AS highest, ROUND(AVG(reading), 1) AS average FROM gauges GROUP BY hall ORDER BY hall;
Terminal: sqlite3 ledger.db < query.sql
╭────────────────┬────────┬─────────┬─────────╮
│ hall │ gauges │ highest │ average │
╞════════════════╪════════╪═════════╪═════════╡
│ Clock Tower │ 2 │ 440.0 │ 221.0 │
│ Couriers' Yard │ 2 │ 88.0 │ 88.0 │
│ Engine Hall │ 4 │ 1200.0 │ 326.2 │
╰────────────────┴────────┴─────────┴─────────╯
Look at the Couriers' Yard: two gauges, but an average of 88.0, the kettle's reading alone, as AVG skips the chimney's NULL.
The groups came back in alphabetical order, as SQLite sorted the halls to make the groups. That order is not promised, so the report says ORDER BY hall. ORDER BY can also sort by an aggregate. Here the units are sorted by how many gauges use them, most first:
query.sql (ledger.db holds the eight gauges of lesson 03)
SELECT unit, COUNT(*) AS gauges FROM gauges GROUP BY unit ORDER BY gauges DESC, unit;
Terminal: sqlite3 ledger.db < query.sql
╭──────┬────────╮
│ unit │ gauges │
╞══════╪════════╡
│ C │ 3 │
│ bar │ 2 │
│ Hz │ 1 │
│ rpm │ 1 │
│ s │ 1 │
╰──────┴────────╯
Groups of several columns
GROUP BY can take a list of columns, and then each different combination is a group: one for each hall and unit that appear together.
query.sql (ledger.db holds the eight gauges of lesson 03)
SELECT hall, unit, COUNT(*) AS gauges FROM gauges GROUP BY hall, unit ORDER BY hall, unit;
Terminal: sqlite3 ledger.db < query.sql
╭────────────────┬──────┬────────╮
│ hall │ unit │ gauges │
╞════════════════╪══════╪════════╡
│ Clock Tower │ Hz │ 1 │
│ Clock Tower │ s │ 1 │
│ Couriers' Yard │ C │ 2 │
│ Engine Hall │ C │ 1 │
│ Engine Hall │ bar │ 2 │
│ Engine Hall │ rpm │ 1 │
╰────────────────┴──────┴────────╯
The Engine Hall split into three groups: one gauge in C, two in bar, one in rpm. A group can also be made by an expression. Group by whether the reading is missing, and the gauges fall into two piles:
query.sql (ledger.db holds the eight gauges of lesson 03)
SELECT reading IS NULL AS unread, COUNT(*) AS gauges FROM gauges GROUP BY reading IS NULL;
Terminal: sqlite3 ledger.db < query.sql
╭────────┬────────╮
│ unread │ gauges │
╞════════╪════════╡
│ 0 │ 7 │
│ 1 │ 1 │
╰────────┴────────╯
A column that is not grouped
Here is a query that looks reasonable and is not:
query.sql (ledger.db holds the eight gauges of lesson 03)
SELECT hall, name, COUNT(*) FROM gauges GROUP BY hall;
Terminal: sqlite3 ledger.db < query.sql
╭────────────────┬──────────┬──────────╮
│ hall │ name │ COUNT(*) │
╞════════════════╪══════════╪══════════╡
│ Clock Tower │ pendulum │ 2 │
│ Couriers' Yard │ chimney │ 2 │
│ Engine Hall │ boiler │ 4 │
╰────────────────┴──────────┴──────────╯
Each hall has several names, but the answer has room for one per group, so SQLite picked one from some row of the group. The pendulum stands for the Clock Tower by chance; the bell has the same right. The rule to follow: every column in the SELECT list of a grouped query is either in the GROUP BY or inside an aggregate. PostgreSQL enforces that rule with an error; SQLite quietly picks a row.
WHERE comes first
WHERE chooses rows before they are grouped. Count, for each hall, its gauges reading above 100:
query.sql (ledger.db holds the eight gauges of lesson 03)
SELECT hall, COUNT(*) AS hot FROM gauges WHERE reading > 100 GROUP BY hall ORDER BY hall;
Terminal: sqlite3 ledger.db < query.sql
╭─────────────┬─────╮
│ hall │ hot │
╞═════════════╪═════╡
│ Clock Tower │ 1 │
│ Engine Hall │ 1 │
╰─────────────┴─────╯
The Couriers' Yard is missing, not shown with a 0. WHERE removed both of its rows, so no group of the Couriers' Yard was ever made, and a group that does not exist gives no row.
Worked example 4
For each hall, how many of its gauges have no reading? Sort the halls by name.
What we have: The gauges table; only the chimney, in the Couriers' Yard, has no reading.
What we need: One row per hall: the hall and its count of unread gauges, 0 included.
The plan: Group by hall; in each group, count the rows with COUNT(*) and the readings with COUNT(reading). The difference is the number of NULLs.
- One group per hall:
GROUP BY hall. - Rows minus readings:
COUNT(*) - COUNT(reading), namedAS unread. - Halls by name:
ORDER BY hall.
query.sql (ledger.db holds the eight gauges of lesson 03)
SELECT hall, COUNT(*) - COUNT(reading) AS unread FROM gauges GROUP BY hall ORDER BY hall;
Terminal: sqlite3 ledger.db < query.sql
╭────────────────┬────────╮
│ hall │ unread │
╞════════════════╪════════╡
│ Clock Tower │ 0 │
│ Couriers' Yard │ 1 │
│ Engine Hall │ 0 │
╰────────────────┴────────╯
The Couriers' Yard has 1 unread gauge; the Clock Tower and the Engine Hall have 0.
Check: By hand: the Couriers' Yard holds the chimney (no reading) and the kettle (88.0), so 2 rows and 1 reading; the other halls have a reading on every row.
A path that fails: Writing WHERE reading IS NULL GROUP BY hall with COUNT(*). It counts the unread gauges correctly, but the halls with none vanish from the answer, as WHERE left them no rows.
When you are stuck: GROUP BY
If a grouped answer has too few rows, look at the WHERE: a group whose rows were all removed does not appear at all.
If a column's value in a grouped answer looks random, it is neither grouped nor inside an aggregate. Add it to GROUP BY, or drop it.
A common mistake
Expecting the groups in a particular order. Add ORDER BY whenever the order matters, as with any answer.
Your turn
Write a query for the number of gauges of each unit, sorted by unit.Tap to reveal
- GROUP BY unit, COUNT(*), ORDER BY unit.
SELECT unit, COUNT(*) FROM gauges GROUP BY unit ORDER BY unit; gives C 3, Hz 1, bar 2, rpm 1, s 1, the capitals first.
How many rows does SELECT hall, unit, COUNT(*) FROM gauges GROUP BY hall, unit; give?Tap to reveal
- One row per hall and unit that appear together.
6, as the table above shows.
Why is SELECT hall, name, COUNT(*) FROM gauges GROUP BY hall; a bad query?Tap to reveal
- How many names does a hall have?
name is neither grouped nor inside an aggregate, so SQLite shows a name from some row of each group, which means nothing.
Did you know?
PostgreSQL's rule, and its exception
PostgreSQL turns SQLite's quiet guess into an error. Its documentation says that in a grouped table, columns not listed in GROUP BY cannot be referenced except in aggregate expressions. There is one exception: if the group is the table's primary key, other columns of that table are functionally dependent on it, since each key has exactly one row, and so they may be shown.
Why it fits here: It sets this topic's rule beside a real database that enforces it, with the sensible exception it allows.
Source: PostgreSQL: Table Expressions
Subtotals and a grand total: ROLLUP
PostgreSQL can give several levels of totals in one query. ROLLUP(e1, e2, ...) groups by the whole list and by every shorter beginning of it, ending with the empty list, which is one group of everything. Its documentation says this is commonly used for hierarchical data, such as total salary by department, by division and company-wide.
Why it fits here: It answers the topic's question: with ROLLUP, one query gives each group's total and the grand total too.
Source: PostgreSQL: Table Expressions
In one line
GROUP BY makes one group per different value, or combination of values, and the aggregates give one answer per group; every other column must be grouped or inside an aggregate, and WHERE removes rows before the groups are made.
Choosing groups: HAVING
At a glance
HAVING keeps the groups that pass a test, as WHERE keeps the rows that pass one.
It comes after GROUP BY and is checked once the groups are made, so its test can use aggregates, such as COUNT(*) > 2. WHERE runs on rows before grouping and cannot use them: SQLite calls that a misuse of aggregate. One query can use both. The parts of a query always come in one order: SELECT, FROM, WHERE, GROUP BY, HAVING, ORDER BY, LIMIT.
Take a guess: Can HAVING be used in a query that has no GROUP BY at all?
WHERE keeps the rows that pass a test. HAVING keeps the groups that pass one. It comes after GROUP BY, and its test can use aggregates, as it is checked once the groups are made. Which halls keep more than two gauges?
query.sql (ledger.db holds the eight gauges of lesson 03)
SELECT hall, COUNT(*) FROM gauges GROUP BY hall HAVING COUNT(*) > 2;
Terminal: sqlite3 ledger.db < query.sql
╭─────────────┬──────────╮
│ hall │ COUNT(*) │
╞═════════════╪══════════╡
│ Engine Hall │ 4 │
╰─────────────┴──────────╯
Read it aloud: "for each hall, its count, keeping only the halls having more than two gauges." The three groups were made and counted; then HAVING dropped the Clock Tower and the Couriers' Yard, with two gauges each.
WHERE and HAVING together
The two tests do different jobs at different times. WHERE works on rows, before grouping; HAVING works on groups, after. One query can use both: which halls have at least two gauges reading above 10?
query.sql (ledger.db holds the eight gauges of lesson 03)
SELECT hall, COUNT(*) AS hot FROM gauges WHERE reading > 10 GROUP BY hall HAVING COUNT(*) >= 2;
Terminal: sqlite3 ledger.db < query.sql
╭─────────────┬─────╮
│ hall │ hot │
╞═════════════╪═════╡
│ Engine Hall │ 2 │
╰─────────────┴─────╯
Step by step: WHERE kept the four rows above 10: the boiler, the fan, the kettle and the bell. GROUP BY made three groups of them: the Engine Hall with two, the Couriers' Yard with one, the Clock Tower with one. HAVING kept the groups with at least two: the Engine Hall.
An aggregate cannot go in WHERE, because when WHERE runs there are no groups yet to count:
query.sql (ledger.db holds the eight gauges of lesson 03)
SELECT hall FROM gauges WHERE COUNT(*) > 2 GROUP BY hall;
Terminal: sqlite3 ledger.db < query.sql
Parse error near line 1: misuse of aggregate: COUNT()
SELECT hall FROM gauges WHERE COUNT(*) > 2 GROUP BY hall;
error here ---^
"Misuse of aggregate" is SQLite's way of saying: this test needs groups, so it belongs in HAVING.
| WHERE | HAVING | |
|---|---|---|
| Tests | rows | groups |
| Runs | before GROUP BY | after GROUP BY |
| Can use aggregates | no | yes |
| Example | WHERE reading > 10 | HAVING COUNT(*) > 2 |
Names in HAVING
SQLite lets HAVING use a name given with AS:
query.sql (ledger.db holds the eight gauges of lesson 03)
SELECT hall, COUNT(*) AS n FROM gauges GROUP BY hall HAVING n > 2;
Terminal: sqlite3 ledger.db < query.sql
╭─────────────┬───╮
│ hall │ n │
╞═════════════╪═══╡
│ Engine Hall │ 4 │
╰─────────────┴───╯
PostgreSQL's documentation says the opposite for its own HAVING: a name from the SELECT list cannot be used there, and the expression must be written out. Writing HAVING COUNT(*) > 2 works in both.
The order of the parts
A query now has up to seven parts, and they always come in this order. It is also, roughly, the order in which the database works through them, except SELECT, which picks the columns near the end:
| Part | What it does |
|---|---|
SELECT | chooses the columns and the aggregates |
FROM | names the table |
WHERE | keeps the rows that pass a test |
GROUP BY | puts the rows into groups |
HAVING | keeps the groups that pass a test |
ORDER BY | sorts the answer |
LIMIT | keeps the first rows |
Worked example 5
Which halls have an average known reading above 200? Show each hall with its average to one place, highest first.
What we have: The halls' averages from the report: the Clock Tower 221.0, the Couriers' Yard 88.0, the Engine Hall 326.2.
What we need: The halls whose average is above 200, with their averages, highest first.
The plan: Group by hall; keep the groups with HAVING AVG(reading) > 200; show ROUND(AVG(reading), 1) and sort by it.
- One group per hall:
GROUP BY hall. - Keep the warm halls:
HAVING AVG(reading) > 200, an aggregate, so it belongs in HAVING. - Show and sort:
ROUND(AVG(reading), 1) AS averageandORDER BY average DESC.
query.sql (ledger.db holds the eight gauges of lesson 03)
SELECT hall, ROUND(AVG(reading), 1) AS average FROM gauges GROUP BY hall HAVING AVG(reading) > 200 ORDER BY average DESC;
Terminal: sqlite3 ledger.db < query.sql
╭─────────────┬─────────╮
│ hall │ average │
╞═════════════╪═════════╡
│ Engine Hall │ 326.2 │
│ Clock Tower │ 221.0 │
╰─────────────┴─────────╯
The Engine Hall, at 326.2, and the Clock Tower, at 221.0.
Check: The Couriers' Yard's average is the kettle's 88.0 alone, below 200, so HAVING dropped it.
A path that fails: Writing WHERE AVG(reading) > 200. There are no groups yet when WHERE runs, and SQLite stops with misuse of aggregate.
Worked example 6
Which units are used by more than one gauge, and by how many? Most used first.
What we have: Five different units; C and bar appear more than once.
What we need: Each unit used by two or more gauges, with its count, highest count first.
The plan: Group by unit, count each group, keep the groups with HAVING COUNT(*) > 1, and sort by the count.
- One group per unit:
GROUP BY unit. - Count each:
COUNT(*) AS gauges. - Keep the shared units:
HAVING COUNT(*) > 1; sort withORDER BY gauges DESC.
query.sql (ledger.db holds the eight gauges of lesson 03)
SELECT unit, COUNT(*) AS gauges FROM gauges GROUP BY unit HAVING COUNT(*) > 1 ORDER BY gauges DESC;
Terminal: sqlite3 ledger.db < query.sql
╭──────┬────────╮
│ unit │ gauges │
╞══════╪════════╡
│ C │ 3 │
│ bar │ 2 │
╰──────┴────────╯
C, used by 3 gauges, and bar, used by 2.
Check: By hand: C for the boiler, chimney and kettle; bar for the pump and valve; rpm, s and Hz once each. The chimney counts here, as COUNT(*) counts rows.
Another way: Without HAVING, add LIMIT 2 after the ORDER BY. It gives the same two rows here, but only by luck: HAVING says what is meant, more than one gauge.
When you are stuck: HAVING
If SQLite reports misuse of aggregate, move the test with the aggregate from WHERE to HAVING.
If a group you expected is missing, run the query without HAVING first, and read each group's numbers.
A common mistake
Using HAVING for a test on single rows, such as HAVING hall = 'Engine Hall'. It works when the column is grouped, but the test is about rows, not groups, and WHERE says so.
Your turn
Write a query for the halls whose highest reading is above 400.Tap to reveal
- GROUP BY hall, then HAVING MAX(reading) > 400.
SELECT hall, MAX(reading) FROM gauges GROUP BY hall HAVING MAX(reading) > 400; gives the Clock Tower (440.0) and the Engine Hall (1200.0).
Where does HAVING go: before or after GROUP BY?Tap to reveal
- It tests groups.
After GROUP BY, and before ORDER BY.
Why can WHERE not test COUNT(*)?Tap to reveal
- What exists when WHERE runs?
WHERE runs on rows before they are grouped, so there are no groups to count yet.
Did you know?
HAVING without GROUP BY, since 2022
SQLite once allowed HAVING only beside GROUP BY. Its list of changes says the HAVING clause is now allowed on any aggregate query, even one with no GROUP BY clause, in the release built on 2022-06-25. That is why HAVING placed before GROUP BY fails at the GROUP: SQLite reads the HAVING as a test of the whole table first.
Why it fits here: It answers the topic's question, and explains the error that HAVING before GROUP BY gives in this lesson.
Source: SQLite: Release History
No nicknames in PostgreSQL's HAVING
SQLite lets HAVING use a name given with AS, such as HAVING n > 2. PostgreSQL's documentation says an output column's name can be used in ORDER BY and GROUP BY, but not in WHERE or HAVING; there the expression must be written out. HAVING COUNT(*) > 2 works in both.
Why it fits here: It shows why this topic writes the aggregate out in HAVING: the short name is SQLite's own convenience.
Source: PostgreSQL: SELECT
SQLite moves row tests out of HAVING
A test on a grouped column, such as HAVING hall = 'Engine Hall', is really about rows. SQLite spots this by itself. Its list of changes says it transfers any terms of the HAVING clause that use only columns mentioned in GROUP BY over to the WHERE clause, for faster processing, so fewer rows are grouped at all.
Why it fits here: It shows the WHERE and HAVING split of this topic from the inside: the database moves row tests to WHERE itself.
Source: SQLite: Release History
In one line
HAVING keeps the groups that pass a test, after GROUP BY, and can use aggregates; WHERE keeps rows before grouping and cannot; the parts run SELECT, FROM, WHERE, GROUP BY, HAVING, ORDER BY, LIMIT.
Where it is used
Wherever a screen shows a number made from many records, an aggregate is working behind it.
Dashboards and reports
A shop's dashboard shows today's orders, COUNT(*), today's takings, SUM(amount), and the average bill, AVG(amount). A school's report card shows each subject's highest and lowest marks with MAX and MIN. A monthly report is a GROUP BY: sales per month, per city, per product.
Counts beside names
The small number beside your inbox is COUNT(*) of the unread messages. A shopping site's "Electronics (1284)" beside each category is a GROUP BY category with a count. A poll's results are votes grouped by choice.
Finding the unusual
HAVING finds the groups that stand out: customers with more than ten orders this month, products returned more than five times, cities where the average delivery takes over three days. Data checks use it too: GROUP BY email HAVING COUNT(*) > 1 finds the e-mail addresses that were entered twice.
| On the screen | In the query |
|---|---|
| Today's orders | SELECT COUNT(*) FROM orders WHERE day = '2026-11-21' |
| Total takings | SELECT SUM(amount) FROM orders |
| Average rating, one place | SELECT ROUND(AVG(stars), 1) FROM reviews |
| Products per category | SELECT category, COUNT(*) FROM products GROUP BY category |
| Accounts entered twice | SELECT email FROM users GROUP BY email HAVING COUNT(*) > 1 |
Mistakes and how to find them
Aggregates fail in the same two ways as filters and sorts: loudly, with an error, or quietly, with a number that looks right. This file holds four mistakes, two of each kind.
query.sql (ledger.db holds the eight gauges of lesson 03)
SELECT hall, COUNT(*) FROM gauges WHERE COUNT(*) > 2 GROUP BY hall;
SELECT COUNT(reading) AS gauges FROM gauges;
SELECT hall, COUNT(*) FROM gauges HAVING COUNT(*) > 2 GROUP BY hall;
SELECT SUM(reading) / COUNT(*) AS average FROM gauges;
Terminal: sqlite3 ledger.db < query.sql
Parse error near line 1: misuse of aggregate: COUNT()
SELECT hall, COUNT(*) FROM gauges WHERE COUNT(*) > 2 GROUP BY hall;
error here ---^
╭────────╮
│ gauges │
╞════════╡
│ 7 │
╰────────╯
Parse error near line 3: near "GROUP": syntax error
CT hall, COUNT(*) FROM gauges HAVING COUNT(*) > 2 GROUP BY hall;
error here ---^
╭──────────╮
│ average │
╞══════════╡
│ 229.3625 │
╰──────────╯
Line 1 put an aggregate in WHERE. There are no groups when WHERE runs, and SQLite says so: misuse of aggregate. The test belongs in HAVING.
Line 3 put HAVING before GROUP BY. SQLite read HAVING as a test on the whole table, which it allows, and then met a GROUP BY where none can stand. The parts have a fixed order: GROUP BY, then HAVING.
Lines 2 and 4 are the quiet ones. Line 2 meant to count the gauges and counted the readings: 7, not 8. Line 4 meant the average reading and divided by every row, so the unread chimney counted as a zero reading: 229.3625, not 262.13. Both answers look like real numbers, which is what makes them dangerous.
The quiet mistakes
| The query | What it really does | What was meant |
|---|---|---|
COUNT(reading) | counts the readings, not the gauges | COUNT(*) |
SUM(reading) / COUNT(*) | treats each NULL as 0 | AVG(reading) |
SUM(reading) of no rows | NULL, not 0 | total(reading) for 0.0 |
SELECT hall, name, COUNT(*) ... GROUP BY hall | a name from some row of each group | group by name too, or drop it |
SELECT name, COUNT(*) FROM gauges | a name from some row; the count is of every row | ORDER BY and LIMIT to pick a row |
WHERE reading > 100 GROUP BY hall | drops the halls with no such rows | a count of 0 needs every hall's rows |
ROUND(AVG(reading)) | a whole number | ROUND(AVG(reading), 1) |
A way to check an aggregate
- Run the query without its aggregates first: SELECT the rows themselves, with the same WHERE.
- Count, add or compare those rows by hand, and write down the number you expect.
- Look for NULLs in the column: COUNT(column), SUM, AVG, MIN and MAX all skip them.
- For a grouped query, add COUNT(*) to the SELECT list, so each group shows its size.
- Add HAVING last, and check which groups it removed.
The debugging corner: show the group's members
SQLite's group_concat(name, ', ') joins the values of a group into one piece of text. SELECT hall, group_concat(name, ', ') FROM gauges GROUP BY hall; shows exactly which gauges went into each group, so you can check a count or an average by eye.
Quick card
The whole lesson on one card. Come back to it whenever you need a reminder.
query.sql (ledger.db holds the eight gauges of lesson 03)
SELECT hall, COUNT(*) AS gauges, ROUND(AVG(reading), 1) AS average FROM gauges WHERE reading IS NOT NULL GROUP BY hall HAVING COUNT(*) >= 2 ORDER BY average DESC;
Terminal: sqlite3 ledger.db < query.sql
╭─────────────┬────────┬─────────╮
│ hall │ gauges │ average │
╞═════════════╪════════╪═════════╡
│ Engine Hall │ 4 │ 326.2 │
│ Clock Tower │ 2 │ 221.0 │
╰─────────────┴────────┴─────────╯
| To do this | Write this |
|---|---|
| Count rows | COUNT(*) |
| Count values, NULL left out | COUNT(reading) |
| Count different values | COUNT(DISTINCT unit) |
| Add up | SUM(reading); total(reading) gives 0.0 for no rows |
| Average | AVG(reading) |
| Smallest and largest | MIN(reading), MAX(reading) |
| Round to two places | ROUND(AVG(reading), 2) |
| Name a total | COUNT(*) AS gauges |
| One answer per group | GROUP BY hall |
| Groups of two columns | GROUP BY hall, unit |
| Keep some groups | HAVING COUNT(*) > 2 |
| The order of the parts | SELECT, FROM, WHERE, GROUP BY, HAVING, ORDER BY, LIMIT |
Words to know: aggregate function, COUNT, SUM, AVG, MIN, MAX, ROUND, total, average, spread, GROUP BY, group, HAVING, misuse of aggregate.
Self-check
Say each answer aloud before you open it.
What is the difference between COUNT(*) and COUNT(reading)?Tap to reveal
- One counts rows, one counts values.
COUNT(*) counts every row; COUNT(reading) counts only the rows whose reading is not NULL.
Why does AVG(reading) differ from SUM(reading) / COUNT(*) here?Tap to reveal
- What does each divide by?
AVG divides by the 7 readings; COUNT(*) is 8, so the NULL counts as a zero.
What do SUM and COUNT give for no rows at all?Tap to reveal
- One of them is a number.
COUNT gives 0; SUM gives NULL, and total() gives 0.0.
What must every column of a grouped query's SELECT list be?Tap to reveal
- Two choices.
Either in the GROUP BY, or inside an aggregate.
When does WHERE run, and when does HAVING?Tap to reveal
- Rows, then groups.
WHERE tests rows before grouping; HAVING tests groups after it.
The story: A number for every hall
By evening the answers fit on one card. Eight gauges, seven of them read. Four in the Engine Hall, two in the Clock Tower, two in the Couriers' Yard. The highest reading in each hall, and the average of each, rounded to two places.
One card asks only for the halls with more than two gauges, and gets the Engine Hall alone. The clerk who argued for eight and the clerk who argued for seven find that both were right: they had counted different things.
The Registrar files the card. "A ledger that can count," she says. "Tomorrow it gets a second page, and the pages learn to point at each other."
Reagents gathered: COUNT, SUM, AVG, MAX, GROUP BY, HAVING.
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)