sql / intermediate
Snippet
Structuring Multi-Step Logic Using Common Table Expressions
Common Table Expressions (CTEs) define temporary named result sets using the WITH clause. CTEs simplify complex database logic by breaking queries into modular, readable steps.
snippet.sql
sql
1
2
3
4
5
6
7
8
9
10
11
12
13
WITH regional_sales AS (SELECT region, SUM(amount) AS total_salesFROM ordersGROUP BY region),top_regions AS (SELECT regionFROM regional_salesWHERE total_sales > 100000)SELECT o.order_id, o.region, o.amountFROM orders oJOIN top_regions tr ON o.region = tr.region;
Breakdown
1
WITH regional_sales AS (
Declares the first Common Table Expression to aggregate sales per region.
2
SELECT region, SUM(amount) AS total_sales
Calculates total sales amount grouped by region.
3
top_regions AS (
Declares a second CTE that filters regions based on the first CTE results.
4
WHERE total_sales > 100000
Applies a threshold condition to retain high-volume regions.
5
JOIN top_regions tr ON o.region = tr.region;
Joins the primary table with the CTE result set to filter qualifying orders.