Question presented to candidate: "We write a query starting with SELECT, but the database does not run it top to bottom. Walk me through the order in which the clauses are logically evaluated, and use it to explain why you can use a column alias in ORDER BY but not in WHERE."
What a strong answer should cover:
- The logical order: FROM and JOINs, then WHERE, GROUP BY, HAVING, window functions, SELECT, DISTINCT, ORDER BY, and finally LIMIT / OFFSET
- Consequences: WHERE cannot see aggregates or SELECT aliases, HAVING filters groups, window functions cannot be filtered in the same query level, ORDER BY can use aliases
- The difference between this logical order (what the query means) and the physical plan (what the engine actually does, such as pushing a filter into a scan)
- Engine differences: SQLite and MySQL accept some aliases where the standard and PostgreSQL do not
- The fix when you need a later value earlier: wrap the query in a subquery or CTE
Code / implementation expected: Optional โ explain with one grouped query, ideally showing the alias error and the subquery fix.
Schema used by the examples: