SQL
Simplifying Complex SQL Queries with Common Table Expressions (CTEs)
Learn to use SQL Common Table Expressions (CTEs) to break down complex queries into logical, readable, and reusable blocks, improving maintainability.
WITH MonthlySales AS (
SELECT
TO_CHAR(order_date, 'YYYY-MM') AS sale_month,
SUM(total_amount) AS total_monthly_sales
FROM orders
GROUP BY sale_month
),
TopMonths AS (
SELECT
sale_month,
total_monthly_sales,
RANK() OVER (ORDER BY total_monthly_sales DESC) as rnk
FROM MonthlySales
)
SELECT sale_month, total_monthly_sales
FROM TopMonths
WHERE rnk <= 3
ORDER BY rnk;
How it works: This snippet uses Common Table Expressions (CTEs) to simplify a multi-step query. `MonthlySales` first calculates total sales for each month. `TopMonths` then uses the `MonthlySales` CTE to rank these months by their total sales using the `RANK()` window function. Finally, the main `SELECT` statement retrieves the top 3 months based on this ranking, demonstrating how CTEs enhance readability and modularity for complex SQL logic.