Interview Q&A · SQL · 10 questions in this topic
SELECT Essentials — SQL Interview Q&A
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
- 1FROM → WHERE → GROUP BY → HAVING → SELECT → ORDER BY → LIMIT.
- 2WHERE cannot use aliases (runs before SELECT).
- 3ORDER BY can (runs after).
Example
-- 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
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
SELECT name, salary / 12.0 AS monthly, -- decimal, not truncated salary / NULLIF(months, 0) AS guarded FROM employees;
What is CASE (simple vs searched) and where can it appear?
Answer
CASE is SQL's conditional expression: simple form matches one value (CASE x WHEN 1 THEN ...), searched form tests conditions (CASE WHEN x > 0 THEN ...). It returns a value, so it appears anywhere values go — SELECT, WHERE, ORDER BY, GROUP BY. Every CASE needs ELSE (NULL default surprises) and END.
CASE pivots rows to columns, buckets ranges, and sorts custom orders — the Swiss-army expression.
Example
SELECT name, CASE WHEN salary >= 90000 THEN 'senior' WHEN salary >= 60000 THEN 'mid' ELSE 'junior' END AS band FROM employees;
💡 Returns-a-value-anywhere is the CASE mental model; bucketing is its flagship use.
How do you sort with ORDER BY (multi-column, directions, NULLs)?
Answer
ORDER BY sorts by expressions left-to-right, each ASC (default) or DESC. NULL placement is engine-defined by default (PostgreSQL: NULLS LAST for ASC) — specify NULLS FIRST/LAST explicitly for portable intent. Sorting without ORDER BY is never guaranteed, regardless of indexes or insertion order.
Top-N needs ORDER BY plus LIMIT; without ORDER BY, LIMIT returns arbitrary rows.
Example
SELECT name, salary FROM employees
ORDER BY department ASC, salary DESC
LIMIT 5;How does LIMIT / OFFSET pagination work, and what breaks at scale?
Answer
LIMIT n returns n rows; OFFSET m skips m first. Deep pages (OFFSET 100000) still scan and discard skipped rows — slow and unstable under concurrent writes (rows shift between pages). Keyset pagination (WHERE id > last_seen ORDER BY id LIMIT n) is stable and index-friendly.
OFFSET for admin UIs; keyset for user-facing infinite scroll and APIs.
Example
-- deep page: slow, unstable -- SELECT * FROM employees ORDER BY id LIMIT 20 OFFSET 100000; -- keyset: fast, stable SELECT * FROM employees WHERE id > 100000 ORDER BY id LIMIT 20;
💡 OFFSET scans what it skips is the performance insight; shifting rows is the correctness one.
What is the difference between `COUNT(*)`, `COUNT(col)` and `COUNT(DISTINCT col)`?
Answer
COUNT(*) counts rows (including all-NULL rows). COUNT(col) counts non-NULL values of that column. COUNT(DISTINCT col) counts distinct non-NULL values. The NULL-skipping of the latter two surprises everyone once.
Row-existence checks want COUNT(*) or EXISTS; value coverage wants COUNT(col).
Example
SELECT COUNT(*) AS rows, COUNT(bonus) AS with_bonus, -- skips NULLs COUNT(DISTINCT department) AS depts FROM employees;
How do you handle NULLs in results (COALESCE, NULLIF)?
Answer
COALESCE returns the first non-NULL argument — default substitution. NULLIF(a, b) returns NULL when a equals b — division guards and sentinel collapsing. Both are standard and nestable; IS NULL / IS NOT NULL test for nullity (= NULL never matches).
NULL means unknown, so any comparison with it is unknown, not true — the three-valued logic behind every NULL surprise.
Example
SELECT name, COALESCE(bonus, 0) AS bonus, salary / NULLIF(months, 0) AS rate FROM employees;
💡 COALESCE for defaults, NULLIF for guards is the pairing to memorize.
What is the difference between `WHERE` and `HAVING`?
Answer
WHERE filters rows before grouping/aggregation; HAVING filters groups after. Aggregates are illegal in WHERE (no groups exist yet) and mandatory-context in HAVING. Both can coexist: WHERE trims input rows, HAVING trims output groups.
Execution order (WHERE → GROUP BY → HAVING) is the whole explanation.
Example
SELECT department, AVG(salary) AS avg_pay FROM employees WHERE age > 25 -- row filter first GROUP BY department HAVING AVG(salary) > 60000; -- group filter after
How do you sort case-insensitively or by custom orders?
Answer
LOWER(col) (or a case-insensitive collation) normalizes case for ordering; CASE in ORDER BY encodes custom sequences (status priority, size tiers). Functional expressions need matching expression indexes to stay fast.
Collation (column or query-level COLLATE) is the engine-native answer where available.
Example
SELECT name FROM employees ORDER BY LOWER(name); SELECT name, status FROM tickets ORDER BY CASE status WHEN 'urgent' THEN 0 WHEN 'high' THEN 1 ELSE 2 END;
Learn this topic
Recommended resourcesAffiliate links · may earn us a commission