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