Thursday, February 5, 2009

SQL SELECT TOP N equivalent in ORACLE

SQL Server:

SELECT TOP 5 id, name, email FROM students

ORACLE:

SELECT id, name, email FROM students WHERE ROWNUM <= 5


Well, this will work fine if we dont use any "order by" clause. what "ROWNUM <= 5" does is simply return you top 5 record in the table.. if you try the ORDER BY code, it will simply extract the top 5 records in the table then ORDER it instead of ORDERING them then select the top 5.

To solve ordering problem we can use the query like this

SELECT id, name, email FROM (select id, name, email from students order by id )
WHERE ROWNUM <= 5 ;


No comments:

Post a Comment