Sub topic 1
SQL Common Table Expressions: Writing Readable Queries with WITH
Prerequisites
This chapter assumes you can write basic SELECT, WHERE, and ORDER BY clauses. You should also know how to JOIN two tables and how to use GROUP BY with aggregate functions such as SUM and COUNT. Familiarity with subqueries helps but is not required.
Starting point: nested subqueries and why they get hard to read
A subquery is a SELECT placed inside another query. A derived table is a subquery placed in the FROM clause. Nesting works, but each layer adds indentation and forces you to read the query from the inside out.
Suppose you want the names of customers whose orders total more than 1000:
SELECT c.name, t.total
FROM customers c
JOIN (
SELECT customer_id, SUM(amount) AS total
FROM orders
GROUP BY customer_id
) t ON t.customer_id = c.id
WHERE t.total > 1000;You must find the innermost SELECT first, then work outward. Each extra layer makes this harder.
Your first CTE: naming a result with WITH
A common table expression (CTE) is a named result set defined with a WITH clause. A result set is the set of rows a query returns. The name lets you refer to that result later in the same statement, as if it were a table.
The same query, refactored with a CTE:
WITH order_totals AS (
SELECT customer_id, SUM(amount) AS total
FROM orders
GROUP BY customer_id
)
SELECT c.name, t.total
FROM customers c
JOIN order_totals t ON t.customer_id = c.id
WHERE t.total > 1000;Chaining several CTEs into a pipeline
Separate CTEs with commas. A later CTE can read from any CTE defined before it. Each step names its output, and the next step uses that name.
WITH order_totals AS (
SELECT customer_id, SUM(amount) AS total
FROM orders
GROUP BY customer_id
),
big_spenders AS (
SELECT customer_id, total
FROM order_totals
WHERE total > 1000
)
SELECT c.name, b.total
FROM big_spenders b
JOIN customers c ON c.id = b.customer_id
ORDER BY b.total DESC;Exercise
Why must bigspenders appear after ordertotals in the WITH clause?
Show answer
bigspenders reads from ordertotals by name. A CTE can only refer to names defined earlier in the same WITH clause, so order_totals must come first.