Bird
Raised Fist0
SQLquery~20 mins

Multiple CTEs in one query in SQL - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Multiple CTEs Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ query_result
intermediate
2:00remaining
Output of multiple CTEs with aggregation
Given the following SQL query with two CTEs, what is the output result set?
SQL
WITH SalesCTE AS (
  SELECT salesperson_id, SUM(amount) AS total_sales
  FROM sales
  GROUP BY salesperson_id
),
TopSalesCTE AS (
  SELECT salesperson_id
  FROM SalesCTE
  WHERE total_sales > 10000
)
SELECT salesperson_id FROM TopSalesCTE ORDER BY salesperson_id;
A[{ "salesperson_id": 2 }, { "salesperson_id": 3 }, { "salesperson_id": 5 }]
B[{ "salesperson_id": 1 }, { "salesperson_id": 3 }]
C[{ "salesperson_id": 2 }, { "salesperson_id": 5 }]
D[]
Attempts:
2 left
💡 Hint
Look at the total sales per salesperson and filter those with sales above 10000.
📝 Syntax
intermediate
2:00remaining
Identify the syntax error in multiple CTEs
Which option contains a syntax error in defining multiple CTEs?
SQL
WITH FirstCTE AS (SELECT id FROM table1),
SecondCTE AS (SELECT id FROM table2)
SELECT * FROM FirstCTE JOIN SecondCTE ON FirstCTE.id = SecondCTE.id;
AWITH FirstCTE AS (SELECT id FROM table1) SecondCTE AS (SELECT id FROM table2) SELECT * FROM FirstCTE JOIN SecondCTE ON FirstCTE.id = SecondCTE.id;
B;di.ETCdnoceS = di.ETCtsriF NO ETCdnoceS NIOJ ETCtsriF MORF * TCELES )2elbat MORF di TCELES( SA ETCdnoceS ,)1elbat MORF di TCELES( SA ETCtsriF HTIW
CWITH FirstCTE AS (SELECT id FROM table1), SecondCTE AS (SELECT id FROM table2); SELECT * FROM FirstCTE JOIN SecondCTE ON FirstCTE.id = SecondCTE.id;
DWITH FirstCTE AS (SELECT id FROM table1), SecondCTE AS (SELECT id FROM table2) SELECT * FROM FirstCTE JOIN SecondCTE ON FirstCTE.id = SecondCTE.id;
Attempts:
2 left
💡 Hint
Check the commas separating CTEs and the placement of the SELECT statement.
❓ optimization
advanced
2:00remaining
Optimizing multiple CTEs for performance
You have two CTEs: one calculates total sales per product, the other filters products with sales above 5000. Which option optimizes the query to avoid scanning the sales table twice?
SQL
WITH TotalSales AS (
  SELECT product_id, SUM(amount) AS total_amount
  FROM sales
  GROUP BY product_id
),
FilteredProducts AS (
  SELECT product_id
  FROM TotalSales
  WHERE total_amount > 5000
)
SELECT * FROM FilteredProducts;
AUse a subquery inside the WHERE clause instead of CTEs.
BCombine both CTEs into one by filtering inside the aggregation CTE.
CCreate an index on sales.amount to speed up aggregation.
DUse two separate queries instead of CTEs.
Attempts:
2 left
💡 Hint
Think about reducing repeated scans of the same table.
🔧 Debug
advanced
2:00remaining
Debugging incorrect output from multiple CTEs
A query with two CTEs returns no rows, but you expect some results. Which option explains the most likely cause?
SQL
WITH CTE1 AS (
  SELECT id FROM table1 WHERE status = 'active'
),
CTE2 AS (
  SELECT id FROM table2 WHERE id IN (SELECT id FROM CTE1)
)
SELECT * FROM CTE2;
ACTE1 returns no rows because no rows have status 'active', so CTE2 has no matching ids.
BCTE2 is missing a JOIN clause to connect with CTE1.
CThe query is missing a final SELECT statement to output results.
DCTE2 uses an invalid subquery syntax causing it to return no rows.
Attempts:
2 left
💡 Hint
Check the filtering condition in the first CTE.
🧠 Conceptual
expert
2:00remaining
Understanding execution order of multiple CTEs
In a query with multiple CTEs, which statement best describes the execution order?
ACTEs are executed after the main query completes.
BAll CTEs are executed in the order they are defined before the main query runs.
CCTEs are executed simultaneously in parallel before the main query.
DCTEs are executed only when referenced by the main query or other CTEs, not necessarily all.
Attempts:
2 left
💡 Hint
Think about whether unused CTEs run or not.

Practice

(1/5)
1. What is the main purpose of using multiple CTEs (Common Table Expressions) in a single SQL query?
easy
A. To automatically create indexes on the tables used
B. To break down complex queries into simpler, named parts for better readability
C. To permanently store intermediate results in the database
D. To speed up the database engine by running queries in parallel

Solution

  1. Step 1: Understand the role of CTEs

    CTEs are temporary named result sets used inside a query to organize complex logic.
  2. 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.
  3. Final Answer:

    To break down complex queries into simpler, named parts for better readability -> Option B
  4. Quick Check:

    Multiple CTEs improve query clarity = D [OK]
Hint: Multiple CTEs split queries into named parts for clarity [OK]
Common Mistakes:
  • Thinking CTEs create permanent tables
  • Assuming CTEs improve query speed automatically
  • Confusing CTEs with indexes
2. Which of the following is the correct syntax to define two CTEs named cte1 and cte2 in one SQL query?
easy
A. WITH cte1 AS (SELECT * FROM table1), cte2 AS (SELECT * FROM table2) SELECT * FROM cte1 JOIN cte2 ON cte1.id = cte2.id;
B. WITH cte1 AS (SELECT * FROM table1) cte2 AS (SELECT * FROM table2) SELECT * FROM cte1 JOIN cte2 ON cte1.id = cte2.id;
C. WITH cte1 (SELECT * FROM table1); WITH cte2 (SELECT * FROM table2); SELECT * FROM cte1 JOIN cte2 ON cte1.id = cte2.id;
D. WITH cte1 = (SELECT * FROM table1), cte2 = (SELECT * FROM table2) SELECT * FROM cte1 JOIN cte2 ON cte1.id = cte2.id;

Solution

  1. Step 1: Recall correct CTE syntax

    Multiple CTEs are separated by commas after WITH, each defined as name AS (query).
  2. 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.
  3. Final Answer:

    WITH cte1 AS (SELECT * FROM table1), cte2 AS (SELECT * FROM table2) SELECT * FROM cte1 JOIN cte2 ON cte1.id = cte2.id; -> Option A
  4. Quick Check:

    Multiple CTEs separated by commas = B [OK]
Hint: Separate multiple CTEs with commas after WITH [OK]
Common Mistakes:
  • Omitting commas between CTEs
  • Using semicolons between CTEs
  • Using equals sign instead of AS
3. Given the following SQL query with multiple CTEs, what will be the output?
WITH cte1 AS (SELECT 1 AS num UNION ALL SELECT 2), cte2 AS (SELECT num FROM cte1 WHERE num = 2) SELECT * FROM cte2;
medium
A. 1 and 2
B. 1
C. 2
D. No rows returned

Solution

  1. Step 1: Analyze cte1 content

    cte1 returns two rows with num values 1 and 2.
  2. Step 2: Analyze cte2 filtering

    cte2 selects only rows from cte1 where num = 2, so only one row with num=2.
  3. Final Answer:

    2 -> Option C
  4. Quick Check:

    cte2 filters num=2 = A [OK]
Hint: Trace each CTE step-by-step to find final output [OK]
Common Mistakes:
  • Assuming cte2 returns all rows from cte1
  • Confusing UNION ALL with UNION
  • Ignoring the WHERE filter in cte2
4. Identify the error in the following SQL query using multiple CTEs:
WITH cte1 AS (SELECT id, name FROM users) SELECT * FROM cte1; WITH cte2 AS (SELECT id FROM orders) SELECT * FROM cte2;
medium
A. CTEs cannot select from tables
B. CTEs must be named with different names
C. Missing JOIN condition between cte1 and cte2
D. Multiple WITH clauses are not allowed in one query

Solution

  1. Step 1: Review CTE syntax rules

    Only one WITH clause is allowed per query; multiple CTEs must be separated by commas inside one WITH.
  2. Step 2: Identify the error in the query

    The query uses two separate WITH clauses, which is invalid syntax.
  3. Final Answer:

    Multiple WITH clauses are not allowed in one query -> Option D
  4. Quick Check:

    Only one WITH clause per query = A [OK]
Hint: Use one WITH clause with commas for multiple CTEs [OK]
Common Mistakes:
  • Writing multiple WITH clauses in one query
  • Forgetting commas between CTEs
  • Assuming CTEs create permanent tables
5. You want to calculate the average order amount per customer and then find customers whose average order is above 100. Which of the following queries correctly uses multiple CTEs to achieve this?
hard
A. 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;
B. WITH avg_orders AS (SELECT customer_id, AVG(amount) AS avg_amount FROM orders), high_avg AS (SELECT customer_id FROM avg_orders WHERE avg_amount > 100) SELECT * FROM high_avg;
C. WITH avg_orders AS (SELECT customer_id, amount FROM orders GROUP BY customer_id), high_avg AS (SELECT customer_id FROM avg_orders WHERE amount > 100) SELECT * FROM high_avg;
D. WITH avg_orders AS (SELECT customer_id, AVG(amount) AS avg_amount FROM orders GROUP BY customer_id) SELECT * FROM avg_orders WHERE avg_amount > 100;

Solution

  1. 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).
  2. 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.
  3. 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 A
  4. Quick Check:

    Multiple CTEs for calculation and filtering = C [OK]
Hint: Use one CTE to calculate, second to filter results [OK]
Common Mistakes:
  • Missing GROUP BY when calculating averages
  • Not filtering on aggregated column
  • Incorrect CTE definitions without commas
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard