skip to content

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.

filter =
query.sqlstep 1: FROM
  1. 1SELECT dept, count(*) AS courses, sum(credits) AS total
  2. 2FROM courses
  3. 3WHERE credits >= 4
  4. 4GROUP BY dept
  5. 5HAVING count(*) >= 2
  6. 6ORDER BY dept;
the table after FROM
codedeptcreditsinstructor_idtitle
CS101CS41Intro to Programming
CS201CS42Data Structures
CS301CS41Databases
CS350CS42Operating Systems
CS401CS43Database Internals
CS499GEN6nullSenior Thesis
HIST101HIST37History of Computing
MATH101MATH44Calculus I
MATH201MATH35Discrete Math
MATH301MATH34Linear Algebra
PHYS101PHYS46Mechanics
PHYS201PHYS46Electromagnetism
(12 rows)

FROM hands over all 12 rows.

clause 1/5
real output, postgres 18.6 (PGlite 0.5.12) · having-clause
pick a filter and step through. WHERE strikes single rows before the buckets exist. HAVING strikes whole buckets, after. with both, MATH loses two courses at the door and then fails HAVING with the one it has left.

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:

categorytextproductsint8avg_pricenumeric
null392.20
audio21119.84
bath27105.21
books1292.15
games1489.48
garden1583.20
kitchen1988.62
office26101.35
outdoor22103.66
pets17115.96
toys24102.76
6 groups kept, 5 removed
one row per category, aggregates computed. 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:

sqldb=shop
SELECT category, count(*) AS products
FROM products
GROUP BY category
HAVING price > 100;
output, from postgres 18.6
ERROR 42803: column "products.price" must appear in the GROUP BY clause or be used in an aggregate function
4 │ HAVING price > 100;
at line 4, column 8

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.

filter =
query.sql
  1. 1SELECT category, count(*) AS products, round(avg(price), 2) AS avg_price
  2. 2FROM products
  3. 3WHERE price > 100
  4. 4GROUP BY category
  5. 5ORDER BY category NULLS FIRST;
the result for WHERE price > 100
categorytextproductsint8avg_pricenumeric
null1182.70
audio14145.12
bath16138.46
books5153.56
games5152.78
garden6142.22
kitchen6152.18
office12155.35
outdoor10160.24
pets10156.92
toys12147.64
(11 rows)

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.

real output, postgres 18.6 (PGlite 0.5.12) · having-clause-shop
switch between them. WHERE keeps all 11 categories, each with fewer products and a higher average. HAVING keeps every product, and only 6 categories pass.

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.

predict the output
sql
SELECT count(*) FROM products HAVING count(*) > 1000;
sqldb=shop
SELECT count(*) FROM products HAVING count(*) > 1000;
SELECT count(*) FROM products HAVING count(*) > 100;
output, from postgres 18.6
#1 · SELECT 0
countint8
(0 rows)
#2 · SELECT 1
countint8
200
(1 row)

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:

sqldb=shop
SELECT category, count(*) AS products
FROM products
GROUP BY category
HAVING category = 'kitchen';
output, from postgres 18.6
SELECT 1
categorytextproductsint8
kitchen19
(1 row)

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.

sqldb=shop
SELECT category, count(*) AS products
FROM products
WHERE category = 'kitchen'
GROUP BY category;
output, from postgres 18.6
SELECT 1
categorytextproductsint8
kitchen19
(1 row)

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:

sqldb=shop
SELECT lower(email) AS email, count(*) AS customers
FROM customers
GROUP BY lower(email)
HAVING count(*) > 1
ORDER BY email NULLS FIRST;
output, from postgres 18.6
SELECT 2
emailtextcustomersint8
null46
zoe.martin@example.com2
(2 rows)

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:

sqldb=shop
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;
output, from postgres 18.6
SELECT 1
emailtextcustomersint8
zoe.martin@example.com2
(1 row)

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.