Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select Nth Row From A Table In Oracle

Tags:

sql

oracle

How can I select the Nth row from a table in Oracle?

I tried

SELECT PRICE FROM AAA_PRICING WHERE ROWNUM = 2

but that didn't work. Please help!

like image 580
Niraj Choubey Avatar asked Dec 22 '10 12:12

Niraj Choubey


6 Answers

Based on the classic answer:

http://asktom.oracle.com/pls/asktom/f?p=100:11:0::::P11_QUESTION_ID:127412348064

select * 
  from ( select a.*, rownum rnum
           from ( YOUR_QUERY_GOES_HERE -- including the order by ) a
          where rownum <= N_ROWS )
 where rnum >= N_ROWS
/
like image 179
davek Avatar answered Nov 15 '22 03:11

davek


Will not works with '=' (will works <2 or >2, but not equal)

so you can

 SELECT Price from (SELECT PRICE, ROWNUM AS RN FROM AAA_PRICING) WHERE RN = 2
like image 30
Michael Pakhantsov Avatar answered Nov 15 '22 03:11

Michael Pakhantsov


To address the reason for this:

The RowNum is a pseudo-column supplied by Oracle. It is generated while the SELECT-clause is being processed. Since the WHERE-clause is handled before the SELECT-clause, the RowNum does not have a proper value yet.

One can argue whether or not it makes sense to have Oracle throw an exception in situation, but because RowNum still is a pseudo-column it's still valid to have it there.

Note: Don't confuse this with RowId, which is an entire different story!

IMPORTANT EDIT:

Note that what I wrote about RowNum is only true for =, >, >=, IN () and maybe others. If you check for, e.g. RowNum < 10, you only get nine records!? I don't know why that is the case!

like image 28
sjngm Avatar answered Nov 15 '22 03:11

sjngm


Select * From
(
    Select Row_Number() OVER (Order by empno) rno, e.* 
    From scott.emp e
)
Where rno in (1, 3, 11)
like image 3
Art Avatar answered Nov 15 '22 01:11

Art


SELECT PRICE 
FROM (  
  SELECT PRICE,    
  ROWNUM rnum 
  FROM AAA_PRICING
  ORDER BY PRICE ASC
  ) 
WHERE    rnum = 2
like image 2
stjohnroe Avatar answered Nov 15 '22 01:11

stjohnroe


If you are on Oracle 12 or above, You can use the result offset and fetch clauses:

SELECT PRICE FROM AAA_PRICING 
offset 1 rows fetch next 1 rows only
like image 1
sideyn Avatar answered Nov 15 '22 01:11

sideyn