// window reference

SQL ROW_NUMBER function

Numbers rows 1, 2, 3... within a partition, ordered as specified. No gaps, no ties, which is exactly what deduplication and top-N-per-group need.

카테고리
창
Returns
bigint
In this category
1 of 79

구문

ROW_NUMBER() OVER (PARTITION BY g ORDER BY x)

엔진 지원

엔진Support메모
SQL Server 예 Supported under this name.
PostgreSQL 예 Supported under this name.
MySQL 예 MySQL 8.0+
SQLite 예 SQLite 3.25+
Oracle 예 Supported under this name.

예시

Any engine

SELECT customer_id, amount,
       ROW_NUMBER() OVER (PARTITION BY customer_id ORDER BY amount DESC) AS rn
FROM orders;

Any engine

-- top order per customer
WITH ranked AS (
  SELECT o.*, ROW_NUMBER() OVER (PARTITION BY customer_id ORDER BY amount DESC, id) AS rn
  FROM orders o
)
SELECT * FROM ranked WHERE rn = 1;

알아 두면 좋은 정보

  • Without a full tiebreaker in ORDER BY, equal rows can number differently run to run; nondeterministic dedupes are the classic production bug. Add a unique column as the final ORDER BY key.
  • Window functions cannot appear in WHERE: wrap the query in a CTE or subquery and filter on rn = 1 outside.
  • ROW_NUMBER vs RANK: ROW_NUMBER never ties; RANK gives tied rows the same number and skips the next ones.

Questions about ROW_NUMBER

How do I get the latest row per group?

ROW_NUMBER() OVER (PARTITION BY group ORDER BY updated_at DESC, id) in a CTE, then filter WHERE rn = 1. The id tiebreaker makes it deterministic.

Why can't I use ROW_NUMBER in WHERE?

Window functions evaluate after WHERE. Put them in a subquery or CTE and filter on the computed number outside.

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

// 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.