HAVING Clause

Intermediate

⏱️ 10 mins read

What You'll Learn

HAVING filters groups produced by GROUP BY. It's WHERE for aggregated results — applied after aggregation, unlike WHERE which runs before. You can use aggregate functions in HAVING that aren't in SELECT.

Syntax

SELECT col, AGG(col2) FROM table
GROUP BY col
HAVING AGG(col2) > value;

Example

-- Departments with more than 5 employees
SELECT department, COUNT(*) AS headcount
FROM employees
GROUP BY department
HAVING COUNT(*) > 5;

-- WHERE and HAVING together
SELECT department, AVG(salary) AS avg_sal
FROM employees
WHERE hire_date >= '2020-01-01'   -- filter rows first
GROUP BY department
HAVING AVG(salary) > 70000;       -- filter groups after

Common Mistakes

Trying to use a SELECT alias in HAVING (most DBs don't allow it — use the aggregate expression again). Confusing WHERE and HAVING: WHERE filters individual rows, HAVING filters groups after aggregation.

Interview Tips

Execution order is key: FROM → JOIN → WHERE → GROUP BY → HAVING → SELECT → ORDER BY → LIMIT. Interviewers test this constantly. HAVING without GROUP BY applies to the entire table as one group.

Practice

Find all customers who placed more than 3 orders in 2024 with a total spend exceeding $1,000.