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.
One portable window function, and two Oracle and SQLite features that look similar but do something else.
Filed under Querying
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.
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.
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.
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.
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.
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.
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.
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.
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.
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).
One window-function query that runs everywhere, plus PostgreSQL's DISTINCT ON shortcut for one row per group.
Five engines, two spellings of "give me rows 21 to 30", plus Oracle's old ROWNUM wrapper.
ORDER BY random() works on every engine and gets slower with every row you add.
SQLly is a native SQL workbench for macOS, Windows and Linux. Its formatter and plan viewer work in all five dialects.