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.
Code
-- 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-levelWHEREwill 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
PostgreSQL EXPLAIN AnalyzerAnalyze PostgreSQL EXPLAIN ANALYZE text or FORMAT JSON plans locally to flag Seq Scans, slow nodes, row misestimates, disk sorts, and index hints.SQL DDL to TypeScript ConverterConvert SQL CREATE TABLE DDL statements into strict TypeScript interfaces with nullable, array, enum, JSONB, and Date or ISO string column mappings.Multi-Mode Escape & Unescape CodecEscape and unescape strings safely across JSON, JavaScript, SQL single-quoted literals, POSIX shell single quotes, and RFC 4180 CSV cells in your browser.SQL FormatterReformat SQL by uppercasing reserved words and breaking lines before SELECT, FROM, WHERE, and other clauses.
FAQ
- What objects does the SQL involve?
- The references are `orders`, `ranked`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.