Update Top N Per Group Via CTE

Window functions cannot appear in an UPDATE's WHERE clause, so rank rows in a CTE with ROW_NUMBER and flip status through UPDATE FROM past the newest order.

SqlData Integrity

Code

snippet
-- Goal: keep only each customer's newest order active, archive everything else
-- Window functions are legal only in SELECT lists and ORDER BY,
-- so an UPDATE's WHERE cannot call ROW_NUMBER() directly - route it through a CTE
WITH ranked AS (
    SELECT
        id,
        ROW_NUMBER() OVER (
            PARTITION BY customer_id
            ORDER BY created_at DESC, id DESC
        ) AS rn
    FROM orders
)
UPDATE orders o
SET status = 'archived'
FROM ranked r
WHERE o.id = r.id
  AND r.rn > 1;

What the code does

What runs is SELECT / UPDATE, with orders and ranked as the object involved.

Mechanically, the statements are built from: a CTE (WITH … AS) that names an intermediate result before the main query; a WHERE clause narrowing which rows one statement affects; a window function (OVER (…)) computing values across rows without collapsing them; an ORDER BY that fixes the output order.

What to watch for

  • Window functions evaluate after WHERE/GROUP BY, so filtering on their output in the same-level WHERE will not work — use an outer query or a CTE.

Applying it

Point it at the orders table.

Statements that matter

WITH ranked AS (
    SELECT
        id,
        ROW_NUMBER() OVER (
            PARTITION BY customer_id
            ORDER BY created_at DESC, id DESC
        ) AS rn
    FROM orders
)
UPDATE orders o
SET status = 'archived'
FROM ranked r
WHERE o.id = r.id
  AND r.rn > 1;

Interactive Tools for This Topic

FAQ

What objects does the SQL involve?
The references are `orders`, `ranked`.