sql – What is the syntax for the functional equivalent of SELECT TOP(N) in Oracle?

Question:

Suppose there is a table TABLE

ID | DEF
 1 | Один
 2 | Два
 3 | Три
 4 | Четыре

Then the query in MS SQL Server

SELECT TOP(2) * FROM TABLE ORDER BY ID DESC

Will give us the output:

ID | DEF
 4 | Четыре
 3 | Три

And a similar query in Oracle (an analogue that was offered to me on the Internet)

SELECT * FROM TABLE WHERE ROWNUM <= 2 ORDER BY ID DESC

Will give us the output:

ID | DEF
 2 | Два
 1 | Один

How to get a really similar syntax for Oracle?

Answer:

In oracle up to version 11 inclusive – through a subquery with row_number :

select *
  from (select t.*, row_number() over (order by id desc) rn
          from t)
 where rn <= 2

In the 12th version, the syntax for the first N lines with LIMIT and OFFSET appeared, almost like in postgres (request copied from the Internet, the 12th oracle is not at hand):

 select *
   from t
  order by id desc
 OFFSET 5 ROWS FETCH NEXT 5 ROWS ONLY;
Scroll to Top