← All lessons
Combining and summarizing · Lesson 3 of 10

HAVING, and the order a query runs in

WHERE can't filter on a count, because when WHERE runs the groups don't exist yet. HAVING filters the groups after they're made, so it can use aggregates. Customers with two or more shipped orders:

SELECT customer_id, COUNT(*) AS shipped
FROM orders
WHERE status = 'shipped'
GROUP BY customer_id
HAVING COUNT(*) >= 2;
Returns
customer_id | shipped
------------+--------
1           | 3
2           | 2
(2 rows)

Read it in steps: take the orders, keep the shipped ones (WHERE), put them in a pile per customer (GROUP BY), count each pile, and keep the piles of two or more (HAVING).

That's the key to SQL: the order you write a query in isn't the order the database works in. It writes as SELECT, FROM, WHERE, GROUP BY, HAVING, ORDER BY, LIMIT, but runs like this:

  1. FROM: find the table (and any joins)
  2. WHERE: keep the rows that pass
  3. GROUP BY: make the groups
  4. HAVING: keep the groups that pass
  5. SELECT: work out the result columns
  6. ORDER BY: sort
  7. LIMIT: cut to the first few

It explains a lot. WHERE can't see an aggregate, because the groups come after it. ORDER BY can use a column alias from SELECT, because it runs after SELECT. And you can sort the groups by their aggregate, to find the biggest:

SELECT category, COUNT(*) AS products
FROM products
GROUP BY category
HAVING COUNT(*) > 1
ORDER BY products DESC, category;
Returns
category | products
---------+---------
Garden   | 3
Books    | 2
Clothing | 2
(3 rows)

Practice

Customers with more than one order (any status): customer_id and the number of orders.

The tables
  • customers (id, name, city, joined)
  • products (id, name, category, price)
  • orders (id, customer_id, ordered_on, status)
  • order_items (order_id, product_id, qty)
  • signups (id, email, name, signed_up_at)
  • payments (id, order_id, amount, currency, paid_at)
  • events (id, received_at, payload (JSON text))
  • staff (id, name, role, manager_id, salary, hired)
  • logins (customer_id, day)
More info

Quick reference

HAVING conditionKeep the groups where it's true (can use aggregates).
WHERE vs HAVINGWHERE filters rows before grouping; HAVING filters groups after.
Run orderFROM, WHERE, GROUP BY, HAVING, SELECT, ORDER BY, LIMIT.

The other AI and data engineering courses