1) Display 9th record
SELECT ename
FROM emp
WHERE rowid=
(SELECT rowid FROM emp WHERE rownum<=9
MINUS
SELECT rowid FROM emp WHERE rownum <9
);
2) Least 5 earners in company
SELECT * FROM (select EMPNO, ENAME, SAL, RANK() OVER (ORDER BY SAL) RAN from emp) where
RAN<=5
SELECT DISTINCT sal
FROM emp e
WHERE 5>=
(SELECT COUNT(DISTINCT sal) FROM emp a WHERE a.sal<=e.sal
)
ORDER BY sal DESC;
Find out nth highest salary from emp table?
Ans:SELECT DISTINCT (a.sal) FROM EMP A WHERE &N = (SELECT COUNT (DISTINCT
(b.sal)) FROM
EMP B WHERE a.sal<=b.sal);
or
SELECT * FROM (SELECT DISTINCT(SAL),DENSE_RANK() OVER (ORDER BY SAL DESC) AS
RNK FROM EMP) WHERE RNK=&N
or
select min(sal) from (select distinct sal from emp order by sal desc) where rownum <=&n
3) To delete both duplicate records
delete from emp1 where empno in
(select distinct empno from emp1 e where exists ( select count(*) from emp1 d where
e.empno=d.empno having count(*)>1));
4) Dept wise highest sal with emp details:
select empno, ename, deptno, sal from emp
where (sal, deptno) in ( select max(sal), deptno from emp group by deptno).
5) Display last 3 records
select * from emp minus select * from emp where rownum <= (select count(*) -3 from emp);
6) Display max sal in each dept along with emp details:
select a.empno , a.ename,b.sal, b.deptno
from
(select empno, ename, sal , deptno from emp) a,
(select deptno, max(sal) sal from emp group by deptno) b
where a.deptno=b.deptno
and a.sal=b.sal
select a.empno, a.ename, b.sal, b.deptno from emp a ,
(select deptno, max(sal) sal from emp group by deptno) b
where a.deptno=b.deptno
and a.sal=b.sal;
list employees and their manages:
select e.empno, e.ename, m.empno, m.ename from emp e, emp m
where e.mgr=m.empno;
select Empno, Ename, Job, Sal, mgr, level from Emp
start with MGR is null
connect by prior Empno = MGR;
cursor example:
declare
cursor c1 is select * from emp;
x c1%rowtype;
begin
open c1;
loop
fetch c1 into x;
if c1%found
then
dbms_output.put_line(x.empno);
else
exit;
end if;
end loop;
close c1;
end;