Using ROWNUM with ORDER BY in Oracle SQL

Lot of times you have tried to use ROWNUM clause along along with the ORDER BY clause and must have been treated with a different output than you expected. You would expect the ROWNUM to be applied after the results have been ordered by the column, but instead it applies the ROWNUM and then does an order by.

Lets look at an example:
Support you had the following data in a student table:
Data1
And we want to find out the youngest student, you would immediately write:
[sql]SELECT * FROM student WHERE ROWNUM=1 ORDER BY age;[/sql]
which would give the output:
Data2

But looking at the data above John/David would should have been the youngest. As I said before, the ORDER BY clause is applied after the ROWNUM selects one row. Lets edit the query a bit and try:
[sql]SELECT * FROM (SELECT * FROM student ORDER BY age) WHERE ROWNUM=1;[/sql]
which would give us the correct output:
Data3

The idea here is to first order the rows/records by moving the order by query as a nested sql and then applying ROWNUM on the resultant data.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s