π AggregationintermediateCommonly used
How to use HAVING in SQL
Filter groups after aggregation β like WHERE but for GROUP BY results.
Filter groups by aggregate valueAll databases
SELECT
country,
COUNT(*) AS user_count
FROM users
GROUP BY country
HAVING COUNT(*) > 100;HAVING filters AFTER aggregation. Returns only countries with more than 100 users.
When to use: Filtering based on an aggregate value like COUNT, SUM, AVG.
HAVING vs WHERE β key differenceAll databases
-- WHERE filters rows BEFORE grouping:
SELECT country, COUNT(*) AS count
FROM users
WHERE active = true -- filter rows first
GROUP BY country
HAVING COUNT(*) > 50; -- then filter groupsWHERE runs before GROUP BY (filters rows). HAVING runs after GROUP BY (filters groups). Use both together when needed.
HAVING with multiple conditionsAll databases
SELECT
user_id,
COUNT(*) AS order_count,
SUM(total) AS total_spent
FROM orders
GROUP BY user_id
HAVING COUNT(*) >= 5
AND SUM(total) > 1000;Find users who placed at least 5 orders AND spent more than $1000 total.
Find duplicates with HAVINGAll databases
SELECT email, COUNT(*) AS occurrences
FROM users
GROUP BY email
HAVING COUNT(*) > 1;Classic pattern for finding duplicate values β group and filter for count > 1.
When to use: Data quality checks, finding duplicate records.
Common Mistakes
- βUsing HAVING instead of WHERE for row-level filters β HAVING is slower
- βConfusing WHERE and HAVING: WHERE filters before grouping, HAVING filters after