Chapter 6 of 12
Course Progress0 of 12 completed (0%)

SQL & Relational Database Mastery · Chapter 6 · ~15 min · Advanced

Subqueries & Common Table Expressions (CTEs)

Replace unreadable spaghetti subqueries with modular CTE pipelines and traverse complex hierarchical trees with RECURSIVE queries.

  • Construct scalar, column, and table subqueries in SELECT, WHERE, and FROM clauses
  • Understand correlated subquery execution mechanics and compare performance with JOINs
  • Refactor nested 'spaghetti SQL' into clean, readable CTE pipelines using WITH
  • Traverse organizational hierarchies and graph structures with RECURSIVE CTEs

Subqueries & Common Table Expressions (CTEs): learn it visually

Replace spaghetti subqueries with readable CTE pipelines and traverse hierarchical organizational trees with RECURSIVE queries.

Subqueries & Common Table Expressions (CTEs)Replace spaghetti subqueries with readable CTE pipelines and traverse hierarchical organizational trees with RECURSIVE queries.UNDERSTANDNested subqueryFOLLOW THE FLOWNamed CTE stepsAPPLY ITReadable querySubqueries & Common Table Expressions (CTEs)Replace spaghetti subqueries with readable CTE pipelines and traverse hierarchical organizational trees with RECURSIVE queries.UNDERSTANDNested subqueryFOLLOW THE FLOWNamed CTE stepsAPPLY ITReadable query

1Intuition: The 3 Cardinalities of Subqueries

A subquery is simply a query nested inside another SQL statement. The database optimizer treats the result of a subquery depending on its cardinality:

Scalar Subquery

Returns exactly 1 row and 1 column. Valid anywhere a single constant value is expected (e.g., SELECT list, WHERE comparison amount > (SELECT ...)).

Column Subquery

Returns multiple rows but exactly 1 column. Valid with set membership operators: IN, ANY, and ALL.

Table Subquery (Derived Table)

Returns multiple rows and multiple columns. Placed in the FROM or JOIN clause and requires a mandatory alias.

Concept Check

What happens if a scalar subquery placed in the SELECT clause (e.g., SELECT id, (SELECT bonus FROM bonuses WHERE bonuses.user_id = users.id) FROM users;) returns 2 rows for a single user?

2Architecture: From Nested Subqueries to CTE Pipelines

Nested subqueries suffer from inside-out reading order: to understand what a query does, you must find the deepest nested parenthesis 50 lines down, figure out what it produces, and mentally bubble up.

Common Table Expressions (WITH) flip this paradigm. They execute like named functions in Python or TypeScript, establishing a top-to-bottom pipeline.

Wrong idea: All subqueries evaluate once and cache their answers

Outer Rows (100,000) × Inner Subquery Scan (100,000)
❌ 10 Billion Iterations: Massive nested loop freeze

Assuming correlated subqueries in WHERE (WHERE salary > (SELECT AVG(salary) FROM employees e2 WHERE e2.dept = e1.dept)) run in O(1). The inner query actually loops N times — once for every single row in the outer table.

Real system: Correlated subqueries execute per-row; JOINs and CTEs vectorize

WITH dept_avg AS (GROUP BY dept) JOIN employees ON ...
✅ Linear O(N+M): Aggregates compute once in memory; joined in a single pass

An independent subquery evaluates once before outer execution. A correlated subquery passes outer row variables to the inner query, triggering an O(N×M) nested loop unless rewritten into a JOIN or pre-aggregated CTE.

-- RECURSIVE CTE: Traversal of an Employee Hierarchy Tree
WITH RECURSIVE employee_hierarchy AS (
    -- 1. ANCHOR MEMBER: Find root nodes (CEO with no manager)
    SELECT
        employee_id,
        name,
        manager_id,
        0 AS depth_level,
        name AS management_chain
    FROM employees
    WHERE manager_id IS NULL

    UNION ALL

    -- 2. RECURSIVE MEMBER: Join children to the prior generation
    SELECT
        e.employee_id,
        e.name,
        e.manager_id,
        eh.depth_level + 1,
        eh.management_chain || ' -> ' || e.name
    FROM employees e
    INNER JOIN employee_hierarchy eh ON e.manager_id = eh.employee_id
)
SELECT * FROM employee_hierarchy ORDER BY depth_level, employee_id;
Concept Check

Why can a correlated subquery in a WHERE clause perform drastically worse than an equivalent INNER JOIN?

3Interactive Visual: Pipeline Builder & Hierarchy Climber

Switch between the linear CTE Pipeline builder and the Recursive Org Chart Climber to watch how CTEs organize queries logically and traverse graph depths.

Interactive CTE Pipeline & Recursive Tree Engine

Active: Stage 4 of 4
Identify top tier accounts (total spend > $5,000)
vip_tier AS (
  SELECT * FROM customer_aggregates WHERE total >= 5000
)
Concept Check

In a RECURSIVE CTE, what component guarantees that recursion will eventually terminate?

4Bug Hunt: Refactor Broken Correlated Subquery to CTE

A slow, broken reporting query attempts to find employees who earn more than their department's average salary using a correlated subquery. Refactor the logic into a high-performance CTE using WITH dept_averages AS (...).

SQL Bug Hunt · Refactor to CTE Pipeline
SQL

🎯 Find and fix the bugs in the code above, then press Run & verify to test your solution.

Need a hint?

• Define WITH dept_averages AS (SELECT department_id, AVG(salary) AS avg_sal FROM employees GROUP BY department_id)

• Join employees e to dept_averages da ON e.department_id = da.department_id

• Add WHERE e.salary > da.avg_sal ORDER BY e.salary DESC

Concept Check

In modern PostgreSQL (version 12+) and SQLite (version 3.35+), what is the default execution behavior of a CTE defined with 'WITH'?

5Recap & Query Pipeline Best Practices

  • CTEs for Readability: Use CTEs to narrate data transformation steps linearly, eliminating impenetrable nested parentheses.
  • Vectorized Joins over Correlated Subqueries: Replace row-by-row subquery iterations with pre-aggregated CTEs or window functions for orders of magnitude performance gains.
  • Recursive CTE Mechanics: Always structure recursive queries into an Anchor Member (base rows), followed by UNION ALL, followed by the Recursive Member joining back to the CTE name.
  • Cycle Detection: When traversing cyclic graphs (e.g. flight routes), track visited IDs in an array or string to prevent infinite recursion loops.

Ready for Chapter 7 (Window Functions Demystified)? Mark as complete:

Enjoying this free lesson? Your support helps us build more free animated chapters.

Support Us