Using ROWNUM Pseudocolumn in Oracle

When querying in Oracle, use ROWNUM pseudocolumn to limit the number of returned rows. Pseudocolumns behave like table columns but are not actually stored in tables. (Other pseudocolumns are RowId, Level, etc.).

In Sybase, the equivalent way to restrict returned rows in T-SQL is the following:

 Set Rowcount nWhere 'n' stands for number of rows returned by query

Consider following this example, which would restrict the resulting number of rows to9:

 SELECT firstnameFROM   employeeWHERE  ROWNUM < 10 ;

Here are the results:

 FIRSTNAME------------JohnTimJulieStacyRahulLeenaAmyBillTeri

However, one should be careful when using the Order By clause along withRownum. When Order By is used with Rownum to restrict query results, it works onlyif Ordered By is the primary key of the table. For example, empid is the primary key in this employee table:

 SELECT firstnameFROM   employeeWHERE  ROWNUM < 5 ORDER BY empid;

Here are the results:

 FIRSTNAME------------JohnJulieStacyTim

Now consider the following query, ordered by a non-PK column. The order of its results would be unpredictable. It would depend on how the rows were inserted in table.

 SELECT firstnameFROM   employeeWHERE  ROWNUM< 5 ORDER BY firstname;

Here are the results:

 FIRSTNAME------------TeriJulieStacyBill
Share the Post:
Share on facebook
Share on twitter
Share on linkedin

Overview

Recent Articles: