SQL Interview Question: WHERE vs HAVING

A
Author
23 Sep, 2026 1 min read 835 views

Short answer: WHERE filters individual rows before grouping. HAVING filters groups after GROUP BY, so it can use aggregate functions like COUNT and SUM.

-- Customers who placed more than 5 paid orders in 2026
SELECT customer_id, COUNT(*) AS paid_orders, SUM(total) AS spent
FROM orders
WHERE status = 'paid'                      -- row filter: before grouping
  AND created_at >= '2026-01-01'
GROUP BY customer_id
HAVING COUNT(*) > 5                        -- group filter: after aggregation
ORDER BY spent DESC;

Logical order of a SELECT

  1. FROM / JOIN
  2. WHERE
  3. GROUP BY
  4. HAVING
  5. SELECT
  6. ORDER BY
  7. LIMIT

That's why you can't use an aggregate in WHERE (groups don't exist yet), and why a SELECT alias usually can't be used in WHERE (it hasn't been computed yet).

SELECT customer_id FROM orders WHERE COUNT(*) > 5 GROUP BY customer_id;  -- error

Performance tip

Filter as early as possible. A condition on a plain column belongs in WHERE, where it can use an index and shrink the data before grouping; putting it in HAVING works but processes more rows.

Was this article helpful?

Comments

No comments yet. Have a question or a tip? Be the first to share it.

Leave a comment

Comments are reviewed before they appear.