01 / 21

Multiple CTEs
Breaking Down Complex Logic

Learn how to chain Common Table Expressions to decompose intricate SQL queries into readable, reusable steps.

SQL

What Is a CTE?

A Common Table Expression (CTE) is a temporary named result set defined within a WITH clause. It exists only for the duration of a single SQL statement and makes your queries easier to read, debug, and maintain.

WITH cte_name AS ( SELECT column_a, column_b FROM some_table WHERE condition = 'value' ) SELECT * FROM cte_name;

Why Use Multiple CTEs?

Real-world queries often require several transformations: filtering, aggregating, joining, then filtering again. Nesting all of that into a single query creates hard-to-read "walls of SQL." Multiple CTEs let you build each step independently.

Readability
Each CTE has a meaningful name, so reviewers can follow the logic step by step.
Debuggability
You can test each CTE in isolation by running just that portion of the query.
Reuse
Later CTEs can reference earlier ones, avoiding duplicated logic.

CTEs as a Data Pipeline

raw_data CTE 1: Filter aggregated CTE 2: Group ranked CTE 3: Rank SELECT Final query

The Syntax for Multiple CTEs

WITH first_cte AS ( SELECT ... ), -- comma separates CTEs second_cte AS ( SELECT ... FROM first_cte -- can reference earlier CTE ), third_cte AS ( SELECT ... FROM second_cte ) SELECT * FROM third_cte;

CTE Scope and Reference Rules

1
Forward only: A CTE can reference any CTE defined before it, but not one defined after it.
2
Same statement only: CTEs are scoped to the single SQL statement they belong to: they vanish once that statement finishes.
3
Multi-reference allowed: The final SELECT (or any later CTE) can reference any earlier CTE multiple times.
4
Naming matters: CTE names must be unique within the same WITH block, just like table aliases.

CTEs vs Subqueries vs Temp Tables

CTEs Subqueries Temp Tables
Reusable in query ✓ Yes ✕ No ✓ Yes
Scope Single statement Single use point Session / connection
Readability High Low (nested) Medium
Performance Optimizer dependent Optimizer dependent Materialized on disk
Requires CREATE ✕ No ✕ No ✓ Yes

How to Apply Multiple CTEs

1
Identify the final question: What does the query need to answer? Work backwards from the desired output columns.
2
List the data steps: Write down each transformation in plain English: filter, aggregate, join, rank, etc.
3
Give each step a name: Use descriptive CTE names like active_users, monthly_totals, ranked_products.
4
Chain them in order: Write the WITH clause with each CTE referencing only earlier CTEs.
5
Write the final SELECT: Pull from the last CTE (or join multiple CTEs) to produce the answer.

Example 1: Top Customers

Goal: Find the top 3 customers by total spending who placed orders in the last 30 days. We need two steps: filter recent orders, then aggregate and rank.

WITH recent_orders AS ( SELECT customer_id, amount FROM orders WHERE order_date >= CURRENT_DATE - 30 ), customer_totals AS ( SELECT customer_id, SUM(amount) AS total_spent FROM recent_orders GROUP BY customer_id ) SELECT customer_id, total_spent FROM customer_totals ORDER BY total_spent DESC LIMIT 3;

Example 1: Step-by-Step Breakdown

recent_orders
Filters the orders table to only the last 30 days. Output: customer_id, amount.
customer_totals
Reads from recent_orders, groups by customer, sums spending. Output: customer_id, total_spent.

Example 2: Employee Bonuses

Goal: Find each department's average salary, then identify employees earning above their department average, and finally count how many such employees each department has.

WITH dept_avg AS ( SELECT dept_id, AVG(salary) AS avg_salary FROM employees GROUP BY dept_id ), above_avg AS ( SELECT e.emp_id, e.dept_id FROM employees e JOIN dept_avg d ON e.dept_id = d.dept_id WHERE e.salary > d.avg_salary ), dept_counts AS ( SELECT dept_id, COUNT(*) AS above_avg_count FROM above_avg GROUP BY dept_id ) SELECT * FROM dept_counts;

Example 2: Data Flow

employees dept_avg above_avg dept_counts SELECT * JOIN

Example 3: Ranking with Window Functions

Goal: For each product category, find the single best-selling product in the last quarter.

WITH quarterly_sales AS ( SELECT product_id, category, SUM(qty) AS total_qty FROM sales WHERE sale_date >= '2024-01-01' GROUP BY product_id, category ), ranked AS ( SELECT *, ROW_NUMBER() OVER ( PARTITION BY category ORDER BY total_qty DESC ) AS rn FROM quarterly_sales ) SELECT product_id, category, total_qty FROM ranked WHERE rn = 1;

Independent vs Chained CTEs

CTEs don't always have to form a chain. Sometimes you define independent CTEs from different tables and join them in the final SELECT.

WITH sales_summary AS ( SELECT region, SUM(revenue) AS total_rev FROM sales GROUP BY region ), headcount AS ( SELECT region, COUNT(*) AS emp_count FROM employees GROUP BY region ) SELECT s.region, s.total_rev, h.emp_count, s.total_rev / h.emp_count AS rev_per_emp FROM sales_summary s JOIN headcount h ON s.region = h.region;

Common Mistakes

✕ Repeating WITH
Writing WITH before every CTE instead of once at the top. Each additional CTE is separated by a comma only.
✕ Forward Reference
Referencing a CTE that is defined later in the WITH block. CTEs can only see CTEs declared above them.
✕ Missing Comma
Forgetting the comma between CTEs. The closing parenthesis of one CTE must be followed by a comma before the next CTE name.

Quick Reference Cheat Sheet

Rule Details
Keyword WITH appears once, CTEs separated by commas
Reference direction Forward only: later CTEs can see earlier ones
Scope One SQL statement only
Naming Unique, descriptive names (snake_case)
Independence CTEs can be chained or independent
Final query SELECT, INSERT, UPDATE, or DELETE after CTEs

Question 1 of 5

When writing multiple CTEs in a single statement, how do you separate them?

Question 2 of 5

Given the CTEs below, which reference is valid?

Question 3 of 5

What is a key advantage of using multiple CTEs over deeply nested subqueries?

Question 4 of 5

You have two independent CTEs: sales_data (from the sales table) and returns_data (from the returns table). How do you combine them?

Question 5 of 5

What happens if you accidentally give a CTE the same name as an existing table in your database?