Multiple CTEs in one query in SQL - Time & Space Complexity
When using multiple CTEs (Common Table Expressions) in one SQL query, it's important to understand how the query's work grows as the data grows.
We want to know how the time to run the query changes when the input data gets bigger.
Analyze the time complexity of the following SQL query using multiple CTEs.
WITH cte1 AS (
SELECT id, value FROM table1 WHERE value > 10
),
cte2 AS (
SELECT id, description FROM table2
),
cte3 AS (
SELECT cte1.id, cte1.value, cte2.description
FROM cte1
JOIN cte2 ON cte1.id = cte2.id
)
SELECT * FROM cte3 WHERE value < 100;
This query defines three CTEs: filtering table1, selecting from table2, then joining them before filtering again.
Look for repeated work inside the query.
- Primary operation: Scanning and filtering rows in table1 and table2, then joining rows from both.
- How many times: Each table is scanned once, but the join compares rows from both tables, which depends on their sizes.
As the number of rows in table1 and table2 grows, the work to scan and join them grows too.
| Input Size (rows in each table) | Approx. Operations |
|---|---|
| 10 | About 10 scans + 10x10 = 100 join checks |
| 100 | About 100 scans + 100x100 = 10,000 join checks |
| 1000 | About 1000 scans + 1000x1000 = 1,000,000 join checks |
Pattern observation: The join work grows much faster than scanning alone, roughly multiplying the sizes of both tables.
Time Complexity: O(n * m)
This means the time grows roughly by multiplying the number of rows in the two tables being joined.
[X] Wrong: "Using multiple CTEs means the query runs multiple times, so time multiplies by the number of CTEs."
[OK] Correct: The database usually runs each CTE once and reuses results, so time depends mostly on the size of data and join operations, not the count of CTEs.
Understanding how multiple CTEs affect query time helps you explain your thought process clearly and shows you know how databases handle complex queries.
"What if we replaced the join with a simple union of the two CTEs? How would the time complexity change?"
Practice
Solution
Step 1: Understand the role of CTEs
CTEs are temporary named result sets used inside a query to organize complex logic.Step 2: Identify the benefit of multiple CTEs
Using multiple CTEs lets you split a big query into smaller, readable parts without permanent storage or indexing.Final Answer:
To break down complex queries into simpler, named parts for better readability -> Option BQuick Check:
Multiple CTEs improve query clarity = D [OK]
- Thinking CTEs create permanent tables
- Assuming CTEs improve query speed automatically
- Confusing CTEs with indexes
cte1 and cte2 in one SQL query?Solution
Step 1: Recall correct CTE syntax
Multiple CTEs are separated by commas after WITH, each defined asname AS (query).Step 2: Check each option
WITH cte1 AS (SELECT * FROM table1), cte2 AS (SELECT * FROM table2) SELECT * FROM cte1 JOIN cte2 ON cte1.id = cte2.id; correctly uses commas and AS keyword; others miss commas or use wrong syntax.Final Answer:
WITH cte1 AS (SELECT * FROM table1), cte2 AS (SELECT * FROM table2) SELECT * FROM cte1 JOIN cte2 ON cte1.id = cte2.id; -> Option AQuick Check:
Multiple CTEs separated by commas = B [OK]
- Omitting commas between CTEs
- Using semicolons between CTEs
- Using equals sign instead of AS
WITH cte1 AS (SELECT 1 AS num UNION ALL SELECT 2), cte2 AS (SELECT num FROM cte1 WHERE num = 2) SELECT * FROM cte2;
Solution
Step 1: Analyze cte1 content
cte1 returns two rows with num values 1 and 2.Step 2: Analyze cte2 filtering
cte2 selects only rows from cte1 where num = 2, so only one row with num=2.Final Answer:
2 -> Option CQuick Check:
cte2 filters num=2 = A [OK]
- Assuming cte2 returns all rows from cte1
- Confusing UNION ALL with UNION
- Ignoring the WHERE filter in cte2
WITH cte1 AS (SELECT id, name FROM users) SELECT * FROM cte1; WITH cte2 AS (SELECT id FROM orders) SELECT * FROM cte2;
Solution
Step 1: Review CTE syntax rules
Only one WITH clause is allowed per query; multiple CTEs must be separated by commas inside one WITH.Step 2: Identify the error in the query
The query uses two separate WITH clauses, which is invalid syntax.Final Answer:
Multiple WITH clauses are not allowed in one query -> Option DQuick Check:
Only one WITH clause per query = A [OK]
- Writing multiple WITH clauses in one query
- Forgetting commas between CTEs
- Assuming CTEs create permanent tables
Solution
Step 1: Calculate average order per customer
WITH avg_orders AS (SELECT customer_id, AVG(amount) AS avg_amount FROM orders GROUP BY customer_id), high_avg AS (SELECT customer_id FROM avg_orders WHERE avg_amount > 100) SELECT * FROM high_avg; correctly groups orders by customer_id and calculates AVG(amount).Step 2: Filter customers with avg_amount > 100
WITH avg_orders AS (SELECT customer_id, AVG(amount) AS avg_amount FROM orders GROUP BY customer_id), high_avg AS (SELECT customer_id FROM avg_orders WHERE avg_amount > 100) SELECT * FROM high_avg; uses a second CTE to filter customers with average above 100, then selects from it.Final Answer:
WITH avg_orders AS (SELECT customer_id, AVG(amount) AS avg_amount FROM orders GROUP BY customer_id), high_avg AS (SELECT customer_id FROM avg_orders WHERE avg_amount > 100) SELECT * FROM high_avg; -> Option AQuick Check:
Multiple CTEs for calculation and filtering = C [OK]
- Missing GROUP BY when calculating averages
- Not filtering on aggregated column
- Incorrect CTE definitions without commas
Ready to prove it?
Pass the test and this pattern moves unknown
