Challenge - 5 Problems
WITH Clause Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ query_result
intermediate2:00remaining
Output of a simple WITH clause query
What is the output of this query using a WITH clause to calculate doubled values?
PostgreSQL
WITH doubled AS (SELECT 1 AS num, 2 AS val UNION ALL SELECT 2, 4 UNION ALL SELECT 3, 6) SELECT num, val FROM doubled WHERE val > 3 ORDER BY num;
Attempts:
2 left
💡 Hint
Look at the WHERE clause filtering values greater than 3.
✗ Incorrect
The WITH clause defines a temporary table 'doubled'. The SELECT filters rows where val > 3, so only rows with val 4 and 6 remain.
📝 Syntax
intermediate2:00remaining
Identify the syntax error in WITH clause usage
Which option contains a syntax error in the WITH clause usage?
PostgreSQL
WITH temp AS SELECT id, name FROM users SELECT * FROM temp;
Attempts:
2 left
💡 Hint
Check if the WITH clause has parentheses around the subquery.
✗ Incorrect
The WITH clause requires the subquery to be enclosed in parentheses. Option A misses parentheses and has an extra semicolon breaking the query.
❓ optimization
advanced3:00remaining
Optimizing multiple WITH clauses
Given two WITH clauses that calculate sums separately, which option combines them efficiently into one WITH clause?
PostgreSQL
WITH sum_a AS (SELECT SUM(amount) AS total_a FROM sales WHERE category = 'A'), sum_b AS (SELECT SUM(amount) AS total_b FROM sales WHERE category = 'B') SELECT total_a, total_b FROM sum_a CROSS JOIN sum_b;
Attempts:
2 left
💡 Hint
Try to calculate both sums in a single scan of the sales table.
✗ Incorrect
Option C uses conditional aggregation to compute both sums in one pass, which is more efficient than separate queries or joins.
🔧 Debug
advanced2:00remaining
Debugging recursive WITH clause
What error will this recursive WITH clause produce?
PostgreSQL
WITH RECURSIVE nums(n) AS (SELECT 1 UNION ALL SELECT n + 1 FROM nums WHERE n < 3) SELECT * FROM nums;
Attempts:
2 left
💡 Hint
Check the base case and recursion condition carefully.
✗ Incorrect
The recursive CTE starts at 1 and adds 1 until n reaches 3, producing rows 1, 2, and 3 without error.
🧠 Conceptual
expert1:30remaining
Understanding scope of WITH clause aliases
Which statement about the scope of table aliases defined in a WITH clause is true?
Attempts:
2 left
💡 Hint
Think about temporary nature of WITH clause results.
✗ Incorrect
WITH clause aliases are temporary and exist only for the duration of the query they are part of.