Skip to content
Back to 50 Concepts
Topic 33 of 50query-executionIntermediate

# 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).

Relational Invariant:Deterministic relational algebra contract evaluated by the Cost-Based Optimizer.

2. Explain Like I'm 5

Intuitive mental model for beginners

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 Trace
Interactive Engine Simulation

Subqueries Visual Simulator

Step 1 of 3
SQL>SELECT name, department, salary FROM employees WHERE salary = (SELECT MAX(salary) FROM employees);Active Input

Step 1: Input & Parsing Stage

Engine Action: Validate SQL syntax and resolve schema metadata for Subqueries
SQL Input

Initiating Subqueries

Schema Catalog

Checking Table Invariants

How the Database Executes This:

The database engine inspects active tables, verifies permissions, and prepares the physical operation.

💡 Nested parentheses in math: Calculate the inner equation inside parentheses first, and feed its result to the outer equation.

4. Real-World Example

Finding all employees who earn more than the company-wide average salary.

Employees
namesalary
Alice$120,000 (Above average)
Bob$80,000 (Below average)
Charlie$100,000 (Equals average: $100k)
Relational walkthrough: The subquery (SELECT AVG(salary) FROM employees) evaluates to 100,000.

5. SQL Syntax

ANSI SQL / PostgreSQL Dialect
Step 1: Scalar subquery in WHERE
SELECT name, salary
FROM employees
WHERE salary > (SELECT AVG(salary) FROM employees);
A scalar subquery returns exactly one row and one column.
Step 2: Derived table in FROM clause
SELECT department, avg_sal
FROM (
  SELECT department, AVG(salary) AS avg_sal
  FROM employees
  GROUP BY department
) AS dept_summary
WHERE avg_sal > 90000;
Derived tables in FROM must have an alias.

6. Important Rules & Behaviors

RuleBehavioral Explanation
Scalar Subquery ExpectationA scalar subquery used with comparison operators (=, >, <) must return at most 1 value; returning 2+ rows causes a runtime error.
Derived Table AliasIn ANSI SQL, every subquery in a FROM clause must be assigned a table alias.
Subquery FlatteningModern Cost-Based Optimizers rewrite subqueries into joins whenever mathematically possible.
Subquery classificationScalar subqueries return 1 row & 1 column; multi-row subqueries return N rows; table subqueries act as derived tables.
Scalar subquery cardinality errorIf 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)
Caution: Scalar subqueries in the SELECT projection list that reference outer rows can trigger slow row-by-row execution if not unnested.

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

Scenario Question:

What error occurs when executing "SELECT * FROM items WHERE price = (SELECT price FROM items);"?

Select your answer: