Challenge - 5 Problems
CTE Mastery in PostgreSQL
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ query_result
intermediate2:00remaining
Output of a simple CTE query
What is the output of this PostgreSQL query using a CTE?
PostgreSQL
WITH numbers AS (SELECT 1 AS num UNION ALL SELECT 2 UNION ALL SELECT 3) SELECT num * 2 AS doubled FROM numbers ORDER BY num;
Attempts:
2 left
💡 Hint
Think about what the CTE 'numbers' contains and how the SELECT multiplies each value.
✗ Incorrect
The CTE 'numbers' creates a temporary table with values 1, 2, and 3. The main query multiplies each by 2, so the output is 2, 4, 6.
🧠 Conceptual
intermediate1:30remaining
Why use CTEs for readability?
Why do developers use Common Table Expressions (CTEs) in PostgreSQL queries?
Attempts:
2 left
💡 Hint
Think about how breaking a big problem into smaller parts helps understanding.
✗ Incorrect
CTEs help break complex queries into smaller, named parts, making them easier to read and maintain.
❓ optimization
advanced2:30remaining
Effect of CTEs on query optimization
In PostgreSQL, how do CTEs affect query optimization compared to subqueries?
Attempts:
2 left
💡 Hint
Consider how PostgreSQL treats CTEs as separate steps in query execution.
✗ Incorrect
In PostgreSQL, CTEs are optimization fences, meaning they are executed independently before the main query, which can affect performance.
🔧 Debug
advanced2:00remaining
Identify the error in this CTE query
What error will this PostgreSQL query raise?
PostgreSQL
WITH cte AS (SELECT id, name FROM users) SELECT id, age FROM cte;
Attempts:
2 left
💡 Hint
Check which columns are selected inside the CTE and which are requested outside.
✗ Incorrect
The CTE selects only 'id' and 'name'. The outer query requests 'id' and 'age', but 'age' is not in the CTE, causing an error.
🧠 Conceptual
expert3:00remaining
When to avoid CTEs for performance
In which situation might using a CTE in PostgreSQL cause slower query performance?
Attempts:
2 left
💡 Hint
Think about how PostgreSQL executes CTEs and the cost of repeated execution.
✗ Incorrect
Because CTEs act as optimization fences, large CTEs used multiple times can be executed repeatedly, slowing down the query.