0Pricing
SQL Interview Prep · Lesson

Sorting by Expressions and Aliases

Where alias references are legal in ORDER BY and how to sort by computed logic.

ORDER BY Is More Flexible Than You Think

A surprising number of candidates believe ORDER BY can only reference plain columns. In fact you can sort by expressions, aliases, column positions, and CASE logic.

Interviewers use this to test whether you understand logical query execution order, because ORDER BY runs after SELECT, which is exactly why aliases work here but not in WHERE.

Why Aliases Are Legal in ORDER BY

Recall the logical execution order: FROM, WHERE, GROUP BY, HAVING, SELECT, then ORDER BY. Because SELECT runs before ORDER BY, the column aliases you defined in SELECT already exist when ORDER BY evaluates.

That is the precise reason an alias works in ORDER BY but fails in WHERE, a question interviewers love to connect back to execution order.

SELECT name, salary * 12 AS annual_pay
FROM employees
ORDER BY annual_pay DESC;

All lessons in this course

  1. Multi-Column Sorting and NULL Placement
  2. LIMIT, OFFSET and FETCH FIRST
  3. Returning the Top-N Rows Reliably
  4. Sorting by Expressions and Aliases
← Back to SQL Interview Prep