Sunday, January 4, 2009

row number in oracle

ROWNUM- is automatically generated when select is performed.
It is a unique value but not stored permanently.
1. How to retrieve the top 5 salaried employees?
A. select rownum,empno,ename,sal from (select rownum,empno,ename,sal from emp order by sal desc) where rownum<=5;

2. How to retrieve the Nth salaried employee?
A. select empno,ename,job,sal from (select empno,ename,job,sal from emp order by sal desc) group by rownum,empno,ename,job,sal having rownum=&n;

3. How to retrieve alternate rows?
A. select rownum,empno,ename,job,sal from emp group by rownum,empno,ename,job,sal having mod(rownum,2)=0;

4. How to delete the duplicate records which is having the same data,empno & ename?
A. delete from emp where rowid not in(select min(rowid) from emp group by empno);
5. How to retrieve the first five rows from the table?
A. select * from emp where rownum<6;

6. How to retrieve the last five rows from the table?
A. select * from emp minus select * from emp where rownum<=10;
select * from emp minus select * from emp where rownum<=(select
max(rownum)-5 from emp);
7. How to retrieve a particular row from the table?
A. select * from emp where rownum<6 minus select * from emp where rownum<5;
8. How to see the no.of rows in the table?
A. select max(rownum) from emp;
9. How to delete a row from the table using rownum?
A. delete from emp where rownum<2;
delete from emp where rownum<5;
10. How to update row using rownum?
A. update emp set sal=2500 where rownum<2;

No comments:

Post a Comment