How a SQL Query Is Processed: The Logical Order of SELECT Clauses
You write SELECT first, but the database evaluates it fifth. The logical processing order (FROM, WHERE, GROUP BY, HAVING, SELECT, DISTINCT, ORDER BY, LIMIT) explains why aliases fail in WHERE, why aggregates need HAVING, and many other everyday errors.
kvi5hnuCode Sprout team member10 min readOn this page
A SELECT statement is written in a fixed order: SELECT, FROM, WHERE, GROUP BY, HAVING, ORDER BY, then a row limit. But the database doesn't evaluate it in that order. Conceptually, it starts with FROM and works through the clauses in a different sequence, called the logical processing order. Once you know that order, a whole class of confusing errors makes sense, and you'll know where each kind of condition belongs.
This article uses clauses that later articles explain in detail. You don't need to master GROUP BY or HAVING yet. The goal here is the big picture.
The logical order

| Step | Clause | What it does | Works on |
|---|---|---|---|
| 1 | FROM (with JOIN ... ON) | builds the working set of rows from the tables | tables |
| 2 | WHERE | keeps only the rows that satisfy a condition | individual rows |
| 3 | GROUP BY | collects rows into groups and computes aggregates such as SUM and COUNT | rows into groups |
| 4 | HAVING | keeps only the groups that satisfy a condition | groups |
| 5 | SELECT | computes the output columns and gives them their aliases (window functions run here too) | rows or groups |
| 6 | DISTINCT | removes duplicate output rows | output rows |
| 7 | ORDER BY | sorts the result | output rows |
| 8 | OFFSET / FETCH (or LIMIT) | skips and keeps a number of rows | sorted rows |
Set operations such as UNION (article 15) combine the outputs of several SELECTs after step 6, and a final ORDER BY and row limit then apply to the combined result.
Each step takes the result of the previous step as its input. That's the key to everything in this article: a clause can only use what earlier steps have produced.
Watching the steps
The example below builds the result of one query step by step. The query finds the customers who spent more than 100 on non-cancelled orders, biggest spender first, top two only:
CREATE TABLE orders (
order_id INTEGER PRIMARY KEY,
customer_id INTEGER NOT NULL,
status VARCHAR(10) NOT NULL,
total DECIMAL(8, 2) NOT NULL
);
INSERT INTO orders VALUES
(1, 10, 'shipped', 120.00), (2, 10, 'shipped', 80.00),
(3, 20, 'cancelled', 400.00), (4, 20, 'shipped', 40.00),
(5, 30, 'shipped', 300.00), (6, 30, 'pending', 25.00),
(7, 40, 'shipped', 150.00);
-- Step 2, WHERE: cancelled orders are removed row by row
SELECT * FROM orders WHERE status <> 'cancelled' ORDER BY order_id;
-- Step 3, GROUP BY: one row per customer, aggregates computed per group
SELECT customer_id, COUNT(*) AS n, SUM(total) AS spent
FROM orders
WHERE status <> 'cancelled'
GROUP BY customer_id
ORDER BY customer_id;
-- Steps 4-8: HAVING keeps big spenders, then SELECT, ORDER BY and LIMIT
SELECT customer_id, COUNT(*) AS n, SUM(total) AS spent
FROM orders
WHERE status <> 'cancelled'
GROUP BY customer_id
HAVING SUM(total) > 100
ORDER BY spent DESC
LIMIT 2;
order_id | customer_id | status | total
----------+-------------+---------+--------
1 | 10 | shipped | 120.00
2 | 10 | shipped | 80.00
4 | 20 | shipped | 40.00
5 | 30 | shipped | 300.00
6 | 30 | pending | 25.00
7 | 40 | shipped | 150.00
(6 rows)
customer_id | n | spent
-------------+---+--------
10 | 2 | 200.00
20 | 1 | 40.00
30 | 2 | 325.00
40 | 1 | 150.00
(4 rows)
customer_id | n | spent
-------------+---+--------
30 | 2 | 325.00
10 | 2 | 200.00
(2 rows)
Follow customer 20 through the steps. Their cancelled order of 400.00 was removed in step 2, so step 3 only summed the remaining 40.00, and step 4's HAVING then removed the whole group. If WHERE ran after grouping, customer 20 would have totalled 440.00 and appeared in the result. Order matters.
Customer 40 survived HAVING with 150.00 but was cut by LIMIT 2 in the last step. The limit applies to the sorted result, which is what makes "top n" queries work (article 10).
What the order explains
Column aliases don't exist in WHERE
An alias such as gross is created in step 5. WHERE runs in step 2, before the alias exists. ORDER BY runs in step 7, after it exists:
CREATE TABLE orders (order_id INTEGER PRIMARY KEY, customer_id INTEGER, total DECIMAL(8, 2));
INSERT INTO orders VALUES (1, 10, 120.00), (2, 10, 80.00), (3, 20, 40.00), (4, 30, 300.00);
-- 1. An alias can be used in ORDER BY: it runs after SELECT
SELECT order_id, total * 1.2 AS gross
FROM orders
ORDER BY gross DESC;
-- 2. ...but not in WHERE, which runs before SELECT
SELECT order_id, total * 1.2 AS gross
FROM orders
WHERE gross > 100;
-- 3. Repeat the expression instead (or use a subquery, article 23)
SELECT order_id, total * 1.2 AS gross
FROM orders
WHERE total * 1.2 > 100
ORDER BY order_id;
-- 4. Aggregates don't exist yet in WHERE: filter groups with HAVING
SELECT customer_id FROM orders WHERE SUM(total) > 150 GROUP BY customer_id;
SELECT customer_id, SUM(total) AS spent
FROM orders
GROUP BY customer_id
HAVING SUM(total) > 150
ORDER BY customer_id;
order_id | gross
----------+---------
4 | 360.000
1 | 144.000
2 | 96.000
3 | 48.000
(4 rows)
psql:/workspace/solution.sql:12: ERROR: column "gross" does not exist
LINE 3: WHERE gross > 100;
^
order_id | gross
----------+---------
1 | 144.000
4 | 360.000
(2 rows)
psql:/workspace/solution.sql:21: ERROR: aggregate functions are not allowed in WHERE
LINE 1: SELECT customer_id FROM orders WHERE SUM(total) > 150 GROUP ...
^
customer_id | spent
-------------+--------
10 | 200.00
30 | 300.00
(2 rows)
The second and fourth statements fail, and both error messages follow directly from the logical order:
column "gross" does not exist: in step 2, there's no column calledgrossyet. Repeat the expression inWHERE, or compute it in a subquery or CTE and filter outside it (articles 23 and 24).aggregate functions are not allowed in WHERE:WHEREfilters individual rows, before any groups exist, so there's no group total to compare. Conditions on aggregates belong inHAVING.
Products differ a little here, and these are the cases where they relax the standard rule:
| Alias used in | Standard SQL | PostgreSQL | MySQL | SQL Server | Oracle 23ai+ | SQLite |
|---|---|---|---|---|---|---|
WHERE | no | no | no | no | no | yes |
GROUP BY | no | yes | yes | no | yes | yes |
HAVING | no | no | yes | no | yes | yes |
ORDER BY | yes | yes | yes | yes | yes | yes |
The portable habit is simple: use aliases only in ORDER BY, and repeat the expression (or use a subquery) everywhere else.
WHERE filters rows, HAVING filters groups
Both clauses filter, but at different stages. A condition on an individual row's values, such as status <> 'cancelled', belongs in WHERE. A condition on a group's aggregate, such as SUM(total) > 100, belongs in HAVING.
You can put a plain row condition in HAVING if it's on a grouped column, but it's less clear, and it can be less efficient: unless the optimizer moves the condition before grouping (PostgreSQL does, not every product does), the database builds and aggregates groups it's about to throw away. Filter as early as possible.
ORDER BY can sort by things that aren't selected
Because ORDER BY runs late, it can use output aliases and column positions. It can also use columns from the FROM tables that you didn't select, for example SELECT name FROM customers ORDER BY signup_date. There's one exception. With DISTINCT, duplicates are removed in step 6, so the sort can only use columns that are in the output. PostgreSQL reports for SELECT DISTINCT, ORDER BY expressions must appear in select list, and MySQL and SQL Server have similar errors.
Window functions can't be filtered in WHERE
Window functions, such as ROW_NUMBER() for numbering rows (Part 6), are computed in step 5. So you can't write WHERE ROW_NUMBER() OVER (...) = 1. The standard solution is to compute the window function in a subquery or CTE, then filter in the outer query. Some products (Snowflake, BigQuery, Databricks, DuckDB, Teradata and Oracle AI Database 26ai) add a non-standard QUALIFY clause that filters on window functions directly.
LIMIT applies last
LIMIT 2 (or FETCH FIRST 2 ROWS ONLY) keeps the first two rows of the sorted result. Without an ORDER BY, "the first two rows" is whatever order the database happened to produce, which can change from run to run.
Logical order is not execution order
The logical order describes what the result must mean, not how the database computes it. The optimizer is free to execute the query any way that produces the same result. For example, it can:
- use an index to find only the matching rows instead of scanning the whole table and then filtering;
- push a
WHEREcondition into a join or a subquery; - join tables in a different order from the one you wrote;
- stop sorting early when it only needs the first few rows of a
LIMIT.
So the logical order is a tool for reasoning about correctness: which names are visible where, and which rows survive each step. For performance, you look at the actual execution plan (article 67).
What's current
- Oracle AI Database 26ai (and 23ai before it) accepts column aliases in
GROUP BY(and positions, when thegroup_by_position_enabledparameter is set) and aliases inHAVING, and addsGROUP BY ALL, which groups by every non-aggregated column in the select list. These are extensions, not standard SQL. - The standard (SQL) still requires the expression itself in
WHERE,GROUP BYandHAVING. OnlyORDER BYmay refer to output aliases. QUALIFYis spreading: most analytical databases have it, and Oracle AI Database 26ai added it, but PostgreSQL, MySQL and SQL Server don't. The subquery pattern works everywhere.
Common questions
Why doesn't SQL just let me use the alias in WHERE?
Because of the order. WHERE decides which rows exist before SELECT computes anything, so an output alias can't feed back into it. Products that allow it (such as SQLite) quietly substitute the expression, which is convenient but non-portable and can hide mistakes when an alias has the same name as a real column.
If the optimizer reorders everything, does the logical order still matter? Yes. It defines which queries are valid and what their results mean. The optimizer may only use shortcuts that produce exactly the result the logical order defines.
Can I use a column position like ORDER BY 2?
Yes. ORDER BY 2 sorts by the second output column. It's handy for quick queries but fragile in code, because adding a column to the select list silently changes the sort. Prefer names.
Is HAVING without GROUP BY allowed?
Yes. The whole table is then treated as one group. For example, SELECT COUNT(*) FROM orders HAVING COUNT(*) > 5 returns one row if there are more than five orders, and no rows otherwise.
Where does a JOIN's ON condition fit?
In step 1. ON decides how rows from the joined tables match while the working set is being built. For inner joins, a condition in ON and the same condition in WHERE give the same result. For outer joins, they don't, and article 13 explains why.
Summary
- The written order of a
SELECTdiffers from its logical order:FROM→WHERE→GROUP BY→HAVING→SELECT→DISTINCT→ORDER BY→OFFSET/FETCH/LIMIT. - Each step works on the output of the previous one, so a clause can only use what earlier steps produced.
- Output aliases exist only from
SELECTonward. In standard SQL, onlyORDER BYcan use them. WHEREfilters rows before grouping.HAVINGfilters groups after aggregation. Aggregates can't appear inWHERE.- Window functions are computed in
SELECT, so filter on them in an outer query. - The row limit applies last, to the sorted result.
- The logical order defines meaning. The optimizer can execute the query in any order that produces the same result.
Practice questions
This query fails in PostgreSQL. Explain the error in terms of the logical order, and fix it.
SELECT product_id, price * qty AS line_total
FROM order_items
WHERE line_total > 500;
Answer
WHERE (step 2) runs before SELECT (step 5), so the alias line_total doesn't exist yet, and PostgreSQL reports column "line_total" does not exist. Repeat the expression:
SELECT product_id, price * qty AS line_total
FROM order_items
WHERE price * qty > 500;
Or compute it in a subquery and filter outside: SELECT * FROM (SELECT product_id, price * qty AS line_total FROM order_items) AS t WHERE line_total > 500.
A report should show customers with at least three shipped orders. Which condition goes in WHERE and which in HAVING?
Answer
status = 'shipped' is a condition on individual rows, so it goes in WHERE and removes the other orders before grouping. "At least three" is a condition on each customer's group, so it goes in HAVING:
SELECT customer_id, COUNT(*) AS shipped_orders
FROM orders
WHERE status = 'shipped'
GROUP BY customer_id
HAVING COUNT(*) >= 3;
If you moved the status test into HAVING, the query would fail, because status isn't a grouped column. And even if it ran, the count would already include non-shipped orders, since grouping happens before HAVING.
In the step-by-step example, what would LIMIT 2 return without ORDER BY spent DESC?
Answer
Two of the three qualifying customers (10, 30 and 40), but there's no guarantee which two. Without ORDER BY, rows come out in whatever order the database produced them, which depends on how it executed the query and can change as the data or the plan changes. A row limit is only meaningful after a sort.
Why is SELECT DISTINCT city FROM customers ORDER BY signup_date rejected?
Answer
DISTINCT (step 6) collapses rows with the same city into one, before ORDER BY (step 7) runs. A city such as Leeds may stand for several customers with different signup dates, so there's no single signup_date to sort that row by. The sort can only use output columns. One fix is to say which date you mean, for example SELECT city FROM customers GROUP BY city ORDER BY MIN(signup_date).
Previous: SQL Tools and How to Run This Course's Examples
Next: SQL SELECT Basics: Choosing Columns, Expressions and Aliases

More in SQL Course
Quiz: SQL Dialect Differences (PostgreSQL, MySQL, SQL Server, Oracle, SQLite)
Twenty-four questions on how the major SQL databases differ: limiting rows, concatenation, empty strings, identifier case, upserts, identity columns, transactional DDL, error handling, isolation defaults, booleans, set operations, RETURNING, dates and typing.
Quiz: SQL Delicate Details
Twenty-five questions on SQL's subtle corners: NULLs in aggregates, IN and CHECK, sort order of NULLs, rounding, CHAR padding, window frame defaults, identity gaps, LIKE escapes, empty groups, set operations and multi-column updates.
Quiz: SQL Interview Questions
Thirty SQL questions of the kind asked in developer and analyst interviews: WHERE vs HAVING, DELETE vs TRUNCATE, keys, joins, duplicates, Nth-highest values, window functions, ACID, isolation, locking, indexes, views, procedures and performance.
Quiz: SQL Course Final Exam (All 15 Parts)
The final exam for the SQL course: thirty questions across all fifteen parts, from query processing, NULLs, joins and aggregation through windows, data changes, types, design, indexes, security, transactions, procedural SQL and tuning.
Discussion
Sign in to ask a question or share what you learned.