Challenge - 5 Problems
CTE Mastery Badge
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ query_result
intermediate2:00remaining
Output of multiple CTEs with aggregation
Consider the following SQL query using two CTEs. What will be the output rows?
PostgreSQL
WITH sales AS ( SELECT 'Alice' AS salesperson, 100 AS amount UNION ALL SELECT 'Bob', 150 UNION ALL SELECT 'Alice', 200 ), summary AS ( SELECT salesperson, SUM(amount) AS total_sales FROM sales GROUP BY salesperson ) SELECT salesperson, total_sales FROM summary ORDER BY salesperson;
Attempts:
2 left
💡 Hint
Sum the amounts for each salesperson from the sales CTE.
✗ Incorrect
The sales CTE lists amounts per salesperson. The summary CTE sums these amounts grouped by salesperson. Alice has 100 + 200 = 300, Bob has 150.
📝 Syntax
intermediate2:00remaining
Identify the syntax error in multiple CTEs
Which option contains a syntax error in defining multiple CTEs?
PostgreSQL
WITH cte1 AS (SELECT 1 AS num), cte2 AS (SELECT 2 AS num) SELECT * FROM cte1 UNION ALL SELECT * FROM cte2;
Attempts:
2 left
💡 Hint
Check the commas and placement between CTE definitions.
✗ Incorrect
Option D misses the comma between cte1 and cte2 definitions, causing a syntax error.
❓ optimization
advanced2:00remaining
Optimizing multiple CTEs for performance
Given two CTEs where the second depends on the first, which option optimizes the query to avoid repeated scans?
PostgreSQL
WITH cte1 AS ( SELECT * FROM orders WHERE order_date >= '2024-01-01' ), cte2 AS ( SELECT customer_id, COUNT(*) AS order_count FROM cte1 GROUP BY customer_id ) SELECT * FROM cte2 WHERE order_count > 5;
Attempts:
2 left
💡 Hint
Indexes help speed up filtering on large tables.
✗ Incorrect
Adding an index on order_date helps the initial filter in cte1 run faster, improving overall query speed without changing logic.
🔧 Debug
advanced2:00remaining
Debugging unexpected output from multiple CTEs
This query returns no rows, but you expect some. What is the cause?
PostgreSQL
WITH cte1 AS ( SELECT * FROM products WHERE price > 100 ), cte2 AS ( SELECT * FROM cte1 WHERE price < 50 ) SELECT * FROM cte2;
Attempts:
2 left
💡 Hint
Check the filter conditions in both CTEs carefully.
✗ Incorrect
cte1 selects products with price > 100, but cte2 filters for price < 50 on cte1 results, which is impossible, so no rows return.
🧠 Conceptual
expert2:00remaining
Understanding execution order of multiple CTEs
In a query with multiple CTEs where cte3 depends on cte2 and cte2 depends on cte1, which statement is true about execution order?
Attempts:
2 left
💡 Hint
Think about how PostgreSQL handles CTEs and dependencies.
✗ Incorrect
PostgreSQL executes CTEs lazily when referenced. cte3 depends on cte2, so cte3 triggers cte2, which triggers cte1 execution.