Recall & Review
beginner
What is a Common Table Expression (CTE) in SQL?
A CTE is a temporary named result set that you can reference within a SELECT, INSERT, UPDATE, or DELETE statement. It helps organize complex queries by breaking them into simpler parts.
Click to reveal answer
beginner
How does a subquery differ from a CTE?
A subquery is a query nested inside another query, often used inline. A CTE is defined before the main query and can be referenced multiple times, improving readability and sometimes performance.
Click to reveal answer
intermediate
Does PostgreSQL always optimize CTEs and subqueries the same way?
No. Before PostgreSQL 12, CTEs acted as optimization fences, meaning they were executed separately and results materialized. Subqueries could be inlined and optimized better. From PostgreSQL 12, CTEs can be inlined like subqueries unless marked with MATERIALIZED or NOT MATERIALIZED.
Click to reveal answer
intermediate
When might a CTE perform worse than a subquery?
If the CTE is materialized (executed and stored) and used only once, it can cause extra work and slower performance compared to a subquery that the planner can inline and optimize.
Click to reveal answer
beginner
What is one advantage of using CTEs despite potential performance costs?
CTEs improve query readability and maintainability by breaking complex queries into named parts. They also allow recursive queries, which subqueries cannot do.
Click to reveal answer
Before PostgreSQL 12, how were CTEs treated in terms of query optimization?
✗ Incorrect
Before PostgreSQL 12, CTEs were executed separately and their results stored, preventing some optimizations.
Which keyword forces a CTE to be materialized in PostgreSQL 12 and later?
✗ Incorrect
The MATERIALIZED keyword forces the CTE to be executed and stored separately.
Which of the following is a benefit of using subqueries over CTEs?
✗ Incorrect
Subqueries can be inlined and optimized better, which can improve performance.
What is a common reason to choose a CTE despite possible performance costs?
✗ Incorrect
CTEs improve query readability and maintainability.
In PostgreSQL 12+, what happens if you do not specify MATERIALIZED or NOT MATERIALIZED for a CTE?
✗ Incorrect
PostgreSQL's planner chooses the best approach automatically.
Explain the performance differences between CTEs and subqueries in PostgreSQL, especially before and after version 12.
Think about how the query planner treats CTEs and subqueries differently across versions.
You got /6 concepts.
Describe when it might be better to use a subquery instead of a CTE for performance reasons.
Consider how materialization affects execution time.
You got /4 concepts.