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

Subqueries — SQL Interview Q&A

All SQL topics

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

Example.sqlsql
-- 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

Example.sqlsql
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

  1. 1EXISTS — safe, short-circuit, correlated.
  2. 2IN — concise, static lists, NOT-form poisoned.
  3. 3JOIN — brings columns, risks fan-out.

Example

Example.sqlsql
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.

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