Tech Interview RoomStudy guides

SQL Fundamentals

WHERE vs HAVING, and in what order does SQL evaluate a query?

Beginner · 2 min read · Lesson 2 of 8 in SQL Fundamentals

Logical order of evaluation

SQL is written SELECT ... FROM ... WHERE ... GROUP BY ... HAVING ... ORDER BY ... LIMIT, but logically evaluated as:

  1. FROM and JOINs: build the row set.
  2. WHERE: filter individual rows.
  3. GROUP BY: form groups.
  4. HAVING: filter groups (can use aggregates).
  5. SELECT: compute output columns and aliases; window functions run here.
  6. DISTINCT.
  7. ORDER BY: can use SELECT aliases.
  8. LIMIT / OFFSET / FETCH FIRST.

Consequences

  • WHERE cannot use aggregates (WHERE COUNT(*) > 5 is an error); use HAVING.
  • WHERE cannot use a SELECT alias in most databases (the alias does not exist yet), but ORDER BY can.
  • 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 QUALIFY where 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/MySQL

Follow-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.