Interview Q&A · SQL · 12 questions in this topic
Subqueries — SQL Interview Q&A
Queries inside queries — scalar, IN, EXISTS, correlated execution and the decorrelation mindset. Part of Subqueries, CTEs & Views · 192 questions in the SQL bank.
What is a subquery and where can it appear?
Answer
A subquery is a SELECT nested inside another statement — in SELECT (scalar per-row value), FROM (derived table), WHERE (IN/EXISTS/comparison), or even INSERT sources. Inner executes per its correlation: uncorrelated once, correlated per outer row.
Nesting expresses stepwise logic; CTEs express the same steps readably — prefer CTEs past one level.
Example
-- scalar subquery in SELECT: SELECT name, (SELECT COUNT(*) FROM orders o WHERE o.customer_id = c.id) AS orders FROM customers c;
💡 Uncorrelated-once vs correlated-per-row is the execution distinction.
What is a scalar subquery and what must it guarantee?
Answer
A scalar subquery returns exactly one value (one row, one column) for use as an expression — per-row lookups, computed columns. Zero rows yield NULL; more than one row errors at runtime. Enforce singularity with aggregation, LIMIT 1, or a uniqueness guarantee.
Un-guarded scalar subqueries are runtime errors waiting for duplicate data.
Example
SELECT name, (SELECT MAX(total) FROM orders o WHERE o.customer_id = c.id) AS biggest_order FROM customers c;
IN vs EXISTS vs JOIN for subquery checks — how do you choose?
Answer
EXISTS: NULL-safe semi-join, short-circuits, ignores SELECT list — the default for correlated checks. IN: concise for static lists and uncorrelated sets, NULL-poisoned in NOT form. JOIN: when you need columns from the other side (with fan-out risk).
Existence → EXISTS; values needed → JOIN; static list → IN.
Key points
- 1EXISTS — safe, short-circuit, correlated.
- 2IN — concise, static lists, NOT-form poisoned.
- 3JOIN — brings columns, risks fan-out.
Example
SELECT * FROM customers c WHERE EXISTS (SELECT 1 FROM orders o WHERE o.customer_id = c.id);
💡 Match operator to need (existence vs columns) — the selection rule.
What is a correlated subquery and why can it be slow?
Answer
A correlated subquery references outer-query columns, so it logically re-executes per outer row — O(rows × inner cost). Planners often decorrelate (rewrite to joins/semi-joins), but complex correlation resists it. Rewrite manually to JOIN/GROUP BY or window forms when EXPLAIN shows per-row execution.
Correlation is expressiveness at per-row price — decorrelate deliberately.
Example
-- per-employee dept average, recomputed per row (slow shape): SELECT name, (SELECT AVG(salary) FROM employees e2 WHERE e2.department = e1.department) FROM employees e1;
💡 Per-outer-row execution is the cost model to state.
How do derived tables (subqueries in FROM) work?
Answer
A FROM subquery produces a named temporary relation (alias mandatory in most engines) that the outer query treats as a table — pre-aggregation, filtering, and shaping before joining. CTEs express the same with better readability and reuse.
Derived tables are scope-limited to their query; CTEs are scope-limited but referenceable multiple times.
Example
SELECT d.dept_id, t.avg_pay FROM departments d JOIN (SELECT department, AVG(salary) AS avg_pay FROM employees GROUP BY department) t ON t.department = d.dept_id;
💡 Mandatory alias is the syntax detail; pre-shape-before-join is the purpose.
How do you compare against aggregates (e.g. above-average salaries)?
Answer
Scalar aggregate subquery in WHERE (global average), or pre-aggregated derived table joined back (per-group average), or window average with outer filter (keeps row detail). Direct aggregates in WHERE are illegal — no groups exist yet.
Three shapes, one rule: compute the benchmark, then compare outside aggregation.
Example
SELECT name, salary FROM employees WHERE salary > (SELECT AVG(salary) FROM employees);
What is the difference between `IN`, `ANY`/`SOME` and `ALL`?
Answer
IN matches set membership (= ANY). = ANY/SOME compare against at least one (equivalent to IN for =). ALL compares against every value (> ALL means above the max). NULLs in the set poison NOT IN and ALL comparisons to UNKNOWN.
ANY/SOME/ALL generalize comparisons beyond equality; IN is the equality special case.
Example
SELECT * FROM employees WHERE salary > ALL (SELECT salary FROM employees WHERE department = 'Intern');
💡 ANY-one vs ALL-every is the quantifier split.
How do you find the Nth highest salary (classic interview question)?
Answer
Dense-rank window (DENSE_RANK() OVER (ORDER BY salary DESC), filter = N) — handles ties correctly and reads clearly. Correlated COUNT (salaries greater than me = N-1) is the no-window fallback. LIMIT/OFFSET top-N breaks on ties.
Lead with DENSE_RANK; note ROW_NUMBER (arbitrary tie-break) vs RANK (gaps) vs DENSE_RANK (no gaps).
Example
SELECT * FROM (SELECT *, DENSE_RANK() OVER ( ORDER BY salary DESC) AS r FROM employees) t WHERE r = 2; -- second-highest distinct salary
💡 DENSE_RANK for ties is the judgment that separates memorized from understood.
How do you check existence efficiently (EXISTS vs COUNT)?
Answer
EXISTS stops at the first match (short-circuit, index-friendly); COUNT(*) > 0 scans everything countable. For presence questions EXISTS is both clearer and faster — COUNT answers how-many, a different question.
Never COUNT to test existence in production code.
Example
-- fast existence: SELECT 1 WHERE EXISTS (SELECT 1 FROM orders WHERE customer_id = 7);
💡 Short-circuit vs full-count is the efficiency story in one line.
Can subqueries go in SELECT, and what are the risks?
Answer
Yes — scalar subqueries compute per-row values inline. Risks: per-row execution cost (N+1-shaped), runtime multi-row errors on duplicate data, and NULL surprises on empty matches. Prefer LEFT JOIN to pre-aggregated derived tables for bulk lookups.
One scalar subquery is clarity; five is a performance incident.
Example
-- correlated per-row lookup (fine small, costly huge): SELECT c.name, (SELECT COUNT(*) FROM orders o WHERE o.customer_id = c.id) AS n FROM customers c;
How do you update/delete based on another table (correlated writes)?
Answer
UPDATE/DELETE with EXISTS or IN subqueries targeting related rows — preview with SELECT first, run in a transaction, verify counts. Correlate exactly; uncorrelated predicates nuke whole tables.
Write-queries deserve the strictest review: SELECT-preview plus transaction plus count-check.
Example
BEGIN; DELETE FROM sessions s WHERE NOT EXISTS (SELECT 1 FROM users u WHERE u.id = s.user_id); -- verify count... COMMIT;
What is query decorrelation (conceptually)?
Answer
Decorrelation rewrites per-row correlated subqueries into set operations (joins, semi-joins, group-bys) the engine executes once — planners do it automatically for simple shapes; engineers do it manually for the rest. Recognizing correlated shapes in EXPLAIN (dependent subplans, loops) triggers the rewrite.
Think once-not-per-row is the optimization instinct.
Example
-- correlated (per row) -> decorrelated (single join+group): -- ... EXISTS (...) ==> ... JOIN (SELECT key GROUP BY key) ...
Learn this topic
Recommended resourcesAffiliate links · may earn us a commission