Question presented to candidate: "You will see queries with a SELECT nested inside another SELECT. What is a subquery, what makes a subquery correlated, and how does that change how the database runs it? Show me one of each."
What a strong answer should cover:
- A subquery is a complete SELECT nested inside another statement, in WHERE, in the SELECT list, in FROM (a derived table) or in HAVING
- The shapes: scalar (one value), row, column list for
IN, and table (a derived table in FROM) - A non-correlated subquery does not reference the outer query, so it can be evaluated once (PostgreSQL shows it as an
InitPlan) - A correlated subquery references a column of the outer row, so logically it runs once per outer row (PostgreSQL shows a
SubPlanwithloopsequal to the outer row count) - Trade-offs: correlated subqueries are clear but can be slow without an index on the correlation column; rewrites with a JOIN plus GROUP BY, a window function, or LATERAL
- Engine detail: a scalar subquery that returns two rows is an error in PostgreSQL but silently uses the first row in SQLite
Code / implementation expected: Yes β one plain subquery (above the company average) and one correlated subquery (above the own-department average).
Schema used by the examples: