🚀 New batches open: Advanced Excel • Power BI • SQL • AI for Analytics — Book a free demo
Home / SQL Tutorial / Day 8

Day 8 — HAVING, and how it differs from WHERE

A classic interview question, and a genuine source of wrong reports: WHERE filters rows, HAVING filters groups.

The one-line difference

  • WHERE runs before grouping — it filters individual rows.
  • HAVING runs after grouping — it filters the totals.

So you cannot use an aggregate in WHERE, and you would not use HAVING for something a WHERE could do.

HAVING in action

Reps with more than 3 orders. Try changing 3 to 4.

HAVING on a total

Both together — and the order matters

Read this as: keep Delivered orders, group them by rep, then keep only reps whose delivered revenue passes 200000.

The order SQL is written in

SELECT which columns FROM which table WHERE filter rows GROUP BY collapse into groups HAVING filter the groups ORDER BY sort the result LIMIT trim the result
Worth memorising That is also close to the order the database actually runs them in — which is why an alias created in SELECT cannot be used in WHERE, but usually can be in ORDER BY.

Departments with more than one person

Try these yourself

  1. Cities with more than one customer.
  2. Departments whose total salary is above 1000000.
  3. Statuses that occur more than 3 times in Orders.
  4. Reps averaging more than 60000 per order.
  5. Explain in one sentence why COUNT(*) cannot go in WHERE.

Want this taught properly?

This tutorial covers the basics. Our SQL course in Noida takes you through window functions, CTEs and stored procedures on a real database, with projects and mentor support.

See the SQL course →