Scrivio Interview library
ConceptFoundations6 min read · updated 12 November 2026

In what logical order does SQL evaluate FROM, WHERE, GROUP BY, HAVING, SELECT, DISTINCT, ORDER BY and LIMIT? Use it to explain why WHERE cannot reference a SELECT alias but ORDER BY can.

Logically, SQL evaluates FROM and the joins first, then WHERE, GROUP BY, HAVING, window functions, SELECT, DISTINCT, ORDER BY and finally LIMIT or OFFSET. Aliases are created in SELECT, which runs after WHERE, so WHERE cannot see them, while ORDER BY runs after SELECT and can. This is a logical model of what the result means; the optimizer may execute steps in a different physical order as long as the result is the same.

Why this question is asked

We write SQL starting with SELECT, but the database does not read it in that order. Knowing the real logical order answers a whole family of everyday puzzles: why an alias works in ORDER BY but not in WHERE, why we cannot filter on ROW_NUMBER() directly, why an aggregate is not allowed in WHERE, and why a LEFT JOIN filtered in WHERE loses rows. Interviewers ask it because it shows whether a developer reasons about SQL or just tries variations until it runs. In this answer, we will walk through the clauses in logical order with one example, use the order to explain the alias rules, deal with window functions, and separate the logical model from what the optimizer actually does.

1The Clauses in Logical Order

Each clause takes the table produced by the previous step and produces a new one. Think of it as a pipeline of virtual tables. FROM, together with any joins, builds the starting rows. WHERE keeps only rows whose condition is true. GROUP BY collapses rows into groups. HAVING filters those groups. Window functions are then computed over the remaining rows. SELECT computes the output expressions and gives them their aliases. DISTINCT removes duplicate output rows. ORDER BY sorts. LIMIT and OFFSET cut the sorted result.

Step throughLogical processing order of a SELECT
  1. FROM and JOINsbuild the input rows
  2. WHEREfilter rows; aggregates and aliases do not exist yet
  3. GROUP BYform groups
  4. HAVINGfilter groups; aggregates are available
  5. Window functionsROW_NUMBER, SUM OVER, computed on surviving rows
  6. SELECTcompute expressions and define aliases
  7. DISTINCTremove duplicate output rows
  8. ORDER BYsort; aliases are visible here
  9. LIMIT / OFFSETkeep a slice of the sorted rows

9 steps in order. Play them, or step through them one at a time.

2Following One Query Through the Pipeline

Here is a query over orders(id, customer_id, total, status), with the size of the virtual table after each step as a comment.

SQL
SELECT customer_id, SUM(total) AS spent -- 6. 120 rows, alias 'spent' is born here
FROM orders -- 1. 10,000 rows
WHERE status = 'PAID' -- 2. 8,200 rows
GROUP BY customer_id -- 3. 950 groups
HAVING SUM(total) > 500 -- 4. 120 groups
ORDER BY spent DESC -- 8. 120 rows sorted by the alias
LIMIT 10; -- 9. 10 rows

Notice that HAVING repeats SUM(total) instead of using spent. In standard SQL, HAVING runs before SELECT, so the alias does not exist yet. Notice also why WHERE cannot contain SUM(total): at step 2 there are no groups yet, only single rows, so there is nothing to sum. That is the exact reason SQL has two filtering clauses: WHERE filters rows before grouping, and HAVING filters groups after it.

3Why WHERE Cannot Use a SELECT Alias but ORDER BY Can

The rule follows directly from the order. An alias is a name that SELECT gives to an expression. When WHERE runs, at step 2, SELECT has not run, so the name does not exist.

SQL
SELECT id, total * 1.19 AS gross
FROM orders
WHERE gross > 100; -- ERROR: column "gross" does not exist
SELECT id, total * 1.19 AS gross
FROM orders
WHERE total * 1.19 > 100 -- repeat the expression, or use a subquery
ORDER BY gross DESC; -- fine: ORDER BY runs after SELECT

ORDER BY runs at step 8, after SELECT has defined gross, so it can refer to it. If we want to filter on a computed value without repeating it, we move the computation into a subquery or CTE: SELECT * FROM (SELECT id, total * 1.19 AS gross FROM orders) t WHERE gross > 100. The inner SELECT has finished by the time the outer WHERE runs, so gross is now an ordinary column.

There is one detail in PostgreSQL: ORDER BY accepts a bare alias, but not an alias inside an expression. ORDER BY gross works, while ORDER BY gross + 1 fails, because in an expression PostgreSQL resolves names against the input columns. MySQL is more permissive.

4Window Functions Need a Subquery to Be Filtered

Window functions such as ROW_NUMBER() run after WHERE, GROUP BY and HAVING, just before SELECT finishes. So the same reasoning says we cannot filter on them in WHERE. To get the latest order per customer, we compute the row number in an inner query and filter outside.

SQL
SELECT * FROM (
SELECT o.*, ROW_NUMBER() OVER (PARTITION BY customer_id
ORDER BY created_at DESC, id DESC) AS rn
FROM orders o
) t
WHERE rn = 1; -- one row per customer, the newest
-- Snowflake, BigQuery, Databricks and DuckDB also offer:
-- SELECT * FROM orders QUALIFY ROW_NUMBER() OVER (...) = 1;

QUALIFY is a filter that some engines run after window functions, exactly where we need it. PostgreSQL and MySQL do not have it, so the subquery or CTE is the portable form.

5A Logical Model, Not an Execution Plan

The order we described defines what the result must be. It does not say how the database computes it. The optimizer is free to rearrange the work as long as the answer is the same. It pushes WHERE conditions down into joins so fewer rows are joined, reads an index that is already sorted instead of running ORDER BY, stops after the LIMIT when the order allows it, and may evaluate a HAVING condition that does not use aggregates as an early WHERE. EXPLAIN shows the physical plan, which often looks nothing like the logical pipeline.

Some databases also relax the alias rules as an extension. MySQL accepts aliases in GROUP BY and HAVING, and PostgreSQL accepts output column names in GROUP BY. These are convenient, but they are not standard SQL and they can be ambiguous when an alias has the same name as a real column, in which case the databases resolve it differently. For SQL that must run in several engines, and for code that other people read, it is safer to follow the logical order: repeat the expression or use a subquery.

6Follow-up questions

Why can SELECT DISTINCT not be combined with ORDER BY on a column that is not selected?

Because DISTINCT runs before ORDER BY and removes duplicates based only on the selected columns. A hidden column could have several values for one surviving row, so the database would not know which one to sort by. PostgreSQL rejects it; we either select the column or sort by an aggregate in a grouped query.

Does the logical order explain the LEFT JOIN filtered in WHERE problem?

Yes. The LEFT JOIN runs in step 1 and adds NULL-filled rows for unmatched customers. WHERE runs in step 2, and a condition on the right table is unknown for those NULLs, so it removes them, turning the outer join into an inner join. Moving the condition into the ON clause makes it part of step 1.

Where do window functions see their rows from?

From the result after WHERE, GROUP BY and HAVING. In a grouped query, a window function works on the groups, so SUM(SUM(total)) OVER () is valid and gives a grand total next to each group's total.

7Conclusion

In this answer, we followed a query through the logical order: FROM and joins, WHERE, GROUP BY, HAVING, window functions, SELECT, DISTINCT, ORDER BY, LIMIT. Because aliases are born in SELECT, WHERE and standard HAVING cannot use them while ORDER BY can, and window functions must be filtered from an outer query or with QUALIFY where it exists. The order describes the meaning of a query, not the physical plan, and vendor extensions that allow aliases elsewhere are convenient but not portable.

What to say in the interviewAbout 90 seconds aloud

Open with

The logical order is FROM with its joins first, then WHERE, then GROUP BY, HAVING, then window functions, then SELECT, DISTINCT, ORDER BY, and finally LIMIT and OFFSET.

Then, if they want more

Each step takes the virtual table from the previous step. That explains the alias question directly: an alias is defined in SELECT, and WHERE runs before SELECT, so when WHERE is evaluated the alias does not exist yet. ORDER BY runs after SELECT, so it can use the alias.

If I want to filter on a computed column without repeating the expression, I put it in a subquery or CTE, and the outer WHERE sees it as a normal column.

The same logic explains why aggregates are not allowed in WHERE, because groups do not exist yet, which is why we have HAVING, and why I cannot filter on ROW_NUMBER in WHERE, since window functions are computed after WHERE and HAVING. For that I use a subquery, or QUALIFY in engines like Snowflake or BigQuery.

I would add that this is a logical model of meaning, not the execution order: the optimizer pushes filters into joins, uses sorted indexes instead of sorting, and stops early for LIMIT. And MySQL lets you use aliases in GROUP BY and HAVING as an extension, which I avoid in portable code.

About this answer

Last updated
12 November 2026
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "In what logical order does SQL evaluate FROM, WHERE, GROUP BY, HAVING, SELECT, DISTINCT...": https://scrivio-interview-library.netlify.app/databases/sql-fundamentals/d78dfc2988/