Sunday, August 12, 2007

Concept of Rownum

ROWNUM is a pseudocolumn that is available in a query . A ROWNUM value is assigned to a row after it passes the predicate phase of the query but before the query does any sorting or aggregation.

Look at the cases below where rownum fetches record and where it does'nt

select * from emp
where
rownum =1 will work
rownum <=5 will work

but the following where clauses wld'nt work

rownum > 5
rownum = 2

This is the algorithm that oracle uses
****************
rownum=1
for x in ( select * from emp )
loop
if ( Predicate) then -- Predicate is nothing but the Where Clause in your select Query
OUTPUT the row
rownum = rownum + 1
end if;
end loop;
****************

For Rownum=1,<=1, why it works


rownum = 1
for x in ( select * from emp )
loop
if ( rownum = 1 ) then
OUTPUT the row
rownum = rownum + 1
end if;
end loop;

For Rownum>=5, why it doesn't work

rownum = 1
for x in ( select * from emp )
loop
if ( rownum >=5 ) --This will not work for the first row
then
OUTPUT the row
rownum = rownum + 1
end if;
end loop;

Think of it as being processed in this order:
1. The FROM/WHERE clause goes first.
2. ROWNUM is assigned and incremented to each output row from the FROM/WHERE clause.
3. SELECT is applied.
4. GROUP BY is applied.
5. HAVING is applied.
6. ORDER BY is applied.