// window reference

Oracle ROWNUM pseudocolumn

ROWNUM numbers rows as Oracle fetches them, before sorting. Top-N queries need the sort in a subquery, or FETCH FIRST and ROW_NUMBER().

Kategorie
Fenster
Returns
NUMBER
In this category
79 of 79

Syntax

ROWNUM

Engine-Unterstützung

EngineSupportNotizen
SQL Server Different name or syntax ROW_NUMBER() OVER (ORDER BY ...); TOP (n)
PostgreSQL Different name or syntax ROW_NUMBER() OVER (ORDER BY ...); LIMIT n
MySQL Different name or syntax ROW_NUMBER() OVER (ORDER BY ...) from 8.0; LIMIT n
SQLite Different name or syntax ROW_NUMBER() OVER (ORDER BY ...); LIMIT n
Oracle Ja ROWNUM pseudocolumn

Beispiele

Oracle

SELECT x FROM (SELECT LEVEL AS x FROM dual CONNECT BY LEVEL <= 5) WHERE ROWNUM = 2;  -- no rows

Oracle

SELECT x FROM (SELECT LEVEL AS x FROM dual CONNECT BY LEVEL <= 5 ORDER BY x DESC) WHERE ROWNUM <= 2;  -- 5, 4

Oracle

SELECT LEVEL AS x FROM dual CONNECT BY LEVEL <= 5 ORDER BY x DESC FETCH FIRST 2 ROWS ONLY;  -- 5, 4

Gut zu wissen

  • ROWNUM is assigned as rows pass the WHERE clause, before ORDER BY. WHERE ROWNUM <= 3 ORDER BY salary DESC sorts three arbitrary rows.
  • WHERE ROWNUM = 2 and WHERE ROWNUM > 1 return no rows: the first candidate gets ROWNUM 1, fails the test, and the next candidate is numbered 1 again.
  • From 12c, FETCH FIRST n ROWS ONLY and ROW_NUMBER() say what you mean. If you keep ROWNUM, sort in an inner query and filter in the outer one.

Questions about ROWNUM

How do I page through results with ROWNUM?

Nest twice: SELECT * FROM (SELECT t.*, ROWNUM AS rn FROM (SELECT ... ORDER BY id) t WHERE ROWNUM <= 20) WHERE rn > 10. On 12c and later, ORDER BY id OFFSET 10 ROWS FETCH NEXT 10 ROWS ONLY is simpler.

Is ROWNUM faster than ROW_NUMBER()?

Both let Oracle stop early. The plan shows COUNT STOPKEY for a ROWNUM filter and WINDOW SORT PUSHED RANK for a ROW_NUMBER() filter.

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.