Comparing CTE and Subquery Performance in PostgreSQL
📖 Scenario: You are working with a sales database that tracks orders and customers. You want to analyze how using Common Table Expressions (CTEs) versus subqueries affects query performance when calculating total sales per customer.
🎯 Goal: Build two SQL queries: one using a CTE and one using a subquery to calculate total sales per customer. Observe and compare their performance.
📋 What You'll Learn
Create a table called orders with columns order_id (integer), customer_id (integer), and amount (numeric).
Insert sample data into orders with at least 5 rows.
Create a CTE query named cte_total_sales that calculates total sales per customer.
Create a subquery that calculates total sales per customer without using a CTE.
💡 Why This Matters
🌍 Real World
Sales analysts often need to summarize data per customer to understand buying patterns and revenue contributions.
💼 Career
Database developers and analysts must write efficient queries and understand how different SQL constructs affect performance.
Progress0 / 4 steps
1
Create the orders table and insert data
Write SQL statements to create a table called orders with columns order_id (integer), customer_id (integer), and amount (numeric). Then insert these exact rows into orders: (1, 101, 50.00), (2, 102, 75.50), (3, 101, 20.00), (4, 103, 100.00), (5, 102, 40.00).
PostgreSQL
Hint
Use CREATE TABLE to define the table and INSERT INTO to add rows.
2
Write a CTE query to calculate total sales per customer
Write a SQL query using a Common Table Expression (CTE) named cte_total_sales that sums the amount for each customer_id from the orders table. Select customer_id and the total amount as total_sales from the CTE.
PostgreSQL
Hint
Use WITH cte_total_sales AS (SELECT ...) to define the CTE, then select from it.
3
Write a subquery to calculate total sales per customer
Write a SQL query that selects customer_id and total sales as total_sales by using a subquery inside the FROM clause. The subquery should sum amount grouped by customer_id from the orders table.
PostgreSQL
Hint
Use a subquery inside FROM with an alias, then select from it.
4
Add an ORDER BY clause to both queries to sort results
Add an ORDER BY customer_id clause to the end of both the CTE query and the subquery to sort the results by customer_id in ascending order.
PostgreSQL
Hint
Use ORDER BY customer_id after the SELECT statements to sort results.
Practice
(1/5)
1. What is a common performance difference between CTEs and subqueries in PostgreSQL before version 12?
easy
A. CTEs and subqueries have identical performance.
B. Subqueries always run slower than CTEs.
C. CTEs act as optimization fences, potentially slowing queries.
D. Subqueries cannot be used inside SELECT statements.
Solution
Step 1: Understand CTE behavior in PostgreSQL before v12
CTEs are treated as optimization fences, meaning the planner executes them separately and does not optimize across them.
Step 2: Compare with subqueries
Subqueries can be inlined and optimized with the rest of the query, often leading to better performance.
Final Answer:
CTEs act as optimization fences, potentially slowing queries. -> Option C
Quick Check:
CTEs before v12 block optimization = A [OK]
Hint: Remember: CTEs block optimization before PostgreSQL 12 [OK]
Common Mistakes:
Thinking subqueries are always slower
Assuming CTEs and subqueries perform the same
Believing subqueries can't be inside SELECT
2. Which of the following is the correct syntax to define a CTE in PostgreSQL?
easy
A. WITH cte_name AS (SELECT * FROM table_name) SELECT * FROM cte_name;
B. SELECT * FROM table_name WITH cte_name AS ();
C. CREATE CTE cte_name SELECT * FROM table_name;
D. WITH (SELECT * FROM table_name) AS cte_name SELECT * FROM cte_name;
Solution
Step 1: Recall CTE syntax
CTEs start with WITH, followed by the CTE name, AS, and a query in parentheses.
Step 2: Validate each option
WITH cte_name AS (SELECT * FROM table_name) SELECT * FROM cte_name; matches the correct syntax. Options A, B, and C have incorrect order or keywords.
Final Answer:
WITH cte_name AS (SELECT * FROM table_name) SELECT * FROM cte_name; -> Option A
Quick Check:
CTE syntax starts with WITH name AS (query) [OK]
Hint: CTE syntax always starts with WITH name AS (query) [OK]
Common Mistakes:
Placing WITH after SELECT
Using CREATE keyword for CTE
Misplacing parentheses
3. Given the following queries, which one is likely to run faster in PostgreSQL 11?
-- Query 1 (CTE): WITH recent_orders AS (SELECT * FROM orders WHERE order_date > '2024-01-01') SELECT customer_id, COUNT(*) FROM recent_orders GROUP BY customer_id;
-- Query 2 (Subquery): SELECT customer_id, COUNT(*) FROM (SELECT * FROM orders WHERE order_date > '2024-01-01') AS recent_orders GROUP BY customer_id;
medium
A. Query 1 runs faster because CTEs are always optimized.
B. Query 2 runs faster because subqueries allow better optimization in PostgreSQL 11.
C. Both queries run at the same speed.
D. Query 1 will cause a syntax error.
Solution
Step 1: Understand PostgreSQL 11 optimization
In PostgreSQL 11, CTEs act as optimization fences, so Query 1 executes the CTE separately.
Step 2: Compare with subquery behavior
Subqueries can be inlined and optimized with the main query, so Query 2 can be faster.
Final Answer:
Query 2 runs faster because subqueries allow better optimization in PostgreSQL 11. -> Option B
Quick Check:
PostgreSQL 11: subqueries optimize better than CTEs [OK]
Hint: Before v12, subqueries usually run faster than CTEs [OK]
Common Mistakes:
Assuming CTEs always optimize well
Thinking both queries have same speed
Believing Query 1 has syntax error
4. Identify the error in this query using a CTE in PostgreSQL:
WITH recent_orders AS SELECT * FROM orders WHERE order_date > '2024-01-01' SELECT * FROM recent_orders;
medium
A. Missing parentheses around the CTE query.
B. CTE name is invalid.
C. Missing semicolon after CTE.
D. CTEs cannot filter by date.
Solution
Step 1: Check CTE syntax
CTE query must be enclosed in parentheses after AS keyword.
Step 2: Identify the missing parentheses
The query lacks parentheses around SELECT * FROM orders WHERE ...
Final Answer:
Missing parentheses around the CTE query. -> Option A
Quick Check:
CTE query must be in parentheses [OK]
Hint: Always put CTE query inside parentheses after AS [OK]
Common Mistakes:
Omitting parentheses around CTE query
Thinking semicolon is required after CTE
Believing CTE names can't be simple
5. You want to optimize a complex query in PostgreSQL 13 that uses multiple CTEs and subqueries. Which approach is best to improve performance?
hard
A. Avoid both CTEs and subqueries; use temporary tables instead.
B. Replace all CTEs with subqueries to allow better optimization.
C. Use only CTEs because subqueries are deprecated in PostgreSQL 13.
D. Keep CTEs because PostgreSQL 13 can inline them, improving speed.
Solution
Step 1: Understand PostgreSQL 13 CTE behavior
Starting with PostgreSQL 12, CTEs can be inlined and optimized like subqueries.
Step 2: Evaluate optimization strategies
Replacing CTEs with subqueries is not necessary; keeping CTEs maintains readability and performance.
Final Answer:
Keep CTEs because PostgreSQL 13 can inline them, improving speed. -> Option D
Quick Check:
PostgreSQL 12+ inlines CTEs for better optimization [OK]
Hint: PostgreSQL 12+ optimizes CTEs like subqueries [OK]
Common Mistakes:
Thinking subqueries are deprecated
Replacing CTEs blindly without testing
Assuming temporary tables always improve speed
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.