// window reference

SQL window functions in UPDATE

Wrap the windowed query in a CTE and join it in the UPDATE, the only portable way to update rows chosen or numbered by a window.

Категория
Окно
Returns
updated rows
In this category
38 of 79

Синтаксис

WITH r AS (SELECT id, ROW_NUMBER() OVER (...) AS rn FROM t)
UPDATE t SET flag = 1 FROM r WHERE t.id = r.id AND r.rn = 1

Поддержка движка

ДвижокSupportЗаметки
SQL Server Да Supported under this name.
PostgreSQL Да Supported under this name.
MySQL Да MySQL 8.0+; WITH r AS (...) UPDATE t JOIN r ON ... SET ...
SQLite Да SQLite 3.33+ for WITH ... UPDATE ... FROM; older versions use WHERE id IN (SELECT ...)
Oracle Да no WITH before UPDATE; UPDATE ... FROM (windowed subquery) on 23ai, MERGE or WHERE id IN (subquery) on 19c

Примеры

SQL Server

WITH r AS (
  SELECT id, ROW_NUMBER() OVER (PARTITION BY customer_id ORDER BY amount DESC, id) AS rn
  FROM orders
)
UPDATE o SET is_primary = 1
FROM orders o JOIN r ON o.id = r.id AND r.rn = 1;

PostgreSQL

WITH r AS (
  SELECT id, ROW_NUMBER() OVER (PARTITION BY customer_id ORDER BY amount DESC, id) AS rn
  FROM orders
)
UPDATE orders o SET is_primary = true
FROM r WHERE o.id = r.id AND r.rn = 1;

Полезно знать

  • Window functions cannot appear in the SET list, in UPDATE's WHERE, or in DELETE's targeting; every engine rejects them at parse time. Only the CTE/derived-table route works.
  • The statement shape is engine-specific: SQL Server updates through the CTE or joins it; PostgreSQL and SQLite 3.33+ use UPDATE ... FROM; MySQL writes UPDATE t JOIN cte ... SET; Oracle 23ai accepts UPDATE t SET ... FROM (windowed subquery) r WHERE ..., and 19c uses MERGE INTO t USING (windowed subquery).
  • For 'update the top N rows' the windowed CTE replaces the classic TOP/LIMIT-with-subquery hacks and is safe against ties when a tiebreaker is included.

Questions about Window Functions in UPDATE

Why can't I put ROW_NUMBER in my UPDATE's WHERE?

The standard allows window functions only in a SELECT list and ORDER BY, and UPDATE's WHERE is neither. Compute the numbers in a SELECT (CTE or subquery) and join it to the target.

How do I delete duplicates on MySQL 8.0?

Number rows in a CTE, then multi-table DELETE joining the keys: DELETE c FROM contacts c JOIN d ON c.id = d.id WHERE d.rn > 1. Deleting directly from the CTE is not allowed.

Browse every function in the SQL function reference, or see what the SQLly desktop app does for your database.

Cheat sheets for the engines that have it: SQL Server, PostgreSQL, MySQL, SQLite, Oracle.

// fewer lookups

Functions your engine actually has

SQLly's completion lists the built-in functions of the engine you're connected to, whether that's SQL Server, PostgreSQL, MySQL, SQLite or Oracle. Hover a function for help, and signature hints show each argument as you type.