Multiple CTEs
Breaking Down Complex Logic
Learn how to chain Common Table Expressions to decompose intricate SQL queries into readable, reusable steps.
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.
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.
CTEs as a Data Pipeline
The Syntax for Multiple CTEs
CTE Scope and Reference Rules
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
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.
Example 1: Step-by-Step Breakdown
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.
Example 2: Data Flow
Example 3: Ranking with Window Functions
Goal: For each product category, find the single best-selling product in the last quarter.
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.
Common Mistakes
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?
WITH
alpha AS (SELECT ... FROM orders),
beta AS (SELECT ... FROM ???),
gamma AS (SELECT ... FROM ???)
SELECT * FROM gamma;
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?