WHERE vs HAVING, and in what order does SQL evaluate a query?
Logical order of evaluation
SQL is written SELECT ... FROM ... WHERE ... GROUP BY ... HAVING ... ORDER BY ... LIMIT, but logically evaluated as:
FROMandJOINs: build the row set.WHERE: filter individual rows.GROUP BY: form groups.HAVING: filter groups (can use aggregates).SELECT: compute output columns and aliases; window functions run here.DISTINCT.ORDER BY: can useSELECTaliases.LIMIT/OFFSET/FETCH FIRST.
Consequences
WHEREcannot use aggregates (WHERE COUNT(*) > 5is an error); useHAVING.WHEREcannot use aSELECTalias in most databases (the alias does not exist yet), butORDER BYcan.- Filter as early as possible: conditions on plain columns belong in
WHERE, so fewer rows reach the grouping step. - To filter on a window function's result, wrap the query in a subquery or CTE (or use
QUALIFYwhere supported).
Example
sql
-- Departments whose average salary of active employees exceeds 80,000
SELECT department_id,
COUNT(*) AS headcount,
ROUND(AVG(salary)) AS avg_salary
FROM employees
WHERE status = 'ACTIVE' -- row filter, before grouping
GROUP BY department_id
HAVING AVG(salary) > 80000 -- group filter, after grouping
ORDER BY avg_salary DESC -- alias allowed here
FETCH FIRST 5 ROWS ONLY; -- LIMIT 5 in PostgreSQL/MySQLFollow-up questions interviewers ask
Try answering each one before you open it.
What does COUNT(*) vs COUNT(column) return?
COUNT(*) counts rows. COUNT(column) counts rows where that column is not NULL. COUNT(DISTINCT column) counts distinct non-null values. This difference matters after a LEFT JOIN: count a column from the right table to get 0 for unmatched rows.