SQL · Queries that survive scale
How does a SELECT statement execute?
Short answer
You write SELECT first, but logically the database evaluates FROM and joins, then WHERE, GROUP BY, HAVING, SELECT, ORDER BY, and LIMIT. SELECT aliases are not available in WHERE.
The written order of a SELECT is not the logical evaluation order. That explains why a column alias works in ORDER BY but not in WHERE, and why aggregated expressions belong in HAVING.
SELECT c.region,
COUNT(*) AS order_count,
SUM(o.total_cents) AS revenue_cents
FROM orders o
JOIN customers c ON c.id = o.customer_id
WHERE o.created_at >= '2026-01-01'
GROUP BY c.region
HAVING COUNT(*) >= 10
ORDER BY revenue_cents DESC
LIMIT 5;Logical evaluation order
- FROM and JOIN build the working set of rows
- WHERE filters individual rows before aggregation
- GROUP BY collapses rows into groups
- HAVING filters groups after aggregation
- SELECT computes output expressions and aliases
- ORDER BY sorts the result, then LIMIT or OFFSET restricts it
The optimizer can reorder physical work as long as the result matches this logical meaning. A predicate may be pushed below a join, or a sort may be skipped when an index already provides the order.
Follow-ups you should expect
Interviewers use these to check whether the first answer was understanding or memorisation.
- 1Why can you use a SELECT alias in ORDER BY but not in WHERE?
- 2What is the difference between LIMIT and a WHERE filter?
- 3Does the database always execute clauses in the written order?
- 4How does DISTINCT fit into the logical order?
Say it in the interview
A SELECT is written starting with output columns, but logically the database builds the row set from FROM and joins, then filters with WHERE. It groups and filters groups with GROUP BY and HAVING, computes the select list, sorts with ORDER BY, and applies LIMIT. That order explains alias visibility and why aggregate filters belong in HAVING. The optimizer can still change physical execution while preserving those semantics.
Use this as a model, not a script. Saying it in your own words is what makes it survive follow-up pressure.
Related questions
Reading is step one
Now say it out loud.
Understanding an answer and delivering it under pressure are different skills. Rehearse this topic in a live SQL mock interview and get scored feedback on depth, clarity and confidence.