01 / 21

Common Table
Expressions (CTEs)

Master the WITH clause to break complex queries into readable, reusable building blocks that make your SQL clear and maintainable.

SQL Database Programming

What Is a CTE?

A Common Table Expression (CTE) is a temporary, named result set that you define at the beginning of a query using the WITH keyword. It exists only for the duration of that single statement: once the query finishes, the CTE disappears.

Why CTEs Matter

Readability
Break a giant query into named, logical steps that read top-to-bottom like a recipe.
Reusability
Reference the same CTE multiple times in one query instead of copy-pasting subqueries.
Debugging
Test each CTE independently by running just its SELECT to verify intermediate results.

Anatomy of WITH

WITH cte_name AS ( SELECT column1, column2 FROM some_table WHERE condition CTE body ) Main Query SELECT * FROM cte_name References the CTE by its name

The Basic Syntax

SQL
WITH high_scorers AS (
    SELECT student_name, score
    FROM exam_results
    WHERE score >= 90
)
SELECT *
FROM high_scorers
ORDER BY score DESC;

CTE vs Subquery

CTE (WITH) Subquery
Location Defined before the main query Nested inside the main query
Readability High: named, top-down Lower: deeply nested
Reuse Can be referenced multiple times Must be duplicated each time
Recursion Supported Not supported
Performance Usually the same as subquery Usually the same as CTE

CTE vs Temp Table vs View

CTE
Lives only during one statement. Disappears when the query finishes. Cannot be indexed.
Temp Table
Lives for the entire session. Can be indexed, updated, and referenced across multiple statements.
View
A permanent saved query in the database. Reusable across sessions and users.

How to Write a CTE

1
Identify the subquery. Find a nested SELECT in your query that could benefit from being named.
2
Write WITH cte_name AS (...). Move the subquery to the top and wrap it in parentheses after AS.
3
Choose a descriptive name. Name it after what it contains: active_users, not temp1.
4
Reference the CTE below. Use the CTE name in your main SELECT, JOIN, or WHERE clause.
5
Test independently. Run just the CTE's SELECT to verify it returns the expected rows.

How the Database Processes a CTE

1. Parse WITH Read CTE definition 2. Execute CTE Build temp result set 3. Run Main Use CTE as table EXECUTION FLOW Source Table CTE Result Final Output WHERE filters JOIN / GROUP BY

Example 1: Simple CTE

Find all products with above-average prices.

SQL
WITH avg_price AS (
    SELECT AVG(price) AS mean_price
    FROM products
)
SELECT product_name, price
FROM products, avg_price
WHERE price > avg_price.mean_price;

Example 2: Multiple CTEs

Compare each department's total sales to the company average.

SQL
WITH dept_totals AS (
    SELECT department, SUM(amount) AS total
    FROM sales
    GROUP BY department
),
company_avg AS (
    SELECT AVG(total) AS avg_total
    FROM dept_totals
)
SELECT d.department, d.total, c.avg_total
FROM dept_totals d, company_avg c
WHERE d.total > c.avg_total;

Example 3: CTE with JOIN

Find customers who placed more orders than the average customer.

SQL
WITH order_counts AS (
    SELECT customer_id,
           COUNT(*) AS num_orders
    FROM orders
    GROUP BY customer_id
)
SELECT c.name, oc.num_orders
FROM customers c
JOIN order_counts oc
  ON c.id = oc.customer_id
WHERE oc.num_orders > (
    SELECT AVG(num_orders)
    FROM order_counts
);

Recursive CTEs

A recursive CTE references itself to traverse hierarchical data: org charts, file trees, or category hierarchies. It has two parts joined by UNION ALL.

Anchor Member
The initial SELECT that returns the starting rows (the base case).
Recursive Member
A SELECT that joins the CTE to itself, adding new rows each iteration until none are found.
SQL
WITH RECURSIVE hierarchy AS (
    -- Anchor: start at top-level
    SELECT id, name, manager_id, 1 AS depth
    FROM employees
    WHERE manager_id IS NULL

    UNION ALL

    -- Recursive: find direct reports
    SELECT e.id, e.name, e.manager_id, h.depth + 1
    FROM employees e
    JOIN hierarchy h ON e.manager_id = h.id
)
SELECT * FROM hierarchy;

How Recursion Unfolds

CEO (depth 1) VP Sales (depth 2) VP Eng (depth 2) Rep A (3) Rep B (3) Dev A (3) Dev B (3) Each iteration discovers the next level until no more rows match the JOIN condition Iteration 1 Iteration 2 Iteration 3

Common Mistakes

✕ Extra WITH keyword
Writing WITH...WITH for multiple CTEs. Use a single WITH and separate CTEs with commas.
✕ Missing comma
Forgetting the comma between CTEs. Each CTE except the last must end with a comma before the next name.
✕ No base case
Recursive CTE without an anchor member causes an infinite loop. Always provide a WHERE that seeds the first rows.
✕ Using outside scope
Trying to SELECT from a CTE in a later statement. CTEs only exist for the single statement they are attached to.

Summary Reference

Feature Syntax / Rule
Single CTE WITH name AS ( SELECT ... )
Multiple CTEs WITH a AS (...), b AS (...) SELECT ...
Recursive CTE WITH RECURSIVE name AS (anchor UNION ALL recursive)
Scope Exists only for the one statement it precedes
Reuse Can be referenced multiple times in the main query
Column aliases Optional: WITH name(col1, col2) AS (...)
Nesting order Later CTEs can reference earlier ones, but not the reverse

Question 1 of 5

Which keyword introduces a Common Table Expression?

Question 2 of 5

How do you define multiple CTEs in a single query?

Question 3 of 5

What is the scope of a CTE?

Question 4 of 5

In a recursive CTE, what happens if you omit the anchor member?

Question 5 of 5

Given the query below, what does the CTE recent_orders contain?

SQL
WITH recent_orders AS (
    SELECT * FROM orders
    WHERE order_date >= '2024-01-01'
)
SELECT COUNT(*) FROM recent_orders;