This Oracle tutorial explains how to use the Oracle/PLSQL ROWNUM function with syntax and examples.
The Oracle/PLSQL ROWNUM function returns a number that represents the order that a row is selected by Oracle from a table or joined tables. The first row has a ROWNUM of 1, the second has a ROWNUM of 2, and so on.
The syntax for the ROWNUM function in Oracle/PLSQL is:
There are no parameters or arguments for the ROWNUM function.
The ROWNUM function returns a numeric value.
The ROWNUM function can be used in the following versions of Oracle/PLSQL:
If you want to follow along with this tutorial, get the DDL to create the tables and the DML to populate the data. Then try the examples in your own database!
Let's look at some Oracle ROWNUM function examples and explore how to use the ROWNUM function in Oracle/PLSQL.
In this ROWNUM example, we have a table called customers with the following data:
Now let's demonstrate how the ROWNUM function works by selecting data from the customers table. Enter the following SQL statement in Oracle:
These are the results that you should see:
In this example, the ROWNUM function returns 1 for the first record, 2 for the second record, and so on. Since this is a very simple example, it would appear that the ROWNUM function is straight-forward to use, but it is a bit more complicated than you think.
Let's complicate the example by introducing an ORDER BY clause and sort the results by last_name in ascending order. Enter the following SELECT statement in Oracle:
You should see these results:
You would expect that the first row in your result set would have a ROWNUM value of 1, but in this example, it has a ROWNUM value of 4. Why is this? Well, it depends how Oracle accessed the rows in the query. For example your results can vary depending on a lot of factors (ie: the order that you inserted the data in the table or if there is an index on the table).
Because of these factors, there is a right and wrong way to use the ROWNUM function.
The most reliable way to use the ROWNUM is to use a subquery to filter and sort your results and then place the ROWNUM function in the outer SELECT. Enter the following SELECT in Oracle:
These are the results that you should see:
By using a subquery in this way, it forces the ROWNUM to properly order the records, starting at 1 for the first record, 2 for the second and so on.
The ROWNUM function is also handy if you want to limit the results of a query. For example, you could return the top 2 results. Enter the following SQL statement in Oracle:
You should see these results:
In this example, the ROWNUM function would return the top 2 results because we want ROWNUM < 3.
If we wanted to get the bottom 2 results, we could just change the sort order of the subquery to last_name DESC. Enter the following query in Oracle:
These are the results that you should see:
Now we get the bottom 2 results because we have sorted the last_name in descending order.