Wednesday, April 20, 2011

Oracle's equivalent of SQL Server's TOP command

Rownum is used in Oracle to retrieve the N-top records.

SELECT * FROM emp  WHERE rownum < 2

Note: Some things to keep in mind are that the “>=” or the “>” operators wont work with ROWNUM. Also remember ROWNUM is to only pick the required row from a result set and should not be confused with the position of the record in the table.

you want the first row of an ordered result set, you need to do the following:

SELECT e.*
  FROM (SELECT * FROM emp ORDER BY empno) e
WHERE rownum < 2 ;

The reason why is because rownum is assigned to the result set as the records are retrieved but before they are sorted. For that reason you must order the result set in an in-line view before using rownum to retrieve the first row (or any number of first rows for that matter).

Do some R & D in Row_Number() in ORACLE

No comments:

Post a Comment