← Back to SQL, page 1

sql-0001 · Medium mid

In what order does a database logically process the clauses of a SELECT statement, and why does that order matter?

A SELECT is written as SELECT, FROM, WHERE, GROUP BY, HAVING, ORDER BY, LIMIT, but it is logically evaluated as FROM, WHERE, GROUP BY, HAVING, SELECT, ORDER BY, LIMIT. This order explains why WHERE cannot filter on an aggregate and why standard SQL does not let WHERE use a column alias.

Full answer

The order you type the clauses is not the order the database reasons about them. The logical order is:

  1. FROM (and JOIN): build the set of input rows.
  2. WHERE: keep only rows that pass the condition.
  3. GROUP BY: collapse the remaining rows into groups.
  4. HAVING: keep only groups that pass the condition.
  5. SELECT: compute the output columns and their aliases.
  6. ORDER BY: sort the output.
  7. LIMIT / OFFSET: cut the sorted output.

"Logical" matters here. The optimizer may physically do things in a different order, for example by using an index to read rows already sorted. It must still return the same answer as if it had followed the steps above.

Three everyday results fall out of this order. WHERE runs before grouping, so WHERE COUNT(*) > 1 is meaningless and you need HAVING. ORDER BY runs after SELECT, so it can sort by an alias. And in standard SQL, WHERE runs before SELECT, so an alias defined in SELECT does not exist yet when WHERE is checked.

PostgreSQL follows the standard and rejects an alias in WHERE:

sql
CREATE TABLE departments (
  id   INTEGER PRIMARY KEY,
  name TEXT NOT NULL
);
CREATE TABLE employees (
  id         INTEGER PRIMARY KEY,
  name       TEXT NOT NULL,
  dept_id    INTEGER REFERENCES departments(id),
  manager_id INTEGER REFERENCES employees(id),
  salary     INTEGER,
  hire_date  TEXT
);
INSERT INTO departments VALUES (1,'Engineering'),(2,'Sales'),(3,'Support'),(4,'Legal');
INSERT INTO employees VALUES
  (1,'Asha', 1,NULL,120000,'2019-03-01'),
  (2,'Ravi', 1,1,    95000,'2020-07-15'),
  (3,'Mei',  1,1,    95000,'2021-01-10'),
  (4,'Tom',  2,1,    70000,'2022-05-20'),
  (5,'Sara', 2,4,    62000,'2023-02-01'),
  (6,'Diego',3,1,    55000,'2021-11-30'),
  (7,'Lena', NULL,4, NULL,  '2024-06-03'),
  (8,'Omar', 3,6,    48000,'2024-09-09');
sql
SELECT name, salary * 12 AS yearly
FROM employees
WHERE yearly > 1000000;
-- error on purpose
text
Error: column "yearly" does not exist

SQLite is more relaxed and resolves the alias anyway:

sql
SELECT name, salary * 12 AS yearly
FROM employees
WHERE yearly > 1000000
ORDER BY name;
nameyearly
Asha1440000
Mei1140000
Ravi1140000

ORDER BY can use the alias on both engines, because sorting happens after SELECT:

sql
SELECT name, salary * 12 AS yearly
FROM employees
WHERE salary IS NOT NULL
ORDER BY yearly DESC
LIMIT 3;
nameyearly
Asha1440000
Ravi1140000
Mei1140000

For portable code, repeat the expression in WHERE or wrap the query in a subquery or CTE and filter outside.

sql
CREATE TABLE departments (
  id   INTEGER PRIMARY KEY,
  name TEXT NOT NULL
);
CREATE TABLE employees (
  id         INTEGER PRIMARY KEY,
  name       TEXT NOT NULL,
  dept_id    INTEGER REFERENCES departments(id),
  manager_id INTEGER REFERENCES employees(id),
  salary     INTEGER,
  hire_date  TEXT
);
INSERT INTO departments VALUES (1,'Engineering'),(2,'Sales'),(3,'Support'),(4,'Legal');
INSERT INTO employees VALUES
  (1,'Asha', 1,NULL,120000,'2019-03-01'),
  (2,'Ravi', 1,1,    95000,'2020-07-15'),
  (3,'Mei',  1,1,    95000,'2021-01-10'),
  (4,'Tom',  2,1,    70000,'2022-05-20'),
  (5,'Sara', 2,4,    62000,'2023-02-01'),
  (6,'Diego',3,1,    55000,'2021-11-30'),
  (7,'Lena', NULL,4, NULL,  '2024-06-03'),
  (8,'Omar', 3,6,    48000,'2024-09-09');

SELECT name, salary * 12 AS yearly
FROM employees
WHERE yearly > 1000000
ORDER BY name;

SELECT name, salary * 12 AS yearly
FROM employees
WHERE salary IS NOT NULL
ORDER BY yearly DESC
LIMIT 3;

Checked on SQLite 3.46.1, run twice with identical output. PostgreSQL results in the answer were checked on PostgreSQL 17.12.

Key points

  • Logical order: FROM, WHERE, GROUP BY, HAVING, SELECT, ORDER BY, LIMIT
  • WHERE filters rows before grouping; HAVING filters groups after it
  • ORDER BY can use SELECT aliases because it runs after SELECT
  • The physical plan may differ, but the result must match the logical order

Common mistakes

  • Writing an aggregate such as COUNT(*) inside WHERE
  • Assuming an alias that works in SQLite's WHERE will also work in PostgreSQL or SQL Server

Follow-ups

  • Where do window functions fit in this order?
  • Why can HAVING sometimes use a SELECT alias in some engines but not others?

Tips

  • Say the logical order out loud, then give one bug it explains, such as the alias-in-WHERE error
  • Mention that the optimizer may reorder work physically without changing the result