Skip to content
  • Logical Order of Query Execution · SQL

Logical Order of Query Execution

LearnViaNotes @learnvianotes· 2 min read

You write SELECT first, but the database evaluates it almost last. This single fact explains most “why can't I use that here?” errors.

FROM / JOIN → WHERE → GROUP BY → HAVING → SELECT → DISTINCT → ORDER BY → LIMIT

  1. FROM + JOINs

    Build the working set of rows from the tables.

  2. WHERE

    Keep rows whose condition is true. Aggregates don't exist yet.

  3. GROUP BY

    Collapse rows into one row per group.

  4. HAVING

    Keep groups whose condition is true — aggregates are available now.

  5. SELECT

    Compute output expressions, window functions and aliases.

  6. DISTINCT

    Remove duplicate output rows.

  7. ORDER BY

    Sort — can use aliases, since SELECT already ran.

  8. LIMIT / OFFSET

    Cut the sorted result.

Consequences

You tryResultWhy
WHERE monthly > 9000 (alias)Error in standard SQLWHERE runs before SELECT creates the alias
WHERE COUNT(*) > 2Error everywhereAggregates don't exist before GROUP BY — use HAVING
ORDER BY monthlyWorksORDER BY runs after SELECT
WHERE ROW_NUMBER() OVER (…) = 1ErrorWindow functions are computed in SELECT — filter in an outer query / CTE
SQL
SELECT dept_id, COUNT(*) AS headcount
FROM employees
WHERE COUNT(*) > 2
GROUP BY dept_id;
Error
misuse of aggregate: COUNT()
SQL
SELECT dept_id, COUNT(*) AS headcount
FROM employees
WHERE dept_id IS NOT NULL           -- row filter: before grouping
GROUP BY dept_id
HAVING COUNT(*) > 2                 -- group filter: after grouping
ORDER BY headcount DESC;            -- alias is fine here
Output
dept_id | headcount
--------+----------
1       | 4
2       | 3
SQL
-- to filter on a computed column, compute it in a subquery / CTE first
SELECT name, monthly
FROM (SELECT name, salary / 12 AS monthly FROM employees) AS t
WHERE monthly > 9000
ORDER BY monthly DESC;
Output
name  | monthly
------+--------
Asha  | 12500
Ravi  | 10000
Priya | 9166

What is the order of execution of a SQL query?

Free for students and teachers

Write notes like this one

Cards for every idea, quizzes and flashcards, read aloud — on the web and your phone.

Something wrong with this note? Open it to report