// dialect comparison

Numbering rows: ROW_NUMBER, ROWNUM and rowid

One portable window function, and two Oracle and SQLite features that look similar but do something else.

Filed under Querying

The verdict

ROW_NUMBER() is the portable answer, with identical syntax on all five engines. Don't confuse it with row identifiers: Oracle's ROWNUM numbers rows before the sort, and SQLite's rowid, PostgreSQL's ctid and Oracle's ROWID identify stored rows, not positions in a result.

Where they differ

ROW_NUMBER() OVER (ORDER BY …) numbers rows after sorting and works in all five engines. Oracle's ROWNUM is assigned before sorting, and SQLite's rowid is the table's storage key rather than a position in the result.

How each engine writes it

SQL Server

SELECT ROW_NUMBER() OVER (ORDER BY hired_at) AS rn, name FROM employees;

Ties get arbitrary numbers unless the ORDER BY is unique, so append a tiebreaker column.

PostgreSQL

SELECT ROW_NUMBER() OVER (ORDER BY hired_at) AS rn, name FROM employees;

No rowid. The ctid system column is a physical location that changes on every UPDATE.

MySQL

SELECT ROW_NUMBER() OVER (ORDER BY hired_at) AS rn, name FROM employees;

8.0+. On 5.7 the @rn := @rn + 1 user-variable trick was the workaround; its evaluation order is not guaranteed, and assigning variables inside expressions is deprecated in 8.0.

SQLite

SELECT ROW_NUMBER() OVER (ORDER BY hired_at) AS rn, name FROM employees;

Window functions since 3.25. Every table except WITHOUT ROWID tables also has a rowid, which is a key, not a result position.

Oracle

SELECT ROW_NUMBER() OVER (ORDER BY hired_at) AS rn, name FROM employees;

The old form, SELECT ROWNUM AS rn, name FROM (SELECT name FROM employees ORDER BY hired_at), needs the subquery because ROWNUM is assigned before ORDER BY.

Questions that come up

What is the difference between ROWNUM and ROW_NUMBER in Oracle?

ROWNUM is a pseudo-column assigned as rows are fetched, before ORDER BY runs, so SELECT ROWNUM, name FROM employees ORDER BY hired_at shows scrambled numbers. ROW_NUMBER() OVER (ORDER BY hired_at) numbers the sorted result. ROWNUM also can't be filtered with WHERE ROWNUM > 1, which never returns a row.

Can I use rowid or ctid as a stable key?

No. PostgreSQL's ctid changes on every UPDATE and on VACUUM FULL. SQLite's rowid can change on VACUUM unless it is aliased by an INTEGER PRIMARY KEY column. Oracle's ROWID changes when a row moves, for example after ALTER TABLE … MOVE or a partition key update. Declare a real primary key.

Why do my ROW_NUMBER values differ between runs?

The ORDER BY inside OVER isn't unique, so tied rows get numbers in whatever order the engine reads them. Add a unique tiebreaker: OVER (ORDER BY hired_at, id).

Keep reading

// write it once, run it anywhere

Switch engines without relearning SQL

SQLly is a native SQL workbench for macOS, Windows and Linux. Its formatter and plan viewer work in all five dialects.