// window reference

SQL deduplicate with window functions

Number rows per duplicate key with ROW_NUMBER and keep rn = 1 (or delete rn > 1), deterministic deduplication that plain DISTINCT cannot express.

Categoria
Janela
Returns
one row per key
In this category
29 of 79

Sintaxe

WITH d AS (SELECT ..., ROW_NUMBER() OVER (PARTITION BY key1, key2 ORDER BY updated_at DESC) AS rn FROM t)
SELECT * FROM d WHERE rn = 1

Suporte a mecanismos

MotorSupportNotas
SQL Server Sim Supported under this name.
PostgreSQL Sim Supported under this name.
MySQL Sim MySQL 8.0+; delete with WITH ... DELETE t FROM t JOIN cte
SQLite Sim SQLite 3.25+; delete with WITH ... DELETE FROM t WHERE id IN (SELECT id FROM cte ...)
Oracle Sim Supported under this name.

Exemplos

SQL Server

-- delete stale duplicates
WITH d AS (
  SELECT *, ROW_NUMBER() OVER (PARTITION BY email ORDER BY updated_at DESC, id) AS rn
  FROM contacts
)
DELETE FROM d WHERE rn > 1;

PostgreSQL

WITH d AS (
  SELECT id, ROW_NUMBER() OVER (PARTITION BY email ORDER BY updated_at DESC, id) AS rn
  FROM contacts
)
DELETE FROM contacts c USING d WHERE c.id = d.id AND d.rn > 1;

Bom saber

  • DISTINCT removes full-row duplicates only. When duplicates differ in timestamps or status, DISTINCT keeps them all; ROW_NUMBER lets you choose the survivor.
  • Deletion syntax differs per engine: SQL Server deletes straight from the CTE; PostgreSQL uses DELETE ... USING the CTE; MySQL needs a multi-table DELETE t FROM t JOIN cte; SQLite (no multi-table DELETE) and Oracle use WHERE id IN (subquery), Oracle often with ROWID as the key.
  • The ORDER BY decides the survivor; updated_at DESC keeps the newest but ties again make it nondeterministic without an id tiebreaker.

Questions about Deduplicate Rows

Why not just SELECT DISTINCT?

DISTINCT collapses only identical rows and picks no survivor. Duplicates usually differ (two updated_at values), so you need a rule; that rule is the ROW_NUMBER's ORDER BY.

How do I dedupe without deleting anything?

The same CTE with WHERE rn = 1 in a view or report keeps the raw table intact, the safer default when you are not sure which rows are 'real' duplicates.

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.