HAVING
Overview
GROUP BY gives you one row per group. Often you only want some of those groups: categories with more than three products, customers who’ve ordered at least three times, months with revenue over $200. You can’t use WHERE for that, because WHERE runs before the groups exist. SQL has a separate clause for filtering groups: HAVING.
Filtering groups
Which categories have more than three products?
SELECT category_id, count(*) AS products
FROM products
GROUP BY category_id
HAVING count(*) > 3
ORDER BY category_id; category_id | products
-------------+----------
2 | 4
3 | 4
(2 rows)HAVING is written after GROUP BY, and its condition is checked once per group, after the aggregates have been calculated. Coffee (3 products) and the gift card’s NULL group (1) didn’t pass.
Try the same condition in WHERE and PostgreSQL explains the problem:
SELECT category_id, count(*) AS products
FROM products
WHERE count(*) > 3
GROUP BY category_id;ERROR: aggregate functions are not allowed in WHERE
LINE 3: WHERE count(*) > 3
^When WHERE runs, there are no groups and no counts yet — just individual rows.
WHERE and HAVING together
The two clauses do different jobs, and many queries use both. Which orders contain at least $80 of goods, not counting gift cards?
SELECT order_id,
sum(quantity * unit_price) AS items_total
FROM order_items
WHERE product_id <> 12
GROUP BY order_id
HAVING sum(quantity * unit_price) >= 80
ORDER BY items_total DESC; order_id | items_total
----------+-------------
2 | 113.00
21 | 109.00
13 | 89.00
(3 rows)Read it in the order the database does:
FROM order_items— all 42 item rows.WHERE product_id <> 12— drop gift-card lines, row by row.GROUP BY order_id— pile the remaining rows up by order.HAVING sum(...) >= 80— keep only orders whose items add up to at least $80.SELECT, thenORDER BY— calculate the output columns and sort.
Rows or groups? Choosing the right clause
A good rule: if a condition could be checked by looking at one row, put it in WHERE. Only conditions that need a whole group — a count, a sum, an average — belong in HAVING.
These two queries return the same thing:
SELECT status, count(*) AS orders
FROM orders
WHERE status <> 'delivered'
GROUP BY status
ORDER BY status; status | orders
-----------+--------
cancelled | 2
paid | 2
pending | 2
shipped | 2
(4 rows)SELECT status, count(*) AS orders
FROM orders
GROUP BY status
HAVING status <> 'delivered'
ORDER BY status; status | orders
-----------+--------
cancelled | 2
paid | 2
pending | 2
shipped | 2
(4 rows)But the first is better. It throws away the delivered rows before doing any grouping work, and it tells the reader “this is a row filter”. On a table of millions of rows, filtering early can make a large difference.
HAVING can use aggregates you don’t select
The aggregate in HAVING doesn’t have to be in the select list. Customers who have had at least one order cancelled:
SELECT customer_id, count(*) AS orders
FROM orders
GROUP BY customer_id
HAVING count(*) FILTER (WHERE status = 'cancelled') > 0
ORDER BY customer_id; customer_id | orders
-------------+--------
4 | 3
6 | 3
(2 rows)And you can combine several conditions with AND and OR, just as in WHERE — for example HAVING count(*) >= 2 AND max(ordered_at) < '2026-09-01' finds repeat customers who’ve gone quiet since the summer.
The logical order of a query
You write a query starting with SELECT, but that’s not the order the database thinks about it. Logically, the clauses are processed like this:
This one diagram explains a lot of SQL’s rules:
- WHERE can’t use aggregates — it runs at step 2, before groups exist at step 3.
- HAVING can — it runs at step 4, after grouping.
- Aliases defined in SELECT (step 5) don’t exist yet in WHERE or HAVING, but they do in ORDER BY (step 7).
- LIMIT runs last, so it always applies to the final, sorted result.
Here’s the alias rule in action:
SELECT customer_id, count(*) AS num_orders
FROM orders
GROUP BY customer_id
HAVING num_orders >= 4;ERROR: column "num_orders" does not exist
LINE 4: HAVING num_orders >= 4;
^At the HAVING stage the alias num_orders hasn’t been created yet, so PostgreSQL looks for a real column with that name and finds none. Repeat the aggregate instead:
SELECT customer_id, count(*) AS num_orders
FROM orders
GROUP BY customer_id
HAVING count(*) >= 4
ORDER BY num_orders DESC; customer_id | num_orders
-------------+------------
1 | 5
2 | 4
(2 rows)…while ORDER BY num_orders works, because sorting happens after SELECT.
Logical, not physical. The database’s planner is free to execute things in a different order — using an index to sort early, say — as long as the result is identical. The logical order is the model you use to reason about what a query means.
HAVING without GROUP BY
Occasionally you’ll see HAVING with no GROUP BY. Then the whole table is one group, and the query returns either one row or none:
SELECT count(*) AS out_of_stock
FROM products
WHERE stock = 0
HAVING count(*) > 0; out_of_stock
--------------
2
(1 row)“Tell me the number of out-of-stock products, but only if there are any.” It’s rare, but it’s a nice confirmation that HAVING is simply a WHERE for groups.
Other databases: MySQL and SQLite allow select-list aliases in
HAVING(HAVING num_orders >= 4), so you’ll see that in their code. Repeating the aggregate works everywhere.
Our regular customers
Marketing defines a regular customer as someone with at least three orders that weren't cancelled. Return the customer_id, the number of such orders, and the first_order date (as a date, without the time) for every regular customer, sorted by number of orders (most first), then customer_id. Use WHERE to drop cancelled orders and HAVING to keep only the regulars. You should get customers 1, 2 and 3.
SELECT customer_id, count(*) AS orders
FROM orders
GROUP BY customer_id;SELECT customer_id,
count(*) AS orders,
min(ordered_at)::date AS first_order
FROM orders
WHERE status <> 'cancelled'
GROUP BY customer_id
HAVING count(*) >= 3
ORDER BY orders DESC, customer_id;Summary
- WHERE filters rows before grouping; HAVING filters groups after the aggregates have been calculated.
- HAVING conditions usually involve aggregates, such as HAVING count(*) > 2 or HAVING sum(total) >= 100.
- Conditions on plain columns belong in WHERE — it's clearer and makes less work for the database.
- SQL runs a query logically in the order FROM, WHERE, GROUP BY, HAVING, SELECT, DISTINCT, ORDER BY, LIMIT.
- That order explains why a SELECT alias can be used in ORDER BY but not in WHERE or HAVING.