HAVING
WHERE for groups. the filter that runs after aggregation, and the one that should have been a WHERE.
- address
- everything.basics.having_clause
- part
- part 2, one table
- chapter
- chapter 12 of 12
- reading time
- 7 min
HAVING is WHERE for buckets. it runs after GROUP BY, so it judges whole groups and can use aggregates like count(*). WHERE runs before, on single rows, so it can't.
a HAVING condition that doesn't use an aggregate should have been a WHERE.
the picture
you know how WHERE count(*) > 1 is an error, and HAVING count(*) > 1 is fine? same condition, different place, and one of them is allowed to count. that's because they stand at two different points on the line.
think of a restaurant on a busy night. at the door, a host checks each guest on their own: no shoes, no entry (WHERE). inside, guests sit down in parties at their tables (GROUP BY). later a manager walks round and looks at whole tables: any table of fewer than two gets moved to the bar (HAVING). the host can't apply the manager's rule, because at the door there are no tables yet. the manager could apply the host's rule, but by then everyone's already been seated for nothing.
- 1SELECT dept, count(*) AS courses, sum(credits) AS total
- 2FROM courses
- 3WHERE credits >= 4
- 4GROUP BY dept
- 5HAVING count(*) >= 2
- 6ORDER BY dept;
| code | dept | credits | instructor_id | title |
|---|---|---|---|---|
| CS101 | CS | 4 | 1 | Intro to Programming |
| CS201 | CS | 4 | 2 | Data Structures |
| CS301 | CS | 4 | 1 | Databases |
| CS350 | CS | 4 | 2 | Operating Systems |
| CS401 | CS | 4 | 3 | Database Internals |
| CS499 | GEN | 6 | null | Senior Thesis |
| HIST101 | HIST | 3 | 7 | History of Computing |
| MATH101 | MATH | 4 | 4 | Calculus I |
| MATH201 | MATH | 3 | 5 | Discrete Math |
| MATH301 | MATH | 3 | 4 | Linear Algebra |
| PHYS101 | PHYS | 4 | 6 | Mechanics |
| PHYS201 | PHYS | 4 | 6 | Electromagnetism |
FROM hands over all 12 rows.
the order is the logical order: FROM, WHERE, GROUP BY, HAVING, SELECT. so the two filters see different tables. WHERE sees rows. HAVING sees buckets.
what HAVING sees
by the time HAVING runs, every bucket has been summed up. picture the table it gets as one row per group, with the aggregates already filled in, and HAVING as a WHERE over that table:
| categorytext | productsint8 | avg_pricenumeric |
|---|---|---|
| null | 3 | 92.20 |
| audio | 21 | 119.84 |
| bath | 27 | 105.21 |
| books | 12 | 92.15 |
| games | 14 | 89.48 |
| garden | 15 | 83.20 |
| kitchen | 19 | 88.62 |
| office | 26 | 101.35 |
| outdoor | 22 | 103.66 |
| pets | 17 | 115.96 |
| toys | 24 | 102.76 |
HAVING avg(price) > 100 keeps six; the five it drops are struck. the 3 products with no category are a bucket too, and it goes.so HAVING may use what that table has: the grouping key, and any aggregate. that's the same rule as for SELECT after a GROUP BY (grouped or aggregated). a plain column has no single value per bucket, so HAVING can't ask about it:
SELECT category, count(*) AS products
FROM products
GROUP BY category
HAVING price > 100;price belongs to single products, and HAVING is looking at categories. if you meant "count only the products over 100", that's a filter on rows, which is WHERE's job. and that's where it gets interesting, because the two give very different answers.
WHERE or HAVING?
"categories, and products over 100" can mean two things. throw out the cheap products and then group what's left. or group everything and then keep the categories whose average is over 100.
- 1SELECT category, count(*) AS products, round(avg(price), 2) AS avg_price
- 2FROM products
- 3WHERE price > 100
- 4GROUP BY category
- 5ORDER BY category NULLS FIRST;
| categorytext | productsint8 | avg_pricenumeric |
|---|---|---|
| null | 1 | 182.70 |
| audio | 14 | 145.12 |
| bath | 16 | 138.46 |
| books | 5 | 153.56 |
| games | 5 | 152.78 |
| garden | 6 | 142.22 |
| kitchen | 6 | 152.18 |
| office | 12 | 155.35 |
| outdoor | 10 | 160.24 |
| pets | 10 | 156.92 |
| toys | 12 | 147.64 |
WHERE price > 100 throws out cheap products before grouping. every category has some expensive ones, so all eleven buckets survive, smaller, and their averages jump.
neither is wrong. they answer different questions, and the question decides which one you need: a condition on single rows goes in WHERE, a condition on a whole group goes in HAVING. you can, and often do, use both in one query.
SELECT count(*) FROM products HAVING count(*) > 1000;SELECT count(*) FROM products HAVING count(*) > 1000;
SELECT count(*) FROM products HAVING count(*) > 100;| countint8 |
|---|
| countint8 |
|---|
| 200 |
zero rows, then one row with 200 in it. HAVING without GROUP BY is legal, and rare. now you know what it does.
the HAVING that should have been a WHERE
this works, and gives the right answer:
SELECT category, count(*) AS products
FROM products
GROUP BY category
HAVING category = 'kitchen';| categorytext | productsint8 |
|---|---|
| kitchen | 19 |
19 kitchen products. but read it the way it runs: build all 11 buckets, then throw away 10. the condition only looks at the key, never at an aggregate, so it would give the same answer on single rows, before grouping. it's a WHERE wearing the wrong coat.
postgres notices. it moves a condition like that down into the scan, so the other categories are never grouped at all (the logical order shows the plan). write it as a WHERE anyway: it says what you mean (keep the kitchen rows), it doesn't rely on the planner being clever, and the next person reading the query doesn't have to wonder whether the HAVING was doing something subtle.
SELECT category, count(*) AS products
FROM products
WHERE category = 'kitchen'
GROUP BY category;| categorytext | productsint8 |
|---|---|
| kitchen | 19 |
finding duplicates
the most useful HAVING you'll ever write is "more than one". group by whatever should be unique, and keep the buckets with company. the shop's customers have a UNIQUE email, but UNIQUE compares exact strings. compare them ignoring case:
SELECT lower(email) AS email, count(*) AS customers
FROM customers
GROUP BY lower(email)
HAVING count(*) > 1
ORDER BY email NULLS FIRST;| emailtext | customersint8 |
|---|---|
| null | 46 |
| zoe.martin@example.com | 2 |
two buckets. zoe.martin@example.com holds Zoë and Zoe Martin, two different people whose emails differ only in capital letters, which UNIQUE happily allowed. and the NULL bucket holds the 46 customers with no email at all: as far as grouping is concerned, their NULLs are the same. that's not a duplicate, that's missing data, and it's a row-level fact, so it gets filtered with WHERE:
SELECT lower(email) AS email, count(*) AS customers
FROM customers
WHERE email IS NOT NULL
GROUP BY lower(email)
HAVING count(*) > 1
ORDER BY email;| emailtext | customersint8 |
|---|---|
| zoe.martin@example.com | 2 |
one real duplicate left. the cure belongs in the schema: a unique index on lower(email) (partial and expression indexes).
keylines
- WHERE judges rows before GROUP BY. HAVING judges buckets after it.
- HAVING can use the grouping key and aggregates, nothing else, same as SELECT.
- WHERE price > 100 and HAVING avg(price) > 100 answer different questions.
- a HAVING with no aggregate in it should have been a WHERE.
- GROUP BY x HAVING count(*) > 1 finds duplicates. watch for the NULL bucket.