SQL reference

HAVING vs WHERE in SQL

In Excel, you'd reach for
fxFiltering the data vs filtering the pivot table totals

Both filter. The difference is when:

  • WHERE runs first, on individual rows, before anything is grouped. Use it for "only 2026 orders" or "only Europe".
  • HAVING runs after GROUP BY, on the totals. Use it for "only customers with 3+ orders" or "only months over $10k".

Writing WHERE COUNT(*) > 3 fails because when WHERE runs, nothing has been counted yet.

SQL order of execution: FROM, WHERE, GROUP BY, HAVING, SELECT, ORDER BY, LIMIT, with the Excel equivalent of each step
The order SQL runs a query in, with the Excel step each one is like. Download · Save to Pinterest

Syntax

SELECT col, SUM(x)
FROM table
WHERE row_condition
GROUP BY col
HAVING SUM(x) > 100;
Try itEdit the query, then Run
customer_idordersunits
290520
324313
297413
322412
181212
162312
87412
365311
343211
213211

Showing 10 of 73 rows. Press Run to see them all.

Read it in order: take orders from April on (WHERE), bucket them per customer (GROUP BY), keep buckets with at least 2 orders (HAVING), sort (ORDER BY). In Excel that's filtering the source data, building a pivot, then applying a value filter to the pivot.

Your turn

Which countries have more than 20 customers who came from paid_search? Show country and customers.

This page on one card

HAVING vs WHERE in SQL: the Excel way (Filtering the data vs filtering the pivot table totals) and the SQL query, side by side
HAVING vs WHERE in SQL, on one card: the Excel way and the SQL. Download · Save to Pinterest
The practice data (7 tables)

See every column and sample rows