WITH Patterns: Step-by-Step Assembly, Reuse, Parameters

The WITH Clause and Recursive Queries showed how to name CTEs and chain them. This page covers a few shapes for using them in real queries.

Assembling step by step

For a query with several steps, such as filtering, aggregation, and ranking, give each step one CTE. Each CTE reads only the step right before it.

Top 3 customers by order amount per grade (excluding canceled)

WITH valid AS (            -- Step 1: filter the target orders
  SELECT cust_id, amt
  FROM orders
  WHERE cust_id BETWEEN 101 AND 300
    AND status <> 'CANCELED'
),
cust_sum AS (              -- Step 2: aggregate per customer
  SELECT cust_id, COUNT(*) AS orders, SUM(amt) AS total_amt
  FROM valid
  GROUP BY cust_id
),
ranked AS (                -- Step 3: rank within the grade
  SELECT c.grade, s.cust_id, s.orders, s.total_amt,
         RANK() OVER (PARTITION BY c.grade ORDER BY s.total_amt DESC) AS rnk
  FROM cust_sum s
  JOIN customers c ON c.cust_id = s.cust_id
)
SELECT grade, rnk, cust_id, orders, total_amt
FROM ranked
WHERE rnk <= 3
ORDER BY grade, rnk

Window functions cannot be used in WHERE, so the ranking is done in one step and the filtering in the next. Among customers 101–300 there are 2 VIPs, so the VIP ranking does not exceed 2 rows.

TIP Check an intermediate result by changing only the last SELECT, for example to SELECT * FROM cust_sum. Leave the earlier steps as they are and add one step at a time.

Referencing the same CTE twice

A CTE can be referenced several times within one statement. You do not have to write the same aggregate twice.

Ratio to the total: build the per-grade totals once, and read each row together with their overall sum.

Order amount per grade and its ratio to the total

WITH grade_sum AS (
  SELECT c.grade, COUNT(*) AS orders, SUM(o.amt) AS total_amt
  FROM orders o
  JOIN customers c ON c.cust_id = o.cust_id
  WHERE o.cust_id BETWEEN 101 AND 300
  GROUP BY c.grade
)
SELECT g.grade, g.orders, g.total_amt,
       ROUND(100.0 * g.total_amt / (SELECT SUM(total_amt) FROM grade_sum), 1) AS pct
FROM grade_sum g
ORDER BY g.grade

NOTE In SQL Server, SUM of an int column is also int. If the total exceeds about 2.1 billion (2,147,483,647), you get the error Msg 8115: Arithmetic overflow. Widening the range of the query above to 101 AND 1000 raises this error in SQL Server. Write large totals as SUM(CAST(o.amt AS bigint)). Oracle's NUMBER and PostgreSQL's sum(integer) (result bigint) do not overflow in this range.

Self-comparison: join the per-year totals CTE under two names, cur and prev, to compare with the previous year. Because it is a LEFT JOIN, prev_amt is NULL for the first year, which has no previous year.

Oracle, PostgreSQL · Yearly order amount per grade and year-over-year change

WITH yearly AS (
  SELECT c.grade, EXTRACT(YEAR FROM o.ord_dt) AS yr, SUM(o.amt) AS total_amt
  FROM orders o
  JOIN customers c ON c.cust_id = o.cust_id
  WHERE o.cust_id BETWEEN 101 AND 1000
    AND o.ord_dt < DATE '2025-01-01'
  GROUP BY c.grade, EXTRACT(YEAR FROM o.ord_dt)
)
SELECT cur.grade, cur.yr, cur.total_amt, prev.total_amt AS prev_amt,
       ROUND(100.0 * (cur.total_amt - prev.total_amt) / prev.total_amt, 1) AS growth_pct
FROM yearly cur
LEFT JOIN yearly prev ON prev.grade = cur.grade AND prev.yr = cur.yr - 1
ORDER BY cur.grade, cur.yr

SQL Server · Yearly order amount per grade and year-over-year change

WITH yearly AS (
  SELECT c.grade, YEAR(o.ord_dt) AS yr, SUM(o.amt) AS total_amt
  FROM orders o
  JOIN customers c ON c.cust_id = o.cust_id
  WHERE o.cust_id BETWEEN 101 AND 1000
    AND o.ord_dt < CAST('2025-01-01' AS date)
  GROUP BY c.grade, YEAR(o.ord_dt)
)
SELECT cur.grade, cur.yr, cur.total_amt, prev.total_amt AS prev_amt,
       ROUND(100.0 * (cur.total_amt - prev.total_amt) / prev.total_amt, 1) AS growth_pct
FROM yearly cur
LEFT JOIN yearly prev ON prev.grade = cur.grade AND prev.yr = cur.yr - 1
ORDER BY cur.grade, cur.yr

Both examples can also be written with window functions. The ratio is SUM(total_amt) OVER (), and the previous year's value is LAG(total_amt) OVER (PARTITION BY grade ORDER BY yr). A join pairs rows by key value, such as "1 year earlier", while LAG pairs with the immediately preceding row. If a year is missing in between, the two results differ.

Parameter row CTE

When constants such as a period or a range are scattered across a query, gather them into a one-row CTE p and join it. To change a value, edit only p. All three DBs accept a SELECT without FROM (Oracle as of 23ai). Date literals differ per DB (Expressions and Functions).

Oracle, PostgreSQL · Orders in the same period by customers who joined within the period

WITH p AS (
  SELECT DATE '2024-01-01' AS from_dt, DATE '2025-01-01' AS to_dt,
         1451 AS cust_from, 1470 AS cust_to
)
SELECT c.cust_id, c.join_dt, COUNT(*) AS orders, SUM(o.amt) AS total_amt
FROM p
JOIN customers c ON c.cust_id BETWEEN p.cust_from AND p.cust_to
                AND c.join_dt >= p.from_dt AND c.join_dt < p.to_dt
JOIN orders o    ON o.cust_id = c.cust_id
                AND o.ord_dt >= p.from_dt AND o.ord_dt < p.to_dt
GROUP BY c.cust_id, c.join_dt
ORDER BY c.cust_id

SQL Server · Orders in the same period by customers who joined within the period

WITH p AS (
  SELECT CAST('2024-01-01' AS date) AS from_dt, CAST('2025-01-01' AS date) AS to_dt,
         1451 AS cust_from, 1470 AS cust_to
)
SELECT c.cust_id, c.join_dt, COUNT(*) AS orders, SUM(o.amt) AS total_amt
FROM p
JOIN customers c ON c.cust_id BETWEEN p.cust_from AND p.cust_to
                AND c.join_dt >= p.from_dt AND c.join_dt < p.to_dt
JOIN orders o    ON o.cust_id = c.cust_id
                AND o.ord_dt >= p.from_dt AND o.ord_dt < p.to_dt
GROUP BY c.cust_id, c.join_dt
ORDER BY c.cust_id

from_dt and to_dt are used in both the join date and order date conditions. Customers 1451–1460 joined in 2023, so they drop out.

NOTE A parameter row is a way to organize constants in queries you run directly. In an application, use bind variables in place of the constants.

Inlining and materialization

A DB processes a CTE in one of two ways.

  • Inlining: expands the CTE's query in place wherever it is referenced. It works like an inline view: outer conditions can be pushed into the CTE, and referencing it twice computes it twice.
  • Materialization: computes the CTE once, keeps it as a temporary result, and reads that result at each reference.
DBHow to chooseWhat appears in the execution plan
PostgreSQLAS MATERIALIZED, AS NOT MATERIALIZED. Without them, a single reference is inlined and two or more references are materializedWhen materialized, a CTE name step and CTE Scan
OracleA /*+ MATERIALIZE */ or /*+ INLINE */ hint after SELECT inside the CTE. Without one, the optimizer decidesWhen materialized, TEMP TABLE TRANSFORMATION and a SYS_TEMP_… table
SQL ServerNo syntax to choose. Always inlinedThe source table is read as many times as it is referenced

The query below references cust_sum twice, in the outer FROM and in a scalar subquery (the rank is the number of customers with a larger total + 1).

CTE referenced twice

WITH cust_sum AS (
  SELECT cust_id, SUM(amt) AS total_amt
  FROM orders
  WHERE cust_id BETWEEN 101 AND 120
  GROUP BY cust_id
)
SELECT a.cust_id, a.total_amt,
       (SELECT COUNT(*) FROM cust_sum b WHERE b.total_amt > a.total_amt) + 1 AS rnk
FROM cust_sum a
ORDER BY rnk, a.cust_id

In the execution plan, PostgreSQL has CTE cust_sum and Oracle has TEMP TABLE TRANSFORMATION, so orders is read only once. Adding AS NOT MATERIALIZED in PostgreSQL or /*+ INLINE */ in Oracle removes that step, and in Oracle the read of orders on the scalar subquery side repeats as many times as there are outer rows (20 times).

Materializing a CTE that is referenced only once can keep outer conditions from being pushed into it.

PostgreSQL · MATERIALIZED: materializing a CTE referenced once

WITH s AS MATERIALIZED (
  SELECT cust_id, COUNT(*) AS orders, SUM(amt) AS total_amt
  FROM orders
  WHERE cust_id BETWEEN 101 AND 200
  GROUP BY cust_id
)
SELECT * FROM s WHERE cust_id = 150

Oracle · MATERIALIZE hint: materializing a CTE referenced once

WITH s AS (
  SELECT /*+ MATERIALIZE */ cust_id, COUNT(*) AS orders, SUM(amt) AS total_amt
  FROM orders
  WHERE cust_id BETWEEN 101 AND 200
  GROUP BY cust_id
)
SELECT * FROM s WHERE cust_id = 150

With MATERIALIZED, PostgreSQL aggregates all of 101–200 first and then filters for 150; without it, PostgreSQL reads only the orders of customer 150. In Oracle the hint creates TEMP TABLE TRANSFORMATION, but in this example the cust_id = 150 condition is pushed down into the side that builds the temporary result, so only customer 150 is aggregated. The result is the same either way; what changes is the amount read.

TIP Whether materialization helps depends on the data and the query. Compare the rows read (A-Rows, Buffers) in the execution plans before and after adding the keyword or hint.