Interview Q&A · SQL · 10 questions in this topic

SELECT Essentials — SQL Interview Q&A

All SQL topics

Projection, aliases, expressions and the logical order SQL actually executes in. Part of SELECT & Filtering · 192 questions in the SQL bank.

What is the logical order of query execution (why WHERE cannot use SELECT aliases)?

Answer

SQL executes FROM, then WHERE, GROUP BY, HAVING, SELECT, ORDER BY, LIMIT — definition order (SELECT first) is not execution order. WHERE runs before SELECT, so it cannot see column aliases; ORDER BY runs after, so it can. GROUP BY also precedes SELECT, which is why only grouped/aggregated expressions are valid.

This ordering explains half of all SQL error messages.

Key points

  1. 1FROM → WHERE → GROUP BY → HAVING → SELECT → ORDER BY → LIMIT.
  2. 2WHERE cannot use aliases (runs before SELECT).
  3. 3ORDER BY can (runs after).

Example

Example.sqlsql
-- INVALID: WHERE runs before the alias exists
-- SELECT salary * 12 AS annual FROM employees WHERE annual > 500000;
-- VALID: repeat the expression, or filter outside
SELECT salary * 12 AS annual FROM employees
ORDER BY annual DESC;

💡 Recite the seven-step order — interviewers treat it as the key to the whole language.

How do column aliases (AS) work?

Answer

AS renames an output column (SELECT salary * 12 AS annual) for readability and client consumption. The AS keyword is optional but recommended; aliases with spaces need quoting ("annual pay"). Aliases are usable in ORDER BY but not in WHERE/GROUP BY (execution order).

Quote style varies ("..." standard, [...] SQL Server, `...` MySQL) — another dialect wrinkle.

Example

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

How do you compute with expressions in SELECT?

Answer

SELECT evaluates arithmetic, string concatenation (|| standard, + in SQL Server, CONCAT everywhere), CASE expressions, and function calls per row. Integer division truncates — cast one side for decimals. Division by zero errors (or NULL, per engine) so NULLIF(denominator, 0) guards it.

Compute close to the data (in SQL) rather than fetching raw rows to divide in application code.

Example

Example.sqlsql
SELECT name, salary / 12.0 AS monthly,  -- decimal, not truncated
       salary / NULLIF(months, 0) AS guarded
FROM employees;

Recommended resourcesAffiliate links · may earn us a commission

Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Cloud hosting for side projectsShip the portfolio project that gets you hired — free credits for new accounts.Claim credits