Subqueries & CTEs
Organize modular, readable queries with Common Table Expressions (WITH) and correlated subqueries.
Core Learning Objectives
- •Write readable multi-step CTE chains for complex data pipelines
- •Use correlated subqueries with EXISTS and NOT EXISTS for optimal filtering
- •Implement recursive CTEs for hierarchical tree structures
Interactive Cheatsheet
PostgreSQL SyntaxWITH regional_sales AS ( SELECT region, SUM(amount) AS total_sales FROM sales GROUP BY region ) SELECT region, total_sales FROM regional_sales WHERE total_sales > (SELECT AVG(total_sales) FROM regional_sales);
Curated Practice Problems (2)
Users With Above-Average Connection Count
Meta's Network Graph team wants to identify hub accounts that possess strictly more friends than the overall network average. Write a SQL query to return the `user_id` and their `friend_count`, for all users whose friend count is strictly greater than the platform-wide average friend count per user. Sort by `friend_count` descending. Tables: - `friendships` (`user_id` INT, `friend_id` INT)
Customer Peak Spending Day (Chained CTE)
Amazon Prime analytics wants to identify each customer's single highest spending calendar day. Write a SQL query using Common Table Expressions (WITH) to find each customer's peak spend day. Return `customer_id`, `order_date`, and `daily_spend`. If a customer tied their peak spend across multiple days, output the most recent date. Sort by `daily_spend` descending, then `customer_id` ascending. Tables: - `orders` (`order_id` INT, `customer_id` INT, `order_date` DATE, `amount` DECIMAL)