Challenge - 5 Problems
Multiple CTEs Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ query_result
intermediate2: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;
Attempts:
2 left
💡 Hint
Look at the total sales per salesperson and filter those with sales above 10000.
✗ Incorrect
The first CTE calculates total sales per salesperson. The second CTE filters those with total sales greater than 10000. Only salesperson_id 2 and 5 meet this condition.
📝 Syntax
intermediate2: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;
Attempts:
2 left
💡 Hint
Check the commas separating CTEs and the placement of the SELECT statement.
✗ Incorrect
Option A is missing a comma between the two CTE definitions, causing a syntax error.
❓ optimization
advanced2: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;
Attempts:
2 left
💡 Hint
Think about reducing repeated scans of the same table.
✗ Incorrect
Combining filtering inside the aggregation CTE reduces scanning the sales table twice, improving performance.
🔧 Debug
advanced2: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;
Attempts:
2 left
💡 Hint
Check the filtering condition in the first CTE.
✗ Incorrect
If CTE1 returns no rows, then the subquery in CTE2 finds no ids, resulting in no output.
🧠 Conceptual
expert2:00remaining
Understanding execution order of multiple CTEs
In a query with multiple CTEs, which statement best describes the execution order?
Attempts:
2 left
💡 Hint
Think about whether unused CTEs run or not.
✗ Incorrect
CTEs behave like inline views and are executed only when referenced, not all upfront.