Skip to main content

SQL guide

SQL order of execution: how a query actually runs

SQL is written SELECT-first but evaluated FROM-first. Learn the logical order of every clause and the bugs it explains: aliases in WHERE, HAVING vs WHERE, and filtering window functions.

By Simas Bandzevicius · Updated November 24, 2026 · 8 min read

You write a query starting with SELECT, but the database does not start there. It first works out where the rows come from, filters them, groups them, and only then decides which columns to return. Knowing this logical order explains most of the confusing errors beginners hit, and a fair number that experienced analysts still trip over.

The logical order

StepClauseWhat it does
1FROM and JOINBuilds the working set of rows from one or more tables
2WHERERemoves individual rows that fail the condition
3GROUP BYCollapses rows into one row per group
4HAVINGRemoves whole groups that fail the condition
5SELECTComputes the output columns, including aliases and window functions
6DISTINCTRemoves duplicate output rows
7ORDER BYSorts the result
8LIMIT / OFFSETKeeps a slice of the sorted result

This is the logical order: the order in which the meaning of the query is defined. The optimizer is free to execute things differently (it may push a filter into a join, or use an index so no sort is needed) as long as the result is the same.

Bug 1: using a SELECT alias in WHERE

-- Fails in PostgreSQL: column "monthly" does not exist
SELECT first_name, salary / 12 AS monthly
FROM employees
WHERE monthly > 1000;

WHERE runs in step 2 and the alias is created in step 5, so it does not exist yet. Repeat the expression, or compute it in a subquery or CTE first:

WITH pay AS (
  SELECT first_name, salary / 12 AS monthly
  FROM employees
)
SELECT first_name, monthly
FROM pay
WHERE monthly > 1000;

ORDER BY runs after SELECT, which is why ORDER BY monthly works in the original query while WHERE monthly does not.

Bug 2: aggregates in WHERE

-- Fails: aggregate functions are not allowed in WHERE
SELECT department_id, COUNT(*)
FROM employees
WHERE COUNT(*) > 5
GROUP BY department_id;

Counts only exist after grouping (step 3), and WHERE has already run. Conditions on aggregates belong in HAVING. A good rule: if the condition is about a single row, use WHERE; if it is about a group total, use HAVING. Putting row filters in WHERE is also faster, because fewer rows reach the grouping step.

Bug 3: filtering on a window function

Window functions such as ROW_NUMBER() are computed in step 5, after WHERE, so this fails:

-- Fails: window functions are not allowed in WHERE
SELECT department_id, first_name,
       ROW_NUMBER() OVER (PARTITION BY department_id ORDER BY salary DESC) AS rn
FROM employees
WHERE rn = 1;

Compute the ranking in one step and filter in the next:

WITH ranked AS (
  SELECT department_id, first_name, salary,
         ROW_NUMBER() OVER (PARTITION BY department_id ORDER BY salary DESC, id) AS rn
  FROM employees
)
SELECT department_id, first_name, salary
FROM ranked
WHERE rn = 1;

Bug 4: a LEFT JOIN that behaves like an INNER JOIN

Because WHERE runs after the join, a condition on the right-hand table removes the rows the LEFT JOIN was supposed to keep:

SELECT c.first_name, o.id AS order_id
FROM customers c
LEFT JOIN orders o ON o.customer_id = c.id
WHERE o.order_date >= DATE '2024-01-01';

Customers with no orders have a NULL order_date, the comparison is unknown, and WHERE drops them. Move the condition into the ON clause so it is applied while matching, not after:

SELECT c.first_name, o.id AS order_id
FROM customers c
LEFT JOIN orders o
  ON o.customer_id = c.id
 AND o.order_date >= DATE '2024-01-01';

Bug 5: LIMIT without ORDER BY

LIMIT is the very last step and only makes sense on a sorted result. Without ORDER BY, "the first ten rows" means whatever order the database happened to produce, which can change between runs or after an index is added. Always sort before limiting, and include a unique tie-breaker such as id.

A habit that uses the order

When a query gets complicated, build it in the same order the database reads it:

  1. Write the FROM and joins, and check the row count with SELECT COUNT(*).
  2. Add WHERE and check the count again.
  3. Add GROUP BY and the aggregates, and check the number of groups.
  4. Add HAVING, then the final column list, then ORDER BY and LIMIT.

Each step has one job, and when a number looks wrong you know exactly which step to inspect.