# Topic 33: Subqueries
Scalar subqueries, multi-row subqueries, subqueries in SELECT/FROM/WHERE, and optimizer flattening.
1. Definition
A subquery (or nested query) is a complete SELECT statement nested inside an outer SQL statement (SELECT, INSERT, UPDATE, or DELETE).
2. Explain Like I'm 5
A subquery is a question inside a question: "Who earned more than the average salary?" First, the inside question finds the average salary ($50k). Then, the outside question finds who earns more than $50k.
3. Animation & Visual Simulation
Interactive Engine TraceSubqueries Visual Simulator
SELECT name, department, salary
FROM employees
WHERE salary = (SELECT MAX(salary) FROM employees);Active InputStep 1: Input & Parsing Stage
Initiating Subqueries
Checking Table Invariants
The database engine inspects active tables, verifies permissions, and prepares the physical operation.
4. Real-World Example
Finding all employees who earn more than the company-wide average salary.
| name | salary |
|---|---|
| Alice | $120,000 (Above average) |
| Bob | $80,000 (Below average) |
| Charlie | $100,000 (Equals average: $100k) |
5. SQL Syntax
ANSI SQL / PostgreSQL DialectSELECT name, salary FROM employees WHERE salary > (SELECT AVG(salary) FROM employees);
SELECT department, avg_sal FROM ( SELECT department, AVG(salary) AS avg_sal FROM employees GROUP BY department ) AS dept_summary WHERE avg_sal > 90000;
6. Important Rules & Behaviors
| Rule | Behavioral Explanation |
|---|---|
| Scalar Subquery Expectation | A scalar subquery used with comparison operators (=, >, <) must return at most 1 value; returning 2+ rows causes a runtime error. |
| Derived Table Alias | In ANSI SQL, every subquery in a FROM clause must be assigned a table alias. |
| Subquery Flattening | Modern Cost-Based Optimizers rewrite subqueries into joins whenever mathematically possible. |
| Subquery classification | Scalar subqueries return 1 row & 1 column; multi-row subqueries return N rows; table subqueries act as derived tables. |
| Scalar subquery cardinality error | If a scalar subquery returns more than 1 row at runtime, the engine aborts the transaction with a fatal error. |
7. Deep Dive: Subquery Unnesting and Optimizer Flattening
Modern database optimizers do not naively execute subqueries independently if they can rewrite them into joins. This process is called subquery unnesting or subquery pull-up, allowing the optimizer to choose better join algorithms.
-- Written as Subquery: SELECT * FROM users WHERE id IN (SELECT user_id FROM orders); -- Optimizer automatically rewrites it into a Semi-Join: -- Hash Semi Join (users.id = orders.user_id)
8. Advantages & Disadvantages
Advantages
- •Enables expressive multi-step queries without temporary tables.
- •Allows dynamic filtering against calculated aggregates.
Disadvantages & Trade-offs
- •Complex nested subqueries become hard to read; CTEs are often clearer.
9. Common Interview Questions
Q1.What is the difference between a Scalar Subquery, Row Subquery, and Table Subquery?
1. Scalar Subquery: returns exactly one column and at most one row (e.g. SELECT (SELECT MAX(salary) FROM employees)); it can be used anywhere a literal constant is accepted. 2. Row Subquery: returns multiple columns for a single row (e.g. WHERE (col1, col2) = (SELECT a, b FROM tbl LIMIT 1)). 3. Table Subquery (Derived Table): returns multiple columns and multiple rows, used in the FROM clause with an alias.
Q2.What happens at runtime if a Scalar Subquery returns multiple rows?
The SQL query planner allows the query to compile, but when the execution engine runs and detects a second row emitted from the subquery, it immediately aborts the entire transaction with a fatal error: "more than one row returned by a subquery used as an expression". Always ensure scalar subqueries use aggregate functions (MAX, MIN) or LIMIT 1.
Q3.What is Query Decorrelation / Subquery Unnesting in the Cost-Based Optimizer?
Naive subquery execution runs the inner query repeatedly or creates intermediate spool tables. Modern optimizers perform Subquery Unnesting: they mathematically transform independent or semi-join subqueries into equivalent joins (Hash Join or Merge Join), allowing the planner to explore global join orders and index paths across the entire query tree.
Q4.Where can subqueries be placed in a SQL statement?
Subqueries can appear in: 1. SELECT list (scalar subquery generating computed columns), 2. FROM clause (derived tables acting as temporary relations), 3. WHERE clause (filtering with IN, EXISTS, or comparisons), 4. HAVING clause (filtering groups by subquery aggregations), 5. JOIN ON clause, and 6. UPDATE SET assignments.
Q5.What is the performance difference between a Derived Table Subquery vs a Common Table Expression (CTE)?
In modern databases (PostgreSQL 12+, MySQL 8+), the optimizer treats non-recursive CTEs and derived table subqueries identically: they are both inlined into the main query AST. However, CTEs are vastly more readable, can be referenced multiple times, and support recursive graph traversal.
10. Interview-Ready Answer
“Subqueries are nested SELECT statements used in WHERE, FROM, or SELECT clauses. While scalar subqueries return a single value for comparisons, multi-row subqueries work with IN or ANY. Modern optimizers unnest eligible subqueries into joins.”
11. Quick Test
What error occurs when executing "SELECT * FROM items WHERE price = (SELECT price FROM items);"?