SQL Queries

Download as doc, pdf, or txt
Download as doc, pdf, or txt
You are on page 1of 130
At a glance
Powered by AI
The document provides links and resources for learning SQL and discusses Oracle database concepts like constraints, loops and conditional statements in PL/SQL.

The document discusses primary constraints like primary key, unique, check and references as well as secondary constraints like not null and default that can be defined in Oracle.

The document explains that except for not null, constraints can be defined at both the column and table level in Oracle. Not null can only be defined at the column level.

1

lGuaranteed Popular Links :

Sql url : http://rfhs8012.fh-regensburg.de/~oracle/sqlplus/index.html


Note: Learn from this URL, U will be Master in SQL

IBM Any Document – Reference :-


http://publib.boulder.ibm.com/infocenter/db2help/index.jsp?
topic=/com.ibm.db2.udb.doc/wareh/c0008688.htm

Gentle Introduction to SQL : http://sqlzoo.net/

http://expertanswercenter.techtarget.com/eac/knowledgebaseCategory/0,295197,sid63_tax29681
4_idx0_off50,00.html

Introduction to Oracle: Tutorial Series : http://w2.syronex.com/jmr/edu/db/

Oracle PL/SQL Tutorial : http://www-db.stanford.edu/~ullman/fcdb/oracle/or-plsql.html

Oracle SQL*Plus Tutorial : http://oldweb.uwp.edu/academic/mis/baldwin/sqlplus.htm

Oracle/SQL Tutorial : http://www.db.cs.ucdavis.edu/teaching/sqltutorial/

SQL Tutorial : http://www.1keydata.com/sql/sql.html

SQL - A Practical Introduction. (Free Download) :


http://www.managedtime.com/freesqlbook.php3

Oracle9i Database Online Documentation :


http://scarlet.ucc.nau.edu/oracle9.0.1/index.htm

Oracle9i Database List of Books (Release 9.0.1)

http://scarlet.ucc.nau.edu/oracle9.0.1/nav/docindex.htm

Administrator Guide – DOC - http://scarlet.ucc.nau.edu/oracle9.0.1/server.901/a90117/toc.htm

PL/SQL REFERENCE Guide :

http://scarlet.ucc.nau.edu/oracle9.0.1/appdev.901/a89856/toc.htm

SQL REFERENCE Guide :

http://scarlet.ucc.nau.edu/oracle9.0.1/server.901/a90125/toc.htm

SQL*Plus User's Guide and Reference


http://scarlet.ucc.nau.edu/oracle9.0.1/server.901/a88827/toc.htm
2

CONSTRAINTS

PRIMARY CONSTRAINTS : PRIMARY,UNIQUE,CHECK,REFERENCES)


SECONDARY CONSTRAINTS : NOT NULL,DEFAULT)

CONSTRAINTS BASED ON 2 LEVELS COLUMN LEVEL and TABLE LEVEL

Except Not null all others can be defined as Both table and column
level.

But Not null as only column level.

Eg. For SECONDARY CONSTRAINTS


~~~~~~~~~~~~~~~~~~~~~~~

1. NOT NULL CONSTRAINT

CREATE TABLE EMP9( ENO NUMBER(3) NOT NULL,


ENAME VARCHAR2(10));

2. DEFAULT CONSTRAINT

CREATE TABLE EMP9(ENO NUMBER(3) NOT NULL,


ENAME VARCHAR2(10),DOJ DATE DEFAULT SYSDATE);

3. PRIMARY CONSTRAINT(COLUMN LEVEL)

UNIQUE

CREATE TABLE EMP9(


ENO NUMBER(3) NOT NULL CONSTRAINT UNIEMP UNIQUE,
ENAME VARCHAR2(10));

PRIMARY KEY

CREATE TABLE EMP9(


ENO NUMBER(3) CONSTRAINT PKEMP9 PRIMARY KEY,
ENAME VARCHAR2(10));

4. CHECK CONSTRAINT

CREATE TABLE BANK(


ACNO NUMBER(2) CONSTRAINT PKBANK PRIMARY KEY,
ACTYPE VARCHAR2(2) CONSTRAINT CKBANK CHECK ( ACTYPE IN
('SB','CA','RD')),
ACNAME VARCHAR2(10),
AMOUNT NUMBER(4));

5. REFERENCES

CREATE TABLE EMP9(


ENO NUMBER(3) CONSTRAINT PKE9 PRIMARY KEY,
JOB VARCHAR2(10),
3

ENAME VARCHAR2(10),
MGR NUMBER(4) REFERENCES EMP9(ENO));

6. REFERENCES(REFERING TO DIFFERENT TABLE)

CREATE TABLE DEPT9(DEPTNO NUMBER(2) CONSTRAINT PKDNO PRIMARY


KEY, DNAME VARCHAR2(10), LOC VARCHAR2(10));

CREATE TABLE EMP9( EMPNO NUMBER(4),ENAME VARCHAR2(10),


SAL NUMBER(7,2),DEPTNO NUMBER(2) CONSTRAINT FKDNO REFERENCES
DEPT9(DEPTNO));

7. TABLE LEVEL CONSTRAINTS

UNIQUE TABLE LEVEL

CREATE TABLE BANK( ACNO NUMBER(3),ACTYPE VARCHAR2(10),


BAL NUMBER(7,2),PLACE VARCHAR2(10),CONSTRAINT UNIBANK
UNIQUE(ACNO,ACTYPE));

PRIMARY KEY(TABLE LEVEL)

CREATE TABLE BANK( ACNO NUMBER(2), ACTYPE VARCHAR2(2) CONSTRAINT


CKBANK CHECK (ACTYPE IN ('SB','CA','RD')),AMOUNT NUMBER)

1. Display the Details of all employees working in the same Department


as 'FORD'
SELECT * FROM EMPLOYEES EMP, DEPARTMENT DEPT
WHERE EMP.DEPTNO = DEPT.DEPTNO AND EMP.DEPTNAME = ‘FORD’

2. Display the details of all employees who are joined before 'FORD'
SELECT * FROM EMPLOYEES EMP, DEPARTMENT DEPT
WHERE EMP.DEPTNO = DEPT.DEPTNO AND EMP.JOINED_DATE<(
SELECT JOINED_DATE FROM EMPLOYEES EMP
WHERE EMP.DEPTNAME=’FORD’)

3. Display the Names of all the employees who are all getting the
salary Greater than the salary of 'SMITH' along with the
difference in salary
select ename,sal-(select sal from TEMP_EMP where ename='SMITH')
"DIFF SAL" from TEMP_EMP where sal>(select sal from TEMP_EMP
where ename='SMITH')

4. Display all the employees working in chicago

5. find the two minimum salaries among table


SELECT SAL FROM (SELECT * FROM TEMP_EMP ORDER BY SAL)
WHERE ROWNUM<3
6. Nth Highest Salary
-- select min(sal) "nth highest sal" from TEMP_EMP
4

where sal in ( select sal from (select DISTINCT(sal) from TEMP_EMP order by sal desc) where
rownum<=&n)
-- SELECT DISTINCT (a.sal) FROM TEMP_EMP A
WHERE &N = (SELECT COUNT (DISTINCT (b.sal)) FROM TEMP_EMP B WHERE a.sal<=b.sal)
-- SELECT sal FROM (SELECT ROWNUM rn, sal FROM (SELECT DISTINCT (sal) FROM
temp_emp ORDER BY sal desc)) x WHERE x.rn = :n;

7. How do i get Greatest salaray of dept group from employee (we have to tables EMP and DEPT. for exp: dept 10 have
10000,dept 20 have 5000 and dept 30 have 15000 salaries, i need dept 30 group salary(means sum of that group is 15000). )
-- select deptno,sal1
from (select deptno , sum(sal) sal1 from temp_emp group by deptno order by sal1 desc)
where rownum<=1

Differentiate between TRUNCATE and DELETE

TRUNCATE deletes much faster than DELETE

TRUNCATE DELETE
It is a DDL statement It is a DML statement
It is a one way trip,cannot ROLLBACK One can Rollback
Doesn't have selective features (where clause) Has
Doesn't fire database triggers Does
It requires disabling of referential constraints. Does not require

SUBQUERIES

SINGLE ROW SUBQUERY


MULTIPLE ROW SUBQUERY

SINGLE ROW SUBQUERY

1. DISPLAY THE EMPLOYEES WHOSE JOB IS SAME AS THAT OF JONES


Select * from emp where job = (select job from emp
Where ename = ‘jones’);

2. DISPLAY THE EMPLOYEES BELONGING TO MILLER'S DEPARTMENT


Select * from emp where dname = (select dname from emp
Where ename = ‘milers’);

3. DISPLAY ALL THE EMPLOYEES REPORTING TO KING

Select * from emp where rname = (select rname from emp


Where ename = ‘king’);

4. DISPLAY ALL THE EMPLOYEES WHO ARE GETTING MAX SALARY

Select * from emp where basal = (select max(basal) from emp);

5. DISPLAY ALL THE DETAILS WHERE SAL IS GREATER THAN MILLER'S SALARY
AND WHO ARE IN SALES DEPARTMENT.
5

Select * from emp where dname = ‘sales’ and basal > (select
basal from emp where ename = ‘milers’);

6. DISPLAY ALL THE DETAILS WHO HAVE JOINED IN SAME DATE AS THAT OF
JAMES.

Select * from emp where doj = (select doj from emp where ename =
‘james’);

MULTIPLE ROW SUBQUERIES

7. DISPLAY ALL THE DETAILS WHERE DEPT IS EITHER SALES OR RESEARCH

Select * from emp where dname = any(select dname from emp where
dname = ‘sales’ or dname = ‘research’);

Select * from emp where dname = any(select dname from emp where
Dname like(‘sales’,’research’));

SUBQUERY RETURNING MULTIPLE COLUMNS

SELECT ENAME,JOB,MGR FROM EMP WHERE (JOB,MGR) IN(SELECT JOB,MGR


FROM EMP WHERE EMPNO=7788);

EXPRESSIONS WITH SUBQUERIES

SELECT * FROM EMP WHERE SAL=(SELECT SAL+50 FROM EMP WHERE


ENAME='JONES');

 ROWID

For each row in the database, the ROWID pseudocolumn returns a


row's address.ROWID values contain information necessary to locate a
row:
* which data block in the data file
* which row in the data block (first row is 0)
* which data file (first file is 1)

 ROWNUM

For each row returned by a query, the ROWNUM pseudocolumn


returns a number indicating the order in which Oracle selects the row
from a table or set of joined rows. The first row selected has a ROWNUM
Of 1, the second has 2, and so on.

CORRELATED SUBQUERY

FIRST TRY USING MAX


6

 5TH HIGHEST SALARY

SELECT * FROM EMP A WHERE 5=(SELECT COUNT(DISTINCT SAL)FROM


EMP B WHERE A.SAL<=B.SAL);

 DELETE DUPLICATE DEPARTMENT NUMBERS

DELETE FROM DEPT A WHERE ROWID NOT IN (SELECT MIN(ROWID) FROM


DEPT B WHERE A.DEPTNO=B.DEPTNO);

 DISPLAY ALTERNATE ROWS

SELECT * FROM EMP WHERE ROWID IN


(SELECT DECODE(MOD(ROWNUM,2),0,ROWID) FROM EMP);

 TO DISPLAY NTH HIGHEST SALARY

SELECT MAX(SAL) FROM EMP A WHERE &N=(SELECT COUNT(DISTINCT


SAL) FROM EMP B WHERE A.SAL<=B.SAL);

SELECT * FROM EMP A WHERE &N=(SELECT COUNT(DISTINCT SAL)


FROM EMP B WHERE A.SAL<=B.SAL);

 DELETE DUPLICATE OCCURENCES

DELETE FROM DEPT WHERE DEPTNO IN(SELECT DEPTNO FROM DEPT


GROUP BY DEPTNO HAVING COUNT(DEPTNO)>1);

DELETE FROM emp A WHERE ROWID NOT IN(SELECT MIN(ROWID) FROM


emp WHERE A.DEPTNO=B.DEPTNO);

 DISPLAY ALTERNATE ROWS

SELECT * FROM GDEPT WHERE ROWID IN(SELECT


DECODE(MOD(ROWNUM,2),0,ROWID) FROM GDEPT);

 DISPLAY from NTH ROW

SELECT * FROM DEPT WHERE ROWID NOT IN(SELECT ROWID FROM DEPT
WHERE ROWNUM<=(SELECT COUNT(*)-&N FROM DEPT));

 DISPLAY DETAILS OF ALL EMPLOYEES WHOSE SAL IS GREATER THAN


AVG(SAL) OF EMPLOYEES IN RESPECTIVE DEPTS

SELECT A.ENAME,A.DEPTNO,A.SAL FROM EMP A,EMP B


WHERE B.SAL>(SELECT AVG(SAL) FROM EMP B GROUP BY DEPTNO)
7

 DISPLAY ALL THE DETAILS WHERE SAL> LOWEST SAL OF EMPLOYEES IN


DEPTNO 20

SELECT * FROM EMP WHERE SAL> ANY(SELECT SAL FROM EMP WHERE
DEPTNO=20);

SELECT * FROM EMP WHERE SAL> ANY (SELECT SAL FROM EMP WHERE
DEPTNO=20);

 DISPLAY ALL THE DETAILS WHERE SAL> HIGHEST SAL OF EMPLOYEES IN


DEPTNO 20

DECLARE
NAME EMP.ENAME%TYPE;
SALARY EMP.SAL%TYPE;
DESIG EMP.JOB%TYPE:='&JOB';
BEGIN
SELECT ENAME,SAL,JOB INTO NAME,SALARY ,DESIG FROM EMP WHERE
JOB=DESIG;
DBMS_OUTPUT.PUT_LINE(NAME||' '||SALARY||' '||DESIG);
END;

1.display name,hiredate of all employees using cursors


2.DISPLAY DETAILS OF ALL EMPLOYEES WHO ARE CLERKS
3.DISPLAY DETAILS OF ALL EMPLOYEES WHEN DEPTNO IS 10.
4. EXAMPLES FOR %FOUND A B C
5.*ASSIGNMENT CLERK 200/-INCREMENT MANAGER INSERT TO TEMP ANALYST
DELETE SALESMAN AND ANNSAL>15000 300/- DECREMENT
6. EXAMPLE FOR %ISOPEN
7.EXAMPLE FOR C1%ROWCOUNT (7 A, 7 B)* display first 5 records
8. display details of first 5 highly paid employees
9.EVEN ROWS
10.NTH ROW
11.CURSOR USING FOR LOOP
12.IF ANNSAL>10000 AND JOB=CLERK INCOME TAX IS 10%,IF ANNSAL>15000 AND
JOB=SALESMAN TAX IS 20%,IF ANNSAL>10000 AND JOB=MANAGAER INCOME TAX IS
30%,ELSE A MESSAGE <10000.

13 CURSOR PARAMETERS TO PASS EMPLOYEE NUMBER AND GET THE DETAILS

14 PASS JOB & GET THE DETAILS

15 PASS DEPTNO AND JOB AND GET THE DETIALS

16 CURSOR LOCKS

17 EXAMPLE FOR IMPLICIT CURSORS

18 INSERT WITH IMPLICIT CURSORS

19 UPDATE AND SELECT WITH IMPLICIT CURSORS

20 DELETE WITH IMPLICIT CURSORS

21.DISPLAY NAMES OF EMPLOYEES WITH SAL IN DESCENDING ORDER


WITHOUT USING ORDER BY
8

22.DISPLAY JOB CATEGORIES ,COUNT(JOB) AND SUM(SAL) FROM EMP

Answers:

1. display name,hiredate of all employees using cursors

DECLARE
cursor c1 is select ename,hiredate from emp;
name varchar(20);
hdate date;
begin
open c1;
loop
fetch c1 into name,hdate;
exit when c1%NOTFOUND;
dbms_output.put_line(name||' '||hdate);
end loop;
close c1;
end;

(VERY IMPORTANT POINT TO BE NOTED IS THAT EXIT WHEN CONDITION IS


SATISFIED WHEN THE FETCH RETURNS FALSE AND WE WILL COME OUT OF LOOP
WHEN EXIT CONDITION IS TRUE.)

4. EXAMPLES FOR %FOUND

DECLARE
cursor c1 is select ename,sal,DEPTNO from emp
WHERE DEPTNO=10;
name varchar(20);
sl number;
dno number;
begin
open c1; loop
fetch c1 into name,sl,dno ;
IF c1%notFOUND THEN
DBMS_OUTPUT.PUT_LINE('CURSOR IS NOT FOUND');
exit;
elsif c1%found then
DBMS_OUTPUT.PUT_LINE('FOUND'||' '||C1%ROWCOUNT);
--INSERT INTO TEMP VALUES(NAME,SL,DNO);
END IF;
end loop;
close c1;
end;

4 B

DECLARE
cursor c1 is select * from emp
WHERE DEPTNO=&deptno;
a emp%rowtype;
begin
open c1;
LOOP
fetch c1 into a;
9

IF c1%FOUND THEN
DBMS_OUTPUT.PUT_LINE(A.ENAME||' '||A.SAL||' '||A.DEPTNO);
else
EXIT;
END IF;
END LOOP;
close c1;
end;

4 C

DECLARE
cursor c1 is select * from emp
WHERE DEPTNO=&deptno;
a emp%rowtype;
begin
open c1;
loop
fetch c1 into a;
IF not c1%FOUND THEN
exit;
else
DBMS_OUTPUT.PUT_LINE(a.ename||' '||a.sal);
END IF;
end loop;
close c1;
end;

5.CLERK 200/-INCREMENT MANAGER INSERT NAME,SAL TO TEMP ANALYST DELETE


SALESMAN AND ANNSAL>15000 300/- INCREMENT

DECLARE
CURSOR C1 IS SELECT * FROM EMP;
A C1%ROWTYPE;
BEGIN
OPEN C1;
LOOP
FETCH C1 INTO A;
EXIT WHEN C1%NOTFOUND;
IF A.JOB='CLERK' THEN
UPDATE EMP SET SAL=A.SAL+200 WHERE EMPNO=A.EMPNO;
COMMIT;
ELSIF A.JOB='MANAGER' THEN
DBMS_OUTPUT.PUT_LINE('ROW INSERTED');
INSERT INTO TEMP VALUES(A.ENAME,A.JOB,A.SAL);
COMMIT;
ELSIF A.JOB='ANALYST' THEN
DBMS_OUTPUT.PUT_LINE('ROW DELETED');
DELETE FROM EMP WHERE EMPNO=A.EMPNO;
COMMIT;
ELSIF A.JOB='SALESMAN' AND A.SAL*12>5000 THEN
DBMS_OUTPUT.PUT_LINE('ROW SALESMAN UPDATED');
UPDATE EMP SET SAL=SAL+300 WHERE EMPNO=A.EMPNO;
COMMIT;
ELSE
DBMS_OUTPUT.PUT_LINE('NO CHANGES');
10

END IF;
END LOOP;
CLOSE C1;
END;

CREATE TABLE TEMP( A VARCHAR2(10),B VARCHAR2(10),C NUMBER(7,2));

6. EXAMPLE FOR %ISOPEN

DECLARE
CURSOR C1 IS SELECT * FROM EMP;
A C1%ROWTYPE;
BEGIN
IF C1%ISOPEN THEN
DBMS_OUTPUT.PUT_LINE('CURSOR ALREADY OPEN');
ELSE
DBMS_OUTPUT.PUT_LINE('CURSOR IS YET TO BE OPENED');
OPEN C1;
END IF;
LOOP
FETCH C1 INTO A;
EXIT WHEN C1%NOTFOUND;
DBMS_OUTPUT.PUT_LINE(A.SAL||' '||A.ENAME||' '||A.JOB);
END LOOP;
CLOSE C1;
END;

6. B

IF NOT C1%ISOPEN
OPEN C1;
ELSE
DBMS_OUTPUT.PUT_LINE('CURSOR IS NOT OPEN');
END IF;

7.EXAMPLE FOR C1%ROWCOUNT display first 5 records

DECLARE
cursor c1 is select * from emp;
a c1%rowtype;
begin
open c1;
loop
fetch c1 into a;
exit when c1%rowcount>6;
dbms_output.put_line(a.ename||' '||a.sal||' '||a.job||'
'||C1%ROWCOUNT);
11

end loop;
close c1;
end;

7 B other method for above pgm

DECLARE
cursor c1 is select * from emp;
a c1%rowtype;
begin
open c1;
loop
fetch c1 into a;
exit when c1%notfound;
if c1%rowcount<=6 then
dbms_output.put_line(a.ename||' '||a.sal||' '||a.job);
end if;
end loop;
close c1;
end;

8 display details of first 5 highly paid employees

DECLARE
cursor c1 is select * from emp order by sal desc;
a c1%rowtype;
begin
open c1;
loop
fetch c1 into a;
exit when c1%rowcount>6;
dbms_output.put_line(a.ename||' '||a.sal||' '||a.job||'
'||C1%ROWCOUNT);
end loop;
close c1;
end;

9. display only even rows

DECLARE
cursor c1 is select * from emp ;
a c1%rowtype;
begin
open c1;
loop
fetch c1 into a;
exit when c1%notfound;
if mod(c1%rowcount,2)=0 then
dbms_output.put_line(a.ename||' '||a.sal||' '||a.job);
end if;
end loop;
close c1;
end;

(for odd rows change 0 to 1);

10 display nth row


12

DECLARE
cursor c1 is select * from emp ;
a c1%rowtype;
n number;
begin
n:=&n;
open c1;
loop
fetch c1 into a;
exit when c1%notfound;
if c1%rowcount=n then
dbms_output.put_line(a.ename||' '||a.sal||' '||a.job);
end if;
end loop;
close c1;
end;

11 cursor using for loop

declare
cursor c2 is select * from emp;
begin
for a in c2 loop
dbms_output.put_line(a.ename||' '||a.sal||' '||a.job);
end loop;
end;

12. IF ANNSAL>10000 AND JOB=CLERK INCOME TAX IS 10%,IF ANNSAL>15000 AND


JOB=SALESMAN TAX IS 20%,IF ANNSAL>10000 AND JOB=MANAGAER INCOME TAX IS
30%,ELSE A MESSAGE <10000

alter table emp add(it number(3));


declare
cursor c1 is select * from EMP;
a c1%rowtype;
begin
open c1;
loop
fetch c1 into a;
exit when c1%notfound;
if a.sal*12>10000 and a.job='CLERK' THEN
UPDATE EMP SET IT=A.SAL*12*0.1 WHERE EMPNO=A.EMPNO;
ELSIF A.SAL*12>15000 AND A.JOB ='SALESMAN' THEN
UPDATE EMP SET IT=A.SAL*12*0.2 WHERE EMPNO=A.EMPNO;
ELSIF A.SAL*12>10000 AND A.JOB='MANAGER' THEN
UPDATE EMP SET IT=A.SAL*12*0.3 WHERE EMPNO=A.EMPNO;
ELSIF A.SAL*12<10000 THEN
DBMS_OUTPUT.PUT_LINE(A.ENAME||' '||'SAL< 10000');
END IF;
END LOOP;
COMMIT;
CLOSE C1;
END;

13 CURSOR PARAMETERS TO PASS EMPLOYEE NUMBER AND GET THE DETAILS


13

DECLARE
CURSOR C1( z NUMBER) IS SELECT * FROM EMP WHERE DEPTNO=z;
A C1%ROWTYPE;
BEGIN
OPEN C1(&DEPTNO);
LOOP
FETCH C1 INTO A;
EXIT WHEN C1%NOTFOUND;
DBMS_OUTPUT.PUT_LINE(A.ENAME||' '||A.DEPTNO||' '||A.SAL);
END LOOP;
CLOSE C1;
END;

14 TO PASS JOB AND GET THE DETAILS

DECLARE
CURSOR C1( A VARCHAR) IS SELECT * FROM EMP WHERE JOB=A;
A C1%ROWTYPE;
BEGIN
OPEN C1('&AJOB');
LOOP
FETCH C1 INTO A;
EXIT WHEN C1%NOTFOUND;
DBMS_OUTPUT.PUT_LINE(A.JOB||' '||A.ENAME||' '||A.EMPNO||' ||A.SAL);
END LOOP;
CLOSE C1;
END;

NOTE :it will not take job in uppercase so upper(job)=upper(a)

15. TO PASS DESIGNATION AND DEPTNO AND GET THE DETAILS

DECLARE
CURSOR C1(A NUMBER,B VARCHAR) IS SELECT * FROM EMP
WHERE DEPTNO=A AND JOB=B;
A C1%ROWTYPE;
BEGIN
OPEN C1(&ADETNO,'&BJOB');
LOOP
FETCH C1 INTO A;
EXIT WHEN C1%NOTFOUND;
DBMS_OUTPUT.PUT_LINE(A.ENAME||' '||A.JOB||' '||A.SAL||'
||A.DEPTNO);
END LOOP;
CLOSE C1;
END;

16 CURSOR LOCKING
14

DECLARE
CURSOR C1 IS SELECT * FROM EMP FOR UPDATE OF SAL;
A C1%ROWTYPE;
BEGIN
OPEN C1;
LOOP
FETCH C1 INTO A;
EXIT WHEN C1%NOTFOUND;
DBMS_OUTPUT.PUT_LINE(A.JOB||' '||A.ENAME||' '||A.SAL||' '||
A.DEPTNO);
IF A.JOB='CLERK' THEN
UPDATE EMP SET JOB='FDC' WHERE empno=a.empno;
end if;
end loop;
close c1;
end;

17 EXAMPLE FOR IMPLICIT CURSORS

DECLARE
CURSOR C1 IS SELECT * FROM EMP;
A C1%ROWTYPE;
BEGIN
OPEN C1;
LOOP
FETCH C1 INTO A;
EXIT WHEN C1%NOTFOUND;
DBMS_OUTPUT.PUT_LINE(C1%ROWCOUNT||' '||SQL%ROWCOUNT||' '||A.ENAME);
END LOOP;
CLOSE C1;
END;

(YOU WILL NOT GET THE OUTPUT BECAUSE SQL%ROWCOUNT WILL RETURN A VALUE
ONLY WHEN THE PREVIOUS DML OPERATION IS SUCCESSFULLY COMPLETLE)

18. IMPLICIT CURSOR WITH INSERT

CREATE TABLE TEMP(A VARCHAR2(10),B NUMBER(7,2), C VARCHAR2(10));


DECLARE
CURSOR C2 IS SELECT * FROM EMP;
A C2%ROWTYPE;
BEGIN
OPEN C2;
LOOP
FETCH C2 INTO A;
EXIT WHEN C2%NOTFOUND;
INSERT INTO TEMP VALUES(A.ENAME,A.SAL,A.JOB);
IF SQL%FOUND THEN
DBMS_OUTPUT.PUT_LINE(SQL%ROWCOUNT||' '||C2%ROWCOUNT||' '||
A.SAL||' '||A.ENAME);
ELSE
EXIT;
END IF ;
END LOOP;
CLOSE C2;
END;
15

19 DELETE WITH IMPLICIT CURSORS

DECLARE
BEGIN
DELETE FROM EMP WHERE DEPTNO=10;
DBMS_OUTPUT.PUT_LINE(SQL%ROWCOUNT);
END;

20. UPDATE AND SELECT WITH IMPLICIT CURSORS

DECLARE
A EMP%ROWTYPE;
BEGIN
SELECT * INTO A FROM EMP WHERE EMPNO=7788;
DBMS_OUTPUT.PUT_lINE('AFTER SELECT SQLCOUNT'|| ' '||SQL%ROWCOUNT);
UPDATE EMP SET DEPTNO=99 WHERE DEPTNO=10;
DBMS_OUTPUT.PUT_lINE('AFTER UPDATE SQLCOUNT'|| ' '||SQL%ROWCOUNT);
END;

OUTPUT IS
AFTER SELECT SQLCOUNT 1
AFTER UPDATE SQLCOUNT 3

21.DISPLAY NAMES OF EMPLOYEES WITH SAL IN DESCENDING ORDER WITHOUT


USING ORDER BY

DECLARE
CURSOR C1 IS SELECT * FROM EMP;
A C1%ROWTYPE;
N NUMBER;
BEGIN
OPEN C1;
SELECT MAX(SAL) INTO N FROM EMP;
LOOP
FETCH C1 INTO A;
EXIT WHEN C1%NOTFOUND;
DBMS_OUTPUT.PUT_LINE(N);
SELECT MAX(SAL) INTO N FROM EMP WHERE SAL<N;
END LOOP;
CLOSE C1;
END;

22.DISPLAY JOB CATEGORIES ,COUNT(JOB) AND SUM(SAL) FROM EMP

DECLARE
CURSOR C1 IS SELECT JOB,COUNT(JOB) XY ,SUM(SAL) AB FROM EMP
GROUP BY JOB;
A C1%ROWTYPE;
BEGIN
OPEN C1;
LOOP
FETCH C1 INTO A;
EXIT WHEN C1%NOTFOUND;

DBMS_OUTPUT.PUT_LINE('________________________________________________')
;
DBMS_OUTPUT.PUT_LINE(' JOB '||' NUMBER '||' SUM OF SAL
16

');
DBMS_OUTPUT.PUT_LINE(A.JOB||' '|| A.XY ||' '||
A.AB);
END LOOP;
CLOSE C1;
END;

DECLARE
CURSOR T1 IS SELECT * FROM TEST1;
TEST_REC T1%ROWTYPE;
BEGIN
FOR TEST IN T1
LOOP
UPDATE TEST1 SET AREA=400 WHERE RADIUS=50;
IF SQL%ROWCOUNT >0 THEN
DBMS_OUTPUT.PUT_LINE('RECORD IS ALREADY EXISTS');
ELSE
DBMS_OUTPUT.PUT_LINE('THERE IS NO RECORD');
END IF;
END LOOP;
END;

DECLARE
RDA AREAS.RADIUS%TYPE;
BEGIN
SELECT RADIUS INTO RDA FROM AREAS WHERE RADIUS =345;
EXCEPTION WHEN NO_DATA_FOUND THEN DBMS_OUTPUT.PUT_LINE('RECORD NOT
FOUND');
END;

Database objects

TABLES,VIEWS,SYNONYM,INDEX,CLUSTER,SEQUENCE,PROCEDURE,FUNCTION
PACKAGE,TRIGGER

 VIEWS
Virtual table changes reflected in table & viceversa no data of
its own, no redundancy and security. A logical table based on one or
more tables or views.

1.CREATE VIEW EV AS SELECT * FROM EMP;

2.CREATE VIEW EV1 AS SELECT ENAME,EMPNO,DEPTNO FROM EMP;

3.CREATE VIEW EV2(EMPNO,SALARY) AS SELECT EMPNO,SAL FROM EMP;

4.CREATE VIEW EM1 AS SELECT ENAME,SAL,DEPTNO,EMPNO,JOB


FROM EMP WHERE DEPTNO=20;

 READ ONLY VIEW

VIEWS WITH GROUP BY,ORDER BY ,AGG , PRIMARY KEY AND CHECK


CONSTRAINTS. THE VIEW BECOMES A READ ONLY VIEW.

1. CREATE VIEW EV AS SELECT DEPTNO,COUNT(*) COUNT FROM EMP GROUP BY


DEPTNO;
17

2. CREATE VIEW EM1 AS SELECT ENAME,SAL,DEPTNO,EMPNO,JOB


FROM EMP WHERE DEPTNO=20 WITH CHECK OPTION CONSTRAINT CK1;

FORCED VIEWS

CREATE FORCE VIEW ABC AS SELECT EMPNO,ENAME,SAL FROM EMPOP;

SEE THE VIEWS

SELECT * FROM <view name>;

DROP VIEW ABC;

SELECT * FROM USER_VIEW;

CREATE VIEW MAG AS SELECT M.MNO,M.NAME,MA.GP,MA.NP FROM MAGI M,MAG MA ;

SYNONYMS

A synonym is an alternative name for a table,view, sequence,


procedure, stored function.

1).Public synonym
2).Private synonym

CREATE SYNONYM Z FOR EMP;


CREATE PUBLIC SYNONYM VV FOR EMP;
DROP SYNONYM Z;
SELECT * FROM USER_SYNONYMS WHERE TABLE_NAME='EMP';

INDEXES

An index is a database object that contains an entry for each


value that appears in the indexed column(s) of the table or cluster and
provides direct, fast access to rows.

PRIMARY KEY AUTOMATICALLY INDEXED HAS ITS EFFECT ON LARGER TABLES

CREATE INDEX AB ON EMP(EMPNO);


SELECT * FROM USER_INDEXES WHERE TABLE_NAME='EMP';

IF YOU WANT TO INDEX A PRIMARY KEY COLUMN FIRST JUST DISABLE IT

DROP INDEX AB;

SEQUENCES

A sequence is a database object from which multiple users may


generate unique integers.You can use sequences to automatically generate
primary key values.

1.CREATE SEQUENCE S1 INCREMENT BY 10 START WITH 10 MAXVALUE 50


2.CREATE SEQUENCE S5 INCREMENT BY 10 START WITH 10 MAXVALUE 50
18

MINVALUE 5 CYCLE CACHE 2;


3.CREATE SEQUENCE S5 INCREMENT BY –2 START WITH 10 MAXVALUE 20
MINVALUE –5 CYCLE CACHE 2;
4.CREATE SEQUENCE S6 INCREMENT BY –2 START WITH 6 MAXVALUE 20
MINVALUE –4 CYCLE CACHE 2;

SELECT * FROM USER_SEQUENCES WHERE TABLE_NAME='EMP';

DROP SEQUENCE S6;

CLUSTERS

A cluster is a schema object that contains one or more tables


that all have one or more columns in common.

1. create cluster c44(deptno number);


2. create table EMPC44(Eno number(9),deptno number,
SAL NUMBER(7,2),HIREDATE DATE)cluster c44(deptno);
3. create table DMPC44(deptno number,DNAME VARCHAR2(10),
LOC VARCHAR2(10))cluster c44(deptno);
4. create index c1i on cluster c4;

tcl commands

grant, revoke

grant privilege on tablename to username

(PRIVILEGES THAT CAN BE GRANTED ARE SELECT , UPDATE, DELETE, INSERT


ALTER,REFERENCE,INDEX)

1. GRANT SELECT ON EMP TO SAVITHA


2. GRANT SELECT ON EMP TO SAVITHA WITH GRANT OPTION
REVOKE ALL ON EMP FROM GEETHA;

COMMIT, ROLLBACK , SAVEPOINT

SQL> SELECT * FROM DEPT;

DEPTNO DNAME LOC


--------- -------------- -------------
10 ACCOUNTING NEW YORK
20 RESEARCH DALLAS
30 SALES CHICAGO
40 OPERATIONS BOSTON
50 CS MYSORE

SQL> SAVEPOINT A
2 ;

Savepoint created.
19

SQL> INSERT INTO DEPT VALUES(60,'IP','BANGALORE');

1 row created.

SQL> SAVEPOINT B;

Savepoint created.

SQL> INSERT INTO DEPT VALUES(70,'IT','GOA');

1 row created.

SQL> SELECT * FROM DEPT;

DEPTNO DNAME LOC


--------- -------------- -------------
10 ACCOUNTING NEW YORK
20 RESEARCH DALLAS
30 SALES CHICAGO
40 OPERATIONS BOSTON
50 CS MYSORE
60 IP BANGALORE
70 IT GOA

7 rows selected.

SQL> ROLLBACK TO SAVEPOINT B;

Rollback complete.

SQL> SELECT * FROM DEPT;

DEPTNO DNAME LOC


--------- -------------- -------------
10 ACCOUNTING NEW YORK
20 RESEARCH DALLAS
30 SALES CHICAGO
40 OPERATIONS BOSTON
50 CS MYSORE
60 IP BANGALORE

6 rows selected.
20

Triggers:

A database trigger is a stored PL/SQL program unit associated


with a specific database table. Oracle executes (fires) the database
trigger automatically whenever a given SQL operation affects the table.
So,unlike subprograms, which must be invoked explicitly, database
triggers are invoked implicitly. Among other things, you can use
database triggers to

 audit data modifications


 log events transparently
 enforce complex business rules
 derive column values automatically
 implement complex security authorizations
 maintain replicate tables .

CREATE TRIGGER <triggername> AFTER UPDATE/INSERT/DELETE OF


<COLUMN NAME> ON <TABLENAME> FOR EACH ROW
BEGIN
-----
-----
executable statements;
-----
-----
END;

DATABASE TRIGGERS

1. WRITE A DATABASE TRIGGER WHICH WILLN'T ALLOW THE USER TO


INSERT,UPDATE OR DELETE BETWEEN NIGHT 7 AND MORNING 6

2. WRITE A DATABASE TRIGGER WHICH FIRES IF YOU TRY TO INSERT ,


UPDATE OR DELETE AFTER 7'O' CLOCK.

3. WRITE A DATABASE TRIGGER BEFORE INSERTING VALUES ON TO


EMP TABLE IF DEPTNO DOES NOT EXIST IN DEPT THEN RAISE THE ERROR.

4. WRITE A DATABASE TRIGGER TO ILLUSTRATE TABLE LEVEL AND


ROW LEVEL TRIGGERS.

5. WRITE A DATABASE TRIGGER WHICH ACTS JUST LIKE PRIMARY KEY


AND DOES NOT ALLOW DUPLICATE VALUE.

6. CREATE A DATABASE TRIGGER WHICH PERFORMS THE ACTION OF THE


ON DELETE CASCADE;

7. WRITE A DATABASE TRIGGER TO INSERT DISTINCT EMPLOYEE NUMBER TO


EMP TABLE (BEFORE INSERT)

8. WRITE A DATABASE TRIGGER TO UPDATE THE SAL FIELD.IF SAL IS MORE


THAN 5000 OR LESS THAN 1000 THEN RAISE THE ERROR.(BEFORE UPDATE).
21

9. WRITE A DATABASE TRIGGER WHERE WHEN CONDITION IS SPECIFIED. WHEN


JOB IS MANAGER THEN CHECK FOR SALARY. IF SAL IS <1000 THEN
RAISE THE ERROR.

10. WRITE A DATABASE TRIGGER WHICH SHOULD NOT DELETE FROM EMP TABLE
IF THE DAY IS SUNDAY.

11. WRITE A DATABASE TRIGGER WHICH SHOULD NOT ALLOW US TO UPDATE IF WE


ARE DOING TRANSACTIONS IN LAST DAY OF THE MONTH

12. WRITE A DATABASE TRIGGERS WHICH INSERTS THE EMPNO AND DEPTNO
INTO TEMP TABLE(AFTER INSERT)

13. WRITE A DATABASE TRIGGER USING INSERTING AND UPDATING WE SHOULD NOT
INSERT ON SUNDAY AND WE SHOULD NOT UPDATE ON LAST DAY OF THE MONTH.

14. UPDATE EMP TABLE AND CHANGE OLD DEPTNO TO NEW DEPTNO. IF OLD DEPTNO
IS 20 THEN DELETE FROM DEPT WHERE DEPTNO IS EQUAL TO NEW DEPTNO

15. WRITE A DATABASE TRIGGER TO DELETE FROM DEPT TABLE .AFTER DELETING
INSERT THE OLD VALUES TO A TABLE.

16. WRITE A DATABASE TRIGGER WHICH SHOULD NOT DELETE THE ROW IF THE
MONTH IS APRIL.

17. WRITE A DATABASE TRIGGER WHICH FIRES BEFORE PERFORMING INSERT


OR UPDATE OPERATIONS. IF THE JOB IS MANAGER THEN HIS SALARY
SHOULD BE IN THE GRADE 5.ELSE RAISE THE APPLICATION ERROR.

1. WRITE A DATABASE TRIGGER WHICH WILLN'T ALLOW THE USER TO


INSERT,UPDATE OR DELETE BETWEEN NIGHT 7 AND MORNING 6

CREATE OR REPLACE TRIGGER GEETIME BEFORE INSERT OR UPDATE


OR DELETE ON EMP for each row
DECLARE
A VARCHAR2(10);
BEGIN
--select to_char(sysdate,'hh24') into a from dual;
A:=TO_CHAR(SYSDATE,'HH24');
IF TO_NUMBER(A) > 19 OR TO_NUMBER(A) < 7 then
RAISE_APPLICATION_ERROR(-20500,'YOU CANT DO THIS OPERATION NOW');
END IF;
END;

2.WRITE A DATABASE TRIGGER WHICH FIRES IF YOU TRY TO INSERT ,UPDATE OR


DELETE AFTER 7'O' CLOCK

CREATE OR REPLACE TRIGGER GEETIME BEFORE INSERT OR UPDATE OR


DELETE ON EMP for each row
DECLARE
A VARCHAR2(10);
BEGIN
SELECT TO_CHAR(SYSDATE,'HH:MI') INTO A FROM DUAL;
IF A > '06:00' then
22

RAISE_APPLICATION_ERROR(-20500,'YOU CANT DO THIS OPERATION


NOW');
END IF;
END;

2.WRITE A DATABASE TRIGGER BEFORE INSERTING VALUES ON TO


EMP TABLE IF DEPTNO DOES NOT EXIST IN DEPT THEN RAISE THE ERROR.

CREATE OR REPLACE TRIGGER IEMP BEFORE INSERT ON EMP


FOR EACH ROW
DECLARE
A NUMBER;
BEGIN
SELECT COUNT(*) INTO A FROM DEPT WHERE
DEPTNO=:NEW.DEPTNO;
IF A=0 THEN
RAISE_APPLICATION_ERROR(-20300,'PARENT KEY IS NOT
EXISTING');
ELSE
PRINT('RECORD IS ALREADY INSERTED');
END IF;
END;

OUTPUT OF THE QUERY IS AS BELOW

SQL> INSERT INTO EMP(EMPNO,DEPTNO) VALUES(23,44);


INSERT INTO EMP(EMPNO,DEPTNO) VALUES(23,44)
*
ERROR at line 1:
ORA-20300: PARENT KEY IS NOT EXISTING
ORA-06512: at "GEETHA.IEMP", line 6
ORA-04088: error during execution of trigger 'GEETHA.IEMP'

3.WRITE A DATABASE TRIGGER TO ILLUSTRATE TABLE LEVEL AND


ROW LEVEL TRIGGERS.

CREATE OR REPLACE TRIGGER UPTABLE BEFORE update ON EMP


BEGIN
DBMS_OUTPUT.PUT_LINE('UPDATE ON TABLE IS FIRED');
END;

CREATE OR REPLACE TRIGGER UPROW BEFORE UPDATE ON EMP


FOR EACH ROW
BEGIN
DBMS_OUTPUT.PUT_LINE('UPDATE ON ROW IS FIRED');
END;

4.WRITE A DATABASE TRIGGER WHICH ACTS JUST LIKE PRIMARY KEY AND DOES
NOT
ALLOW DUPLICATE VALUES

CREATE OR REPLACE TRIGGER PRIKEY BEFORE INSERT ON EMP


FOR EACH ROW
23

DECLARE
A NUMBER;
BEGIN
SELECT COUNT(*) INTO A FROM EMP WHERE EMPNO=:NEW.EMPNO;
IF A >=1 THEN
RAISE_APPLICATION_eRROR(-20500,'THE PRI KEY RULE IS
VOILATED');
ELSIF A=0 THEN
PRINT('RECORD IS INSERTED');
END IF;
END;

SQL> INSERT INTO EMP(EMPNO,DEPTNO) VALUES(7788,20);


INSERT INTO EMP(EMPNO,DEPTNO) VALUES(7788,20)
*
ERROR at line 1:
ORA-20500: THE PRI KEY RULE IS VOILATED
ORA-06512: at "GEETHA.PRIKEY", line 6
ORA-04088: error during execution of trigger 'GEETHA.PRIKEY'

SQL> INSERT INTO EMP(EMPNO,DEPTNO) VALUES(77,20);

1 row created.

5. CREATE A DATABASE TRIGGER WHICH PERFORMS THE ACTION OF THE


ON DELETE CASCADE;

CREATE OR REPLACE TRIGGER DELDEPT


AFTER DELETE ON DEPT FOR EACH ROW
BEGIN
DELETE FROM EMP WHERE DEPTNO=:OLD.DEPTNO;
PRINT('RECORDS IN EMP ARE ALSO DELETED');
END;

6.WRITE A DATABASE TRIGGER TO INSERT DISTINCT EMPLOYEE NUMBER TO


EMP TABLE (BEFORE INSERT)

CREATE OR REPLACE TRIGGER PRIM_UNIQUE


BEFORE INSERT ON emp FOR EACH ROW
DECLARE
NO NUMBER;
BEGIN
SELECT NVL(MAX(EMPNO),0)+1 INTO NO FROM EMP;
:NEW.EMPNO:=NO;
END;

7.WRITE A DATABASE TRIGGER TO UPDATE THE SAL FIELD.IF SAL IS MORE THAN
5000 OR LESS THAN 1000 THEN RAISE THE ERROR.(BEFORE UPDATE).

CREATE OR REPLACE TRIGGER CHECK_SAL BEFORE update ON emp


FOR EACH ROW
BEGIN
if :new.sal <1000 or :new.sal>5000 then
raise_application_error(-20001,'check sal ');
24

end if;
END;

8.WRITE A DATABASE TRIGGER WHERE WHEN CONDITION IS SPECIFIED.


WHEN JOB IS MANAGER THEN CHECK FOR SALARY. IF SAL IS <1000 THEN
RAISE THE ERROR.

CREATE OR REPLACE TRIGGER EMPNO_CHECK BEFORE INSERT ON emp


FOR EACH ROW when (NEW.job='MANAGER')
BEGIN
if :new.SAL<1000 THEN
raise_application_error(-20001,'PLEASE INCREASE THE SALARY ');
end if;
END;

9.WRITE A DATABASE TRIGGER WHICH SHOULD NOT DELETE FROM EMP TABLE IF
THE DAY IS SUNDAY.

CREATE OR REPLACE TRIGGER EMPNO_CHECK


BEFORE DELETE ON emp
BEGIN
if to_char(sysdate,'dAy')='SUNDAY' then
raise_application_error(-20001,'TO DAY IS SUNDAY ');
end if;
END;

10.WRITE A DATABASE TRIGGER WHICH SHOULD NOT ALLOW US TO UPDATE IF WE


ARE DOING TRANSACTIONS IN LAST DAY OF THE MONTH

CREATE OR REPLACE TRIGGER EMPNO_CHECK


BEFORE UPDATE ON emp
BEGIN
if to_char(sysdate)=LAST_DAY(SYSDATE) then
raise_application_error(-20001,'TO DAY IS LAST DAY OF MONTH');
end if;
END;

11.WRITE A DATABASE TRIGGERS WHICH INSERTS THE EMPNO AND DEPTNO


INTO TEMP TABLE(AFTER INSERT)

CREATE OR REPLACE TRIGGER AFTER_INS


AFTER INSERT ON emp
FOR EACH ROW
BEGIN
INSERT INTO TEMP(EMPNO,DEPTNO)VALUES(:NEW.EMPNO,:NEW.DEPTNO);
END;

12.WRITE A DATABASE TRIGGER USING INSERTING AND UPDATING WE SHOULD NOT


INSERT ON SUNDAY AND WE SHOULD NOT UPDATE ON LAST DAY OF THE MONTH.

CREATE OR REPLACE TRIGGER EMPNO_CHECK


BEFORE INSERT OR UPDATE ON emp
FOR EACH ROW
BEGIN
IF INSERTING THEN
25

if to_char(sysdate,'dy')='mon' then
raise_application_error(-20001,'TO DAY IS SUNDAY ');
end if;
end if;
IF UPDATING THEN
if to_char(sysdate)=LAST_DAY(SYSDATE) then
raise_application_error(-20001,'TO DAY IS MONTHY
LAST DAY so no updating ');
end if;
END IF;
END;

13.UPDATE EMP TABLE AND CHANGE OLD DEPTNO TO NEW DEPTNO. IF OLD DEPTNO
IS 20 THEN DELETE FROM DEPT WHERE DEPTNO IS EQUAL TO NEW DEPTNO

CREATE OR REPLACE TRIGGER AFTER_UPDATE


AFTER UPDATE ON EMP
FOR EACH ROW
BEGIN
IF :OLD.DEPTNO=20 THEN
DELETE FROM DEPT WHERE DEPTNO=:NEW.DEPTNO;
END IF;
END;

14.WRITE A DATABASE TRIGGER TO DELETE FROM DEPT TABLE .AFTER DELETING


INSERT THE OLD VALUES TO A TABLE.

CREATE OR REPLACE TRIGGER AFTER_delete


AFTER delete ON DEPT
FOR EACH ROW
BEGIN
insert into dept1 values(:old.deptno,:old.dname,:old.loc);
END;

15.WRITE A DATABASE TRIGGER WHICH SHOULD NOT DELETE THE ROW


IF THE MONTH IS APRIL.

CREATE OR REPLACE TRIGGER month_CHECK


BEFORE DELETE ON emp
BEGIN
if to_char(sysdate,'month')='july' then
raise_application_error(-20001,'this month is holiday ');
end if;
END;

16.WRITE A DATABASE TRIGGER WHICH FIRES BEFORE PERFORMING INSERT OR


UPDATE OPERATIONS. IF THE JOB IS MANAGER THEN HIS SALARY SHOULD BE
IN THE GRADE 5.ELSE RAISE THE APPLICATION ERROR.

create or replace trigger jobgrade


before insert or update of JOB,SAL on emp
for each row
26

when (new.job='MANAGER')
declare
lo number;
hi number;
begin
select losal,hisal into lo,hi from salgrade where grade=5;
if :new.sal>lo and :new.sal<hi then
print('insert success');
else
raise_application_error(-20500,'INsert operation not allowed');
end if;
end;

EXTRA INFORMATION FOR MISS.MG

create or replace trigger days


before delete on emp
declare
a number:=to_number(to_char(sysdate,'d')) ;
dummy varchar(20);
begin
if NOT a in(1,6) then
raise_application_error(-20002,'today no transaction');
else
begin
select user into dummy from dual;
if dummy <>'geetha' then
raise_application_error(-20004,'NOT A PROPER USER');
else
db('a proper user ');
end if;
end;
end if;
end;

declare
dummy varchar(20);
begin
select user into dummy from dual;
if dummy <>'GEETHA' then
raise_application_error(-20002,'today no transaction');
else
db('a proper user ');
end if;
exception
when no_data_found then
db('no data found');
end;

CREATE OR REPLACE TRIGGER T2 BEFORE INSERT ON EMP FOR EACH ROW


DECLARE
27

A NUMBER;
BEGIN
SELECT COUNT(*) INTO A FROM EMP WHERE DEPTNO=:NEW.DEPTNO;
IF A>=1 THEN
RAISE_APPLICATION_ERROR(-20101,'PRIMARY KEY VIOLATION');
ELSE
DBMS_OUTPUT.PUT_LINE('VALUE INSERTED');
END IF;
END;

CREATE OR REPLACE TRIGGER DELDEPT


AFTER DELETE ON DEPT
FOR EACH ROW
BEGIN
DELETE EMP WHERE DEPTNO=:OLD.DEPTNO;
DBMS_OUTPUT.PUT_LINE('SDFSDF');
END;

CREATE OR REPLACE TRIGGER CHECK_SAL


BEFORE update ON emp
FOR EACH ROW
BEGIN
if :new.sal <1000 or :new.sal>5000 then
raise_application_error(-20001,'check sal ');
end if;
END;

EXCEPTION
---------
PRE-DEFINED :
-----------
NO_DATA_FOUND

TOO_MANY_ROWS

VALUE_ERROR A NUMBER(3) A:=1000;

INVALID_NUMBER A NUMBER A:='XXX'

CURSOR_ALREADY_OPEN

INVALID_CURSOR

ZERO_ERROR 100/0

STORAGE_ERROR

PROGRAM_ERROR

LOGIN_DENIED

DUP_VAL_INDEX VIOLATING UNIQUE

USER-DEFINED EXCEPTION
----------------------
28

---------------------------------------------------------------------
VALUE_ERROR:
-----------
DECLARE
S1 NUMBER;
BEGIN
A:=1000;
SELECT SAL INTO S1 FROM EMP WHERE EMPNO=700;
DBMS_OUTPUT.PUT_LINE(S1);
EXCEPTION
WHEN NO_DATA_FOUND THEN
DBMS_OUTPUT.PUT_LINE('NO SUCH EMPLOYEE');
WHEN VALUE_ERROR THEN
A:=100;
UPDATE EMP SET SAL=SAL+A;
END;
---------------------------------------------------------------------

USER-DEFINED EXCEPTION
----------------------

DECLARE
A1 EXCEPTION;
S1 EMP.SAL%TYPE;
BEGIN
SELECT SAL INTO S1 FROM EMP WHERE EMPNO=7900;
RAISE A1;
EXCEPTION
WHEN A1 THEN
UPDATE EMP SET SAL=S1+2000 WHERE EMPNO=7900;
END;

--------------------------------------------------------------------

DECLARE

RAD NUMBER;
AREA2 NUMBER;

BEGIN
SELECT RADIUS,AREA INTO RAD,AREA2 FROM TEST1 WHERE RADIUS IN(10,20);
DBMS_OUTPUT.PUT_LINE(RAD||AREA2);

EXCEPTION
WHEN TOO_MANY_ROWS THEN
DBMS_OUTPUT.PUT_LINE('TOO MANY ROWS');
END;
29

1.
WRITE A FUCTION TO DISPLAY THE SYSTEM TIME AND THE CORRESPONDING
PL/SQL BLOCK.
2.
(STORED FUNCTION)
WRITE A FUNCTION TO DISPLAY THE JOB WHEN THE NUMBER IS PASSED
WRITE A FUNCTION TO ACCEPT NAME AND PRINT JOB
3.
WRITE A FUCTION TO ADD 2 NUMBERS.
(STORED FUNCTION)
WRITE A FUNCTION TO CHECK WHETHER NUMBER IS EVEN OR ODD
4.
(LOCAL FUNCTION)
WRITE A FUNCTION TO GET SALARY WHEN NUMBER IS PASSED.

5.
WRITE A FUNCTION TO ILLUSTRATE IN OUT PARAMETERS.
6.
EXAMPLE FOR IN PARAMETER
7.
WRITE A FUNCTION TO ILLUSTRATE OUT PARAMETER.
WRITE A FUNCTION TO DISPLAY NAME,JOB AND SALARY WHEN NUMBER IS
PASSED

8.
IF ANNSAL>10000 TAX IS 10%
IF ANNSAL>15000 TAX IS 20%
IF ANNSAL>20000 INCOME TAX IS 30%
ELSE
INCOME TAX IS ZERO.
9.
WRITE A FUNCTION TO FIND THE FACTORIAL OF A NUMBER
10.
WRITE A BLOCK TO CALCULATE GROSS SALARY WHEN NUMBER IS PASSED.
GROSS=BASIC+HRA(30%)+DA(50%)-PF(10%)
11.
WRITE A FUNCTION TO RETURN THE AVERAGE SALARY OF THE
EMPLOYEES.IF THE
NUMBER OF EMPLOYEES ARE MORE THAN 2 THEN ONLY CALCULATE THE
AVERAGE.
30

12.
write a pl/sql block to delete a record. If delete operation
is
successful return 1 else return 0.
13.
write a pl/sql block to pass the employee number and the
increment
amount.FUNCTION SHOULD RETURN THE NET SALARY.

14.
write a pl/sql block to illustrate default as in parameter.

************************************************************************
***********

FUNCTIONS
~~~~~~~~~

1.
WRITE A FUCTION TO DISPLAY THE SYSTEM TIME AND THE CORRESPONDING
PL/SQL BLOCK.

CREATE OR REPLACE FUNCTION TIME1


RETURN VARCHAR IS
TIM VARCHAR(10);
BEGIN
SELECT TO_CHAR(SYSDATE,'HH:MI:SS') INTO TIM FROM DUAL;
RETURN TIM;
END;

DECLARE
AB VARCHAR(30);
BEGIN
AB:=TIME1;
DBMS_OUTPUT.PUT_lINE(AB);
END;

________________________________________________________________________
_

2.(STORED FUNCTION)
WRITE A FUNCTION TO DISPLAY THE JOB WHEN THE NUMBER IS PASSED

CREATE OR REPLACE FUNCTION SAL (N NUMBER)


RETURN VARCHAR IS
DESIG EMP.JOB%TYPE;
BEGIN
SELECT JOB INTO DESIG FROM EMP WHERE EMPNO=N;
RETURN DESIG;
END;

SELECT SAL(&N) FROM DUAL;

IF YOU GIVE THE VALUE FOR N IMMEDIATELY VALUE WILL BE DISPLAYED.


31

DECLARE
A VARCHAR(10);
BEGIN
A:=SAL(&EMPNO);
DBMS_OUTPUT.PUT_LINE(A);
END;

_____________________

WRITE A FUNCTION TO ACCEPT NAME AND PRINT JOB

S
CREATE OR REPLACE FUNCTION FUN(N VARCHAR2)
RETURN VARCHAR2 IS
J VARCHAR2(10);
BEGIN
SELECT JOB INTO J FROM EMP WHERE ENAME=N;
RETURN J;
END;

Declare
A varchar2(25);
B varchar2(25);
Begin
A:= fun(&b);
Dbms_output.put_line(a);
End;
________________________________________________________________________
_

3.(STORED FUNCTION)
WRITE A FUNCTION TO CHECK WHETHER NUMBER IS EVEN OR ODD

CREATE OR REPLACE FUNCTION EV_ODD(N NUMBER)


RETURN VARCHAR IS
BEGIN
IF MOD(N,2)=0 THEN
RETURN('NUMBER IS EVEN');
ELSE
RETURN('NUMBER IS ODD');
END IF;
END;

DECLARE
NO_TEST NUMBER:=&NO_TEST;
MES VARCHAR(25);
BEGIN
MES:=EV_ODD(NO_tEST);
DBMS_OUTPUT.PUT_LINE(MES);
END;

______________________

CREATE OR REPLACE FUNCTION ADD1(N1 NUMBER,N2 NUMBER)


32

RETURN NUMBER IS
RES NUMBER;
BEGIN
RES:=N1+N2;
RETURN RES;
END;

SELECT ADD1(2,3) FROM DUAL;


OR
YOU CAN ALSO HAVE A PL/SQL BLOCK TO EXECUTE THE FUNCTION.

________________________________________________________________________
_

4.(LOCAL FUNCTION)
WRITE A FUNCTION TO GET SALARY WHEN NUMBER IS PASSED.

DECLARE
A NUMBER;
FUNCTION F1(N NUMBER) RETURN NUMBER
IS
SALARY EMP.SAL%TYPE;
BEGIN
SELECT SAL INTO SALARY FROM EMP WHERE EMPNO=N;
RETURN SALARY;
END;
BEGIN
A:=F1(&N);
DBMS_OUTPUT.PUT_LINE(A);
END;

________________________________________________________________________
_

5.
WRITE A FUNCTION TO ILLUSTRATE IN OUT PARAMETERS.

create or replace function FUN(n IN OUT number) return number IS


BEGIN
N:=N+10;
RETURN N;
END;

declare
n1 number :=10;
n2 number;

begin
n2 :=fun(n1);
dbms_output.put_line(n2);
end;
33

________________________________________________________________________
_

6.
EXAMPLE FOR IN PARAMETER

CREATE OR REPLACE FUNCTION FUN1(N IN NUMBER)


RETURN NUMBER IS
SALARY NUMBER;
BEGIN
SELECT SAL INTO SALARY FROM EMP WHERE EMPNO=N;
RETURN SALARY;
END;

DECLARE
SALARY NUMBER(7,2);
BEGIN
SALARY:=FUN1(7788);
DBMS_OUTPUT.PUT_lINE(SALARY);
END;

________________________________________________________________________
_

7.
--WRITE A FUNCTION TO ILLUSTRATE OUT PARAMETER.
--WRITE A FUNCTION TO DISPLAY NAME,JOB AND SALARY WHEN NUMBER IS PASSED

CREATE OR REPLACE FUNCTION FUN5(DESIG EMP.EMPNO%TYPE,SALARY OUT


EMP.SAL%TYPE,
S OUT EMP.JOB%TYPE)
RETURN VARCHAR2 IS
NAME VARCHAR(30);
BEGIN
SELECT ENAME,JOB,SAL INTO NAME,S,SALARY FROM EMP WHERE EMPNO=DESIG;
RETURN NAME;
EXCEPTION
WHEN OTHERS THEN
RETURN ('ERROR');
END;

DECLARE
A EMP.EMPNO%TYPE:=&EMPNO;
B VARCHAR(30);
C VARCHAR(30);
D NUMBER(8,2);
BEGIN
B:=FUN5(A,D,C);
DBMS_OUTPUT.PUT_LINE(A||' '||B||' '||C||' '||d);
END;

OUTPUT OF THE QUERY IS


Enter value for empno: 7900
old 2: A EMP.EMPNO%TYPE:=&EMPNO;
34

new 2: A EMP.EMPNO%TYPE:=7900;
Commit complete.
7900 JAMES CLERK 950

________________________________________________________________________
_

8.

IF ANNSAL>10000 TAX IS 10%


IF ANNSAL>15000 TAX IS 20%
IF ANNSAL>20000 INCOME TAX IS 30%
ELSE
INCOME TAX IS ZERO.

CREATE OR REPLACE FUNCTION INCOMETAX(N NUMBER)


RETURN NUMBER IS
SC NUMBER;
ANN NUMBER;
IT NUMBER;
BEGIN
SELECT SAL+NVL(COMM,0) INTO SC FROM EMP WHERE EMPNO=N;
ANN:=SC*12;
IF ANN>10000 AND ANN<15000 THEN
IT:=ANN*0.1;
ELSIF ANN>15000 AND ANN<20000 THEN
IT:=ANN*0.2;
ELSIF ANN>20000 THEN
IT:=ANN*0.3;
ELSE
IT:=0;
END IF;
RETURN IT;
END;

DECLARE
IT NUMBER;
BEGIN
IT:=INCOMETAX(&EMPNO);
DBMS_OUTPUT.PUT_LINE('INCOME TAX OF THE EMPLOYEE IS');
DBMS_OUTPUT.PUT_LINE(IT);
END;

________________________________________________________________________
_

9.
--WRITE A FUNCTION TO FIND THE FACTORIAL OF A NUMBER

CREATE OR REPLACE FUNCTION FACT( N NUMBER) RETURN NUMBER IS


F NUMBER:=1;
BEGIN
FOR I IN 1..N LOOP
35

F:=F*I;
END LOOP;
RETURN F;
END;

DECLARE
RESULT NUMBER;
N NUMBER:=&N;
BEGIN
RESULT:= FACT(N);
DBMS_OUTPUT.PUT_LINE('FACTORIAL OF'|| N || 'IS'||RESULT);
END;

OR

SELECT FACT(4) FROM DUAL;


________________________________________________________________________
_

10.
WRITE A BLOCK TO CALCULATE GROSS SALARY WHEN NUMBER IS PASSED.
GROSS=BASIC+HRA(30%)+DA(50%)-PF(10%)

CREATE OR REPLACE FUNCTION GROSS(N NUMBER) RETURN NUMBER IS


S NUMBER;
HRA NUMBER;
DA NUMBER;
PF NUMBER;
gross NUMBER;
BEGIN
SELECT SAL INTO S FROM EMP WHERE EMPNO=N;
HRA:=S*0.3;
DA:=S*0.5;
PF:=S*0.1;
gross:=S+HRA+DA-PF;
RETURN gross;
END;

DECLARE
GROSS1 NUMBER;
ENO NUMBER:=&EMPNO;
SALARY NUMBER;
BEGIN
SELECT SAL INTO SALARY FROM EMP WHERE EMPNO=ENO;
DBMS_OUTPUT.PUT_LINE('BEFORE FUNCTION CALL SALARY IS'||' '||SALARY);
GROSS1:=GROSS(ENO);
DBMS_OUTPUT.PUT_LINE('AFTER FUNCTION CALL SALARY IS'||' '||GROSS1);
END;

OR
SQL> SELECT GROSS(7934) FROM DUAL;

GROSS(7934)
-----------
2210
36

________________________________________________________________________
_

11.
WRITE A FUNCTION TO RETURN THE AVERAGE SALARY OF THE
EMPLOYEES.IF THE
NUMBER OF EMPLOYEES ARE MORE THAN 2 THEN ONLY CALCULATE THE
AVERAGE.

CREATE OR REPLACE FUNCTION AVSAL(N NUMBER) RETURN NUMBER IS


CO1 NUMBER;
AG NUMBER;
BEGIN
SELECT COUNT(*) INTO CO1 FROM EMP WHERE DEPTNO=N;
IF N>2 THEN
SELECT AVG(SAL) INTO AG FROM EMP WHERE DEPTNO=N;
END IF;
RETURN AG;
END;

DECLARE
N NUMBER:=&DEPTNO;
ASAL NUMBER;
BEGIN
ASAL:=AVSAL(N);
DBMS_OUTPUT.PUT_lINE('AVERAGE SALARY OF DEPTNO'||' '||N||' IS
'||ASAL);
END;

________________________________________________________________________
_

12.
--write a pl/sql block to delete a record. If delete operation
--ISsuccessful return 1 else return 0.

create or replace function fun3(n emp.empno%type) return number is


a number;
begin
delete from emp where empno=n;
if sql%found then
return 1;
else
return 0;
end if;
--exception
--when no_data_found then
--return 100;
end;

declare
n number;
begin
37

n:=fun3(&empno);
dbms_output.put_Line(n);
if n=0 then
dbms_output.put_line('deletion unsuccessfull');
elsif n=1 then
dbms_output.put_line('deletion successfull');
end if;
end;

________________________________________________________________________
_

13.

write a pl/sql block to pass the employee number and the increment
amount . FUNCTION SHOULD RETURN THE NET SALARY

create or replace function raise_sal(eno number,incre number)


return number is
a number;
begin
select count(*) into a from emp where empno=eno;
if a=0 then
raise_application_error(-20300,'employee does not exist');
else
update emp set sal=sal+incre where empno=eno;
select sal into a from emp where empno=eno;
end if;
return a;
end;

declare
netsal number;
begin
netsal:=raise_sal(&empno,&salary);
dbms_output.put_line('Net salary is'||' '||netsal);
end;

________________________________________________________________________
_

14.
write a pl/sql block to illustrate default as in parameter.

create or replace function def(n number default 7369) return number


is
salary emp.sal%type;
begin
select sal into salary from emp where empno=n;
return salary;
end;
38

select def from dual;

________________________________________________________________________
_

functions : 1) single row functions


2) multiple row functions(group)(aggregate)

Single row functions


~~~~~~~~~~~~~~~~~~~~
1) ARITHMETIC
2) CHARACTER
3) GENERAL
4) DATE
5) CONVERSION
39

1 ARITHMETIC FUNCTIONS
~~~~~~~~~~~~~~~~~~~~
ABs
ceil(>n)
floor(<n)
mod
power
sign
sqrt
trunc
round
(SIN,COS,TAN,SINH,LOG,LN)

2 CHARACTER FUNCTIONS
~~~~~~~~~~~~~~~~~~~~~~~~~~~
INITCAP
LOWER
UPPER
LPAD
RPAD
SOUNDEX
LTRIM
RTRIM
SUBSTR
LENGTH
INSTR

CONCAT
3 GENERAL FUNCTIONS
~~~~~~~~~~~~~~~~~~~~~~~~~
NVL
DECODE
TRANSLATE
REPLACE
GREATEST
LEAST

4 DATE FUNCTIONS
~~~~~~~~~~~~~~~~~~~~~~~~~
SYSDATE
ADD_MONTHS
MONTHS_BETWEEN
LAST_DAY
NEXT_DAY

5 CONVERSION FUNCTIONS
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
TO_DATE
TO_CHAR
TO_NUMBER

GROUP FUNCTIONS
~~~~~~~~~~~~~~~~
40

~~~~~~~~~~~~~~~~
COUNT
SUM
MAX
MIN
AVG

SYMBOL DEFINITION
~~~~~~ ~~~~~~~~~~
D NUMBER OF DAY IN WEEK(1-7 STARTS WITH SUNDAY)
DD DAY IN NUMBERS
DDD NUMBER OF DAYS SINCE JAN1
DAY DAY FULLY SPELT OUT
DY FIRST 3 CHARACTERS OF THE DAY
MM MONTH IN NUMBERS
MONTH MONTH FULLY SPELT OUT
MON MONTH IN 3 LETTERS
WW NUMBER OF WEEKS OVER SINCE JAN 1
W NUMBER OF WEEKS OVER IN THAT MONTH
Y 1 DIGIT YEAR
YY 2 DIGIT YEAR
YYY 3 DIGIT YEAR
YYYY 4 DIGIT YEAR
YEAR YEAR FULLY SPELT OUT
HH HOUR
MI MINUTES
SS SECONDS
SSSS MILLISECONDS
HH24 24 HOUR FORMAT
HH12 12 HOUR FORMAT
FMDDTH 1ST,2ND,3RD ----(ORDINAL FORMAT)
RM ROMAN NUMERAL MONTH
FMDDSPTH SPELLED FORMAT (FIRST, SECOND, THIRD)

GROUP BY AND HAVING CLAUSE


~~~~~~~~~~~~~~~~~~~~~~~~~~~
1). NUMBER OF EMPLOYEES DEPTNOWISE
2). SUM OF SALARIES DEPTNOWISE
3). NUMBER OF EMPLOYEES JOBWISE
4). SUM,MAX,MIN AND AVG OF SAL JOBWISE
5). AVG(SAL) DEPTNOWISE WITH SAL>4000
41

query to select nth record


~~~~~~~~~~~~~~~~~~~~~~~~~~~
Query to delete nth record
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
delete from emp where rowid in
(
select rowid from emp where rownum<=&n
minus
select rowid from emp where rownum<=&n-1);
HBN

select * from emp where rowid in


(
select rowid from emp where rownum<=&n
minus
select rowid from emp where rownum<=&n-1);

display n records in between


~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

CORRECT QUERY
~~~~~~~~~~~~~~
SELECT ROWNUM,ROWID,ENAME FROM EMP WHERE ROWNUM<=&N
MINUS
SELECT ROWNUM,ROWID,ENAME FROM EMP WHERE ROWNUM<=&N

(TRIALS)
~~~~~~~~~
select rownum,rowid,empno,ename,job FROM EMP A WHERE ROWID IN
(
(SELECT ROWID FROM EMP WHERE ROWNUM <=
(SELECT COUNT(*)-&N FROM EMP)) minus
(select rowid from emp where rownum<=
(select count(*) -&n from emp))
);

(SECOND TRIAL)
~~~~~~~~~~~~~~
select rownum,rowid,empno,ename,job FROM EMP A WHERE ROWID IN
(
(SELECT ROWID FROM EMP WHERE ROWNUM <
(SELECT COUNT(*)-&N FROM EMP)) minus
(select rowid from emp where rownum<=
(select count(*) -&n from emp))
);

(THIRD TRIAL)
~~~~~~~~~~~~~~~
DELETE FROM EMP A WHERE ROWID IN
42

(
( SELECT ROWID FROM EMP WHERE ROWNUM<=&N)
MINUS
(SELECT ROWID FROM EMP WHERE ROWNUM<=&N)
);

DISPLAY ALL THE DETAILS OF EMPLOYEES WHOSE JOB IS


SAME AS THAT OF JONES.

1. Display the Details of all Employees along with their


Department Information.

select e.* ,d.dname,d.deptno,d.loc


from emp e,dept d
where e.deptno=d.deptno;

2. Display the Details of all Employees who are Getting Salary


Greater than the Salary of ADAMS

select a.ename,a.sal,b.ename,b.sal
from emp a,emp b
where a.ename='FORD' AND B.SAL>A.SAL;

SELECT ENAME,SAL,JOB
FROM EMP
WHERE SAL>(SELECT SAL FROM EMP WHERE ENAME='ADAMS');

3. Display the details of all employees who are joined before 'FORD'

SELECT A.ENAME,A.SAL,A.HIREDATE,B.ENAME,B.SAL,B.HIREDATE
FROM EMP A,EMP B
WHERE A.ENAME='FORD' AND B.HIREDATE<A.HIREDATE;

SELECT * FROM EMP WHERE HIREDATE <(SELECT HIREDATE


FROM EMP WHERE ENAME='FORD');

4. Display the details of all the employees who are joined After SMITH
2 But Before Miller.

SELECT A.ENAME,A.HIREDATE ,B.HIREDATE,C.HIREDATE


FROM EMP A,EMP B,EMP C
WHERE B.ENAME='SMITH' AND C.ENAME='MILLER' AND
A.HIREDATE> B.HIREDATE AND A.HIREDATE<C.HIREDATE;

SELECT * FROM EMP WHERE HIREDATE


>(SELECT HIREDATE FROM EMP WHERE ENAME='SMITH') AND
HIREDATE <(SELECT HIREDATE FROM EMP WHERE ENAME='MILLER');

5. Display the Details of all employees along with their managers Name
43

AND
Employee Number.

SELECT A.EMPNO,A.ENAME,A.JOB,B.JOB"REPORT",B.ENAME "REPNAME"


FROM EMP A ,EMP B
WHERE A.MGR=B.EMPNO;

6. Display the Details of all employees working in the same Department


as 'FORD'

select * from emp where deptno=(select deptno from emp


where ename='FORD');

select a.ename,a.sal,a.job,a.deptno
from emp a,emp b
where a.deptno=b.deptno and b.ename='FORD';

7. Display the details of all the employees who are Getting the Less
commision than 'FORD.'. Consider NULL commision as '0'

SQL> SELECT A.ENAME,A.COMM,B.COMM,B.ENAME


2 FROM EMP A,EMP B
3 WHERE NVL(A.COMM,0) >NVL(B.COMM,0) AND B.ENAME='FORD';

ENAME COMM COMM ENAME


---------- --------- --------- ----------
ALLEN 300 FORD
WARD 500 FORD
MARTIN 1400 FORD

SELECT a.ename oriname,a.comm oricomm,


b.ename,b.comm from emp a,emp b
WHERE A.COMM < B.COMM AND B.ENAME='MARTIN';

SELECT a.ename oriname,a.comm oricomm,


b.ename,b.comm from emp a,emp b
where NVL(a.comm,0)<NVL(b.comm,0) and b.ename='MARTIN';

8. Display the details of all the employees for whom the Ford is
the Manager.

SELECT A.ENAME ACTUALNAME,A.SAL,A.JOB,B.ENAME REPORTSTO ,B.SAL,


B.JOB
FROM EMP A,EMP B WHERE B.ENAME='FORD' AND A.MGR=B.EMPNO;

9. Display the Details of all the employees who are joined in the
same month of FORD

SELECT A.ENAME,A.HIREDATE,B.ENAME,B.HIREDATE
FROM EMP A,EMP B
WHERE B.ENAME='FORD' AND TO_CHAR(A.HIREDATE,'MONTH')=
TO_CHAR(B.HIREDATE,'MONTH');
44

10. Display the details of all the employees who are in the
SALES Department

SELECT * FROM EMP WHERE DEPTNO=(SELECT DEPTNO


FROM DEPT WHERE DNAME='SALES');

SELECT A.ENAME,A.DEPTNO,A.JOB,B.DEPTNO,B.DNAME
FROM EMP A,DEPT B WHERE B.DNAME='SALES' AND
A.DEPTNO=B.DEPTNO;

11. Display the details of all the employees who are not ANALYSTS
and Getting Salary Greeater than 'CLARK';

SELECT A.ENAME,A.JOB,A.SAL,B.ENAME,B.SAL,B.JOB
FROM EMP A,EMP B
WHERE A.JOB!='ANALYST' AND A.SAL >B.SAL AND
B.ENAME='CLARK';

SELECT * FROM EMP WHERE JOB NOT IN 'ANALYST' AND


SAL > (SELECT SAL FROM EMP WHERE ENAME='CLARK');

12. Display All the employee Names along with their Manager.

SELECT A.EMPNO,A.ENAME,A.JOB,B.ENAME MANAGER,B.JOB REPORTING


FROM EMP A,EMP B
WHERE A.MGR=B.EMPNO;

13. Display the Names of all the employees who are all getting the
salary Greater than the salary of 'SMITH'

SELECT * FROM EMP WHERE SAL >(SELECT SAL FROM EMP


WHERE ENAME='SMITH');

SELECT A.ENAME,A.JOB,A.SAL,B.ENAME,B.SAL
FROM EMP A,EMP B
WHERE B.ENAME='SMITH' AND A.SAL > B.SAL;

14. Display the Names of all the employees who are all getting the
salary Greater than the salary of 'SMITH' along with the
difference in salary

SELECT A.ENAME,A.JOB,A.SAL,B.ENAME,B.SAL,A.SAL-B.SAL
FROM EMP A,EMP B
WHERE B.ENAME='SMITH' AND A.SAL>B.SAL ;

15. Display the details of all the employees whose sal is greater
than the average salary of the employees in their
respective deparments.
45

SELECT * FROM EMP A


WHERE SAL > ( SELECT AVG(SAL) FROM EMP B
WHERE A.DEPTNO=B.DEPTNO );

16. WRITE A QUERY TO PRINT THE MULTIPLICATION TABLE

SELECT &R || '*'||' ' ||LPAD(ROWNUM,4,' ')||' = '|| &R * ROWNUM


FROM EMP WHERE ROWNUM <= 10;

17. LIST FOLLOWING DETAILS FOR EMPLOYEES WHO EARN 36000/- A YEAR
OR ARE CLERKS

SELECT A.ENAME,A.JOB,A.SAL*12,B.DNAME
FROM EMP A,DEPT B
WHERE A.DEPTNO=B.DEPTNO AND A.SAL*12>30000
OR A.DEPTNO=B.DEPTNO AND A.JOB='CLERK';

18.

select ename,sal,
decode(sal,least(sal,1000),'<1000',
greatest(least(sal,2000)),'>1000 and <2000',
greatest(least(sal,3000)),'>2000 and <3000') from emp;

ENAME SAL DECODE(SAL,LEAS


---------- --------- ---------------
SMITH 800 <1000
ALLEN 1600 >1000 and <2000
WARD 1250 >1000 and <2000
JONES 2975 >2000 and <3000
MARTIN 1250 >1000 and <2000
BLAKE 2850 >2000 and <3000
CLARK 2450 >2000 and <3000
SCOTT 3000 >2000 and <3000
KING 5000
TURNER 1500 >1000 and <2000
ADAMS 1100 >1000 and <2000
JAMES 950 <1000
FORD 3000 >2000 and <3000
MILLER 1300 >1000 and <2000

/*SILLY*/

select sal,count(*) aa,


decode(sal,least(sal,1000),'<1000',
greatest(least(sal,2000)),'>1000 and <2000',
greatest(least(sal,3000)),'>2000 and <3000') from emp group by
decode(sal,least(sal,1000),'<1000',
greatest(least(sal,2000)),'>1000 and <2000',
greatest(least(sal,3000)),'>2000 and <3000'),sal;

OR
SELECT SAL,DECODE(FLOOR(SAL/1000),0,'<1000',1,'> 1000 AND < 2000',
3,'>2000 AND < 3000','> 3000') FROM EMP;

OR
46

(SANJAYA)
SELECT SAL,DECODE(GREATEST(SAL,1000),1000,'< 1000',
LEAST(SAL,2000), ' > 1000 AND < 2000',
LEAST(SAL,3000), '> 2000 AND < 3000',
LEAST(SAL,4000),' = 3000',' > 3000 ') FROM EMP;

19. display the details of all the employees whose salary is equal to
range as specified in grade 5.

select sal from emp where sal >


(select losal from salgrade where grade=5) and
sal< (select hisal from salgrade where grade=5);

20. CREATE A SEQUENCE AND GENERATE SOME NUMBERS .INSERT THESE NUMBERS
INTO THE TABLE BY CONCATENATING IT WITH E.

create sequence s1
start with 1
increment by 1
maxvalue 10

insert into EM3(A) values


(concat('e',s12.nextval));

21.

select lpad(' ',level-1)||ename from emp


START WITH job = 'PRESIDENT'
CONNECT BY PRIOR EMPNO = MGR;

_______________________________________________________________________

END OF REPORT

_______________________________________________________________________

select a.sal,a.ename,a.deptno
from emp a
group by a.deptno having a.sal>all(select avg(sal) from emp b
from emp b
group by deptno);

select distinct a.sal, a.ename, a.deptno


from emp a,emp b
where a.deptno=b.deptno and
a.sal >all(select avg(sal) from emp b group by deptno);

-------------------------------------------------------------------

declare
47

a number:=&a;
b number:=&b;
c number;
begin
c:=a*b;
b:=a+b;
a:=mod(c,b);
dbms_output.put_line(' '||a);
dbms_output.put_line(' '||b);
dbms_output.put_line(' '||c);
end;

declare
a number:=&a;
n number;
begin
for i in 1..10 loop
n:=a*i;
dbms_output.put_line(a||'*'||i||'='||n);
end loop;
end;

declare
a number:=&a;
b number;
c number:=2;
begin
for i in 1..10 loop
if a:=1 then
b:=c+2;
else
b:=2+i;
dbms_output.put_line(b);
end if;
end loop;
end;

declare
begin
for i in 1..3 loop
dbms_output.put_line('?');
dbms_output.new_line;
dbms_output.put(?);
end loop;
end;
48

declare
a number(10);
begin
a:=1;
dbms_output.put_line(a);
a:=12;
dbms_output.put_line(a);
a:=123;
dbms_output.put_line(a);
a:=1234;
dbms_output.put_line(a);
a:=12345;
dbms_output.put_line(a);
a:=123456;
dbms_output.put_line(a);
a:=1234567;
dbms_output.put_line(a);
a:=12345678;
dbms_output.put_line(a);
a:=123456789;
dbms_output.put_line(a);
a:=1234567890;
dbms_output.put_line(a);
end;

declare
e1 number;
e2 number;
e3 number;
val number;
begin
val:=&e3;
select deptno into e2 from emp where empno=val;
if e2=10 then update emp set comm=1000 where empno=val;
elsif e2 = 20 then update emp set comm=2000 where empno=val;
elsif e3=30 then update emp set comm=3000 where empno=val;
end if;
end;

declare
type type1 is record(eno number(4) not null:=7788,ena emp.ename%type);
erec type1;
begin
select empno,ename into erec from emp where empno=7788;
dbms_output.put_line(erec.eno||erec.ena);
end;

declare
salary emp.sal%type;
mgr_num emp.mgr%type;
emno emp.empno%type;
enam emp.ename%type;
begin
select ename,empno,sal, mgr into enam,emno,salary,
mgr_num from emp where empno=7788;
while salary<4000
49

loop
update emp set sal=1000 where empno=mgr_num;
end loop;
insert into emp1 values(null,salary,enam);
commit;
end;

declare
no number;
name varchar2(20);
salary number(7,2);
begin
select ename,sal into name,salary from emp where empno=&no;
insert into emp1 values(name,salary);
end;

declare
str varchar2(20);
rev varchar2(20);
begin
str:='&input';
if length(str)=0 then
dbms_output.put_line('null');
else
for i in 1..length(str)
loop
rev:=substr(str,i,1);
end loop;
end if;
dbms_output.put_line('rev string' ||rev);
end;

declare
a number;
b number:=1;
begin
a:=&no;
for i in 1..a
loop
b:=b*i;
end loop;
dbms_output.put_line(b);
end;

ORACLE WORKSHEET QUESTIONS

I. QUESTIONS BASED ON DATA DEFINITION LANGUAGE COMMANDS :

1: CREATE A TABLE EMP AND DEPT USING THE FOLLOWING INFORMATION:-

a. DEPT :
50

COLUMN NAME DATATYPE(SIZE)


------------------------------- -------- -------------
DEPTNO NUMBER(2)
DNAME VARCHAR2(14)
LOC VARCHAR2(13)
--------------------------------------------------------
b.EMP:

COLUMN NAME DATATYPE(SIZE)


------------------------------- -------- ------------
EMPNO NUMBER(4)
ENAME VARCHAR2(10)
JOB VARCHAR2(9)
MGR NUMBER(4)
HIREDATE DATE
SAL NUMBER(7,2)
COMM NUMBER(7,2)
DEPTNO NUMBER(2)

2: CHECK THE DEFAULT SIZE OF A NUMBER,CHAR AND DATE DATATYPES

3: DESCRIBE THE STRUCTURE OF THE DEPT TABLE AND EMP TABLE

4: ADD TWO COLUMNS TO THE TABLE EMP WITH THE FOLLOWING


INFORMATION IN ONE SINGLE ALTER COMMAND :-
COLUMN NAME DATATYPE(SIZE)
--------------------------------------------------------------
SEX CHAR(1)
PLACE CHAR(15)

5: MODIFY THE COLUMN JOB PRESENT IN THE EMP TABLE


WITH THE FOLLOWING INFORMATION GIVEN BELOW :-
COLUMN NAME DATATYPE(SIZE)
-------------------------------------------------------
JOB VARCHAR2(15)

6: MODIFY THE COLUMN ENAME PRESENT IN THE EMP TABLE


WITH THE FOLLOWING INFORMATION GIVEN BELOW :-
COLUMN NAME DATATYPE(SIZE)
------------------------------------------------------
ENAME CHAR(15)

7: DECREASE THE SIZE FOR THE COLUMN EMPNO WITH THE FOLLOWING
INFORMATION :-
COLUMN NAME DATATYPE(SIZE)
--------------------------------------------------------
EMPNO NUMBER(2)

8: MODIFY THE COLUMN NAME OF EMPNO TO EMPLOYEE_NUMBER PRESENT


IN THE EMP TABLE VERIFY THE RESULT

9: ADD A NEW COLUMN NATIONALITY PLACED BETWEEN JOB AND MGR


COLUMNS
AND VERIFY THE RESULT

10: DROP THE TABLE DEPT AND EMP


51

11: WHAT IS THE DATA TYPE OF THE COLUMN HIREDATE AND HOW MANY BYTES
IT OCCUPIES

QUESTIONS BASED ON CONSTRAINTS :

12: CREATE A TABLE EMP AND DEPT USING THE FOLLOWING INFORMATIOM

a. DEPT :

COLUMN NAME DATATYPE(SIZE)


------------------------------- -------- -------------
DEPTNO NUMBER(2)CONSTRAINT PK_DEPTNO
PRIMARY
KEY,
DNAME VARCHAR2(14)
LOC VARCHAR2(13)

EMP :

COLUMN NAME DATATYPE(SIZE)


------------------------------- -------- ------------
EMPNO NUMBER(4)CONSTRAINT PK_EMPNO
PRIMARY
KEY,
ENAME VARCHAR2(10)CONSTRAINT UQ_ENAME
UNIQUE,
JOB VARCHAR2(9),
MGR NUMBER(4),
HIREDATE DATE DEFAULT SYSDATE,
SAL NUMBER(7,2)CONSTRAINT CK_SAL
CHECK(SAL>0) NN_SAL NOT NULL,
COMM NUMBER(7,2),
DEPTNO NUMBER(2)CONSTRAINT FK_DEPTNO
REFERENCES DEPT(DEPTNO)

13: SELECT ALL THE CONSTRAINTS IN EMP TABLE

SOL: SELECT * FROM USER_CONSTRAINTS WHERE TABLE_NAME='EMP';

14: SELECT THE OWNER,CONSTRAINT NAME,CONSTRAINT TYPE,TABLE


NAME,STATUS
FOR DEPT TABLE

SOL: SELECT OWNER,CONSTRAINT_NAME,CONSTRAINT_TYPE,TABLE_NAME,STATUS


FROM USER_CONSTRAINTS WHERE TABLE_NAME='DEPT';

15: DROP THE CONSTRAINT UQ_ENAME FROM EMP TABLE

SOL: ALTER TABLE EMP DROP CONSTRAINT UQ_ENAME;

16: ADD A NEW COLUMN PINCODE WITH NOT NULL CONSTRAINT


TO THE EXISTING TABLE DEPT

SOL: ALTER TABLE DEPT ADD(PINCODE NUMBER(6) NOT NULL);

17: DISABLE THE CONSTRAINT PK_DEPTNO PRESENT IN DEPT TABLE


52

SOL: ALTER TABLE DEPT DISABLE CONSTRAINT PK_DEPTNO;

18: ENABLE THE CONSTRAINT PK_DEPTNO WHICH IS DEFINED IN THE


DEPTNO COLUMN OF DEPT TABLE

SOL: ALTER TABLE DEPT ENABLE CONSTRAINT PK_DEPTNO;

II. QUESTIONS BASED ON DATA MANIPULATION LANGUAGE COMMANDS :-

PROBLEMS BASED ON INSERT COMMAND:-

19: INSERT THE GIVEN VALUES INTO THE TABLES:

EMP:
(i)7369,SMITH,CLERK,7902,17-DEC-80,800,NULL,20
(ii)7499,ALLEN,SALESMAN,7698,20-FEB-81,1600,300,30
(iii)7521,WARD,SALESMAN,7698,22-FEB-81,1250,500,30
(iv)7566,JONES,MANAGER,7839,02-APR-81,2975,NULL,20
(v)7654,MARTIN,SALESMAN,7698,28-SEP-81,1250,1400,30
(vi)7698,BLAKE,MANAGER,7839,01-MAY-81,2850,NULL,30
(vii)7782,CLARK,MANAGER,7839,09-JUN-81,2450,NULL,10
(viii)7788,SCOTT,ANALYST,7566,19-NOV-96,3000,NULL,20
(ix)7839,KING,PRESIDENT,NULL,17-NOV-81,5000,NULL,10
(x)7844,TURNER,SALESMAN,7698,08-SEP-81,1500,0,30
(xi)7876,ADAMS,CLERK,7788,23-DEC-96,1100,NULL,20
(xii)7900,JAMES,CLERK,7698,03-DEC-81,950,NULL,30
(xiii)7902,FORD,ANALYST,7566,03-DEC-81,3000,NULL,20
(xiv)7934,MILLER,CLERK,7782,23-JAN-82,1300,NULL,10
(xv)7943,JOHN,CLERK,7943,10-DEC-83,2000,NULL,50

DEPT:

(i)10,ACCOUNTING,NEW YORK
(ii)20,RESEARCH,DALLAS
(iii)30,SALES,CHICAGO
(iv)40,OPERATIONS,BOSTON
(v)50,COMPUTER,AMERICA
20: INSERT ONLY THE RECORDS OF EMPLOYEE NUMBER,NAME,SALARY
INTO EMP TABLE

SOL: INSERT INTO EMP(EMPNO,ENAME,SAL) VALUES('7955','PAUL',1200);

21: INSERT TWO ROWS INTO EMP TABLE USING PARAMETER SUBSTITUTION

SOL: INSERT INTO EMP VALUES(&EMPNO,'&ENAME','&JOB',&MGR,'&HIREDATE',


&SAL,&COMM,&DEPTNO);

22: INSERT THE CURRENT TRANSACTION DATE TEMPORARY TABLE

SOL: INSERT INTO TEMP VALUES(SYSDATE);

PROBLEMS ON SELECT COMMAND:-

23: LIST THE INFORMATION OF ALL EMPLOYEES


53

SOL: SELECT * FROM EMP;

24: LIST THE INFORMATION OF ALL THE DEPARTMENTS

SOL: SELECT * FROM DEPT;

25: LIST THE DEPARTMENT NUMBERS,EMPLOYEE NUMBERS AND THEIR MANAGERS


NUMBERS

SOL: SELECT DEPT.DEPTNO,EMP.EMPNO,EMP.MGR FROM EMP,DEPT;

26: LIST DEPARTMENT NAME AND LOCATIONS FROM DEPT TABLE

SOL: SELECT DNAME,LOC FROM DEPT;

27: LIST THE INFORMATION OF EMPLOYEES AND THEIR DEPARTMENTS


IN A SINGLE DML COMMAND

SOL: SELECT * FROM EMP;

28: COPY ALL THE RECORDS OF THREE COLUMNS EMPNO,ENAME,JOB FROM EMP
TABLE AND INSERT THE RECORDS INTO A TEMP TABLE WITH COLUMN
NAMES
SAME AS EMPNO,ENAME,JOB

SOL: INSERT INTO TEMP(EMPNO,ENAME,JOB)


SELECT EMPNO,ENAME,JOB

29: LIST THE DETAILS OF BOTH THE TABLES

SOL: SELECT * FROM EMP,DEPT;

30: LIST THE INFORMATION OF ALL THE EMPLOYEES PRESENT IN THE USER
NAMED SCOTT

SOL: SELECT * FROM SCOTT.EMP;

31: LIST THE INFORMATION OF ALL THE DEPARTMENTS FROM YOUR BATCHMATES
DEPT TABLE

SOL: SELECT * FROM ORA252P.DEPT;

32: LIST OUT ALL THE TABLE NAMES IN YOUR SCHEMA

SOL: SELECT * FROM TAB;

33: LIST ALL THE SYSTEM TABLES

SOL: SELECT * FROM SYS.DICTIONARY;

34: GET THE INFORMATION OF THE MAXIMUM AVAILABLE BLOCKS ALLOTED TO A


PARTICULAR USER FOR CREATING TABLES FROM THE SYSTEM TABLES

SOL: SELECT * FROM USER_TS_QUOTAS;

35: LIST OUT ALL THE PRIVILAGES GIVEN TO A PARTICULAR USER


54

36: LIST OUT ALL THE TABLES WHICH START WITH 'S'

SOL: SELECT TABLE_NAME FROM USER_TABLES WHERE TABLE_NAME LIKE 'S%';

37: COPY THE STRUCTURE OF DEPT TABLE ALONE TO A TEMPORARY TABLE


CALLED TEMP1

SOL: CREATE TABLE TEMP1 AS SELECT * FROM DEPT WHERE 1=2;

PROBLEMS ON UPDATE COMMAND:-

38: UPDATE THE SALARY BY 10% HIKE TO ANALYSTS WORKING IN DEPARTMENT


NUMBER 20 AND 30

SOL: UPDATE EMP SET SAL=SAL+(SAL*0.1) WHERE DEPTNO IN (10,20)


AND JOB='ANALYST';
39: GIVE 5% RAISE IN SALARY TO ALL THE SALESMAN

SOL: UPDATE EMP SET SAL=SAL+(SAL*0.5) WHERE JOB='SALESMAN';

40: PROMOTE ALL THE EMPLOYEES DESCRIBED AS SALESMAN TO SALES OFFICER


IF THEIR GROSS SALARY PER MONTH IS GREATER THAN 3000

SOL: UPDATE EMP SET JOB='SALES OFFICER' WHERE JOB='SALESMAN'


AND SAL>3000;

41: GIVE ALL THE EMPLOYEES A COMMISSION OF RS.500

SOL: UPDATE EMP SET COMM=500;

42: CHANGE THE DEPARTMENT OF JAMES TO 20

SOL: UPDATE EMP SET DEPTNO=20 WHERE ENAME='JAMES';

43. CALCULATE ALL THE EMPLOYEES TOTAL SALARY WITH COMMISION

SOL: SELECT SAL+NVL(COMM) "TOTAL" FROM EMP;

PROBLEMS ON DELETE COMMAND:-


44: DELETE ALL THE RECORDS OF EMPLOYEES

SOL: DELETE FROM EMP;

45: GET BACK THE ORIGINAL RECORDS OF EMPLOYEES BACK

SOL: ROLLBACK;

46: DELETE ALLEN'S RECORD ONLY

SOL: DELETE FROM EMP WHERE ENAME='ALLEN';

47: DELETE RECORDS OF ENAME COLUMN ONLY AND VERIFY IT

SOL: NOT POSSIBLE

48: DELETE THE RECORDS OF EMPLOYEE NUMBER 7782


55

SOL: DELETE FROM EMP WHERE EMPNO=7782;

49: DELETE THE EMPLOYEE'S RECORDS WHO DOES'NT HAVE COMMISION

SOL: DELETE FROM EMP WHERE COMM IS NULL;

50: GET BACK THE ORIGINAL RECORDS

SOL: ROLLBACK;

51: DELETE THE DUPLICATE RECORDS OF THE EMPLOYEE TABLE

SOl: DELETE FROM EMP A


WHERE ROWID<>(SELECT MIN(ROWID) FROM EMP B
WHERE A.EMPNO=B.EMPNO);

52: DELETE THE FIRST FIVE RECORDS OF EMPLOYEE TABLE

SOL: DELETE FROM EMP X


WHERE 5>(SELECT COUNT(ROWID) FROM EMP Y WHERE Y.ROWID<X.ROWID);

( OR )

DELETE FROM EMP WHERE ROWNUM <6;

53: DELETE THE ROWS OF THE TEMP TABLE PERMANENTLY

SOL: TRUNCATE TABLE TEMP;

III. PROBLEMS ON TRANSACTIONAL COMMANDS :-

54: UPDATE A RECORD OF EMP TABLE AND SAVE THE CHANGES PERMANENTLY
IN THE DATABASE

SOL: UPDATE EMP SET SAL=SAL+100 WHERE EMPNO=100;


COMMIT;
55: SQL*PLUS HAS THE FACILITY TO AUTOMATICALLY SAVE ALL THE
RECORDS, WITHOUT ISSUING THE TCL COMMAND WHICH IS THAT

SOL: SET AUTOCOMMIT ON

56: GIVE ALL THE PRIVILAGES YOU HAVE OF A DATABASE OBJECT TO


ANOTHER
USER

SOL: GRANT ALL ON EMP TO ORA253A;

57: GIVE ONLY SELECT,INSERT PRIVILAGES TO ANOTHER USER

SOL: GRANT SELECT,INSERT ON EMP TO ORA267A;

58: LIST THE USER'S ID AND WHICH DATABASE OBJECT YOU HAVE GRANTED

SOL: SELECT * FROM USER_TAB_PRIVS;

59: GET BACK THE PRIVILAGES BACK FROM THE USER


56

SOL: REVOKE ALL ON EMP FROM ORA267A;

IV. PROBLEMS BASED ON OPERATORS :-

PROBLEMS BASED ON ARITHMETIC,RELATIONAL,LOGICAL AND


CHARACTER OPERATORS:-

60: LIST ALL THE EMPLOYEES SALARY WITH COMMISSION PROVIDE A NEW
HEADING AS TOTAL SALARY

SOL: SELECT SAL+NVL(COMM,0) "TOTAL SALARY" FROM EMP ;

61: GIVE THE SALARY WITH A REDUCTION OF 10% FROM THEIR SALARY TO
PERSONS WHOSE JOB IS CLERK AND AND BELONGING TO DEPARTMENT
NUMBER
30

SOL: UPDATE EMP SET SAL=SAL-(0.1*SAL) WHERE JOB='CLERK' AND


DEPTNO=30;

62: LIST THE EMPLOYEES BELONGING TO DEPARTMENT 20

SOL: SELECT * FROM EMP WHERE DEPTNO=20;

63: LIST THE NAME AND SALARY OF THE EMPLOYEES WHOSE SALARY IS
LESS THAN 3000

SOL: SELECT ENAME,SAL FROM EMP WHERE SAL<3000;

64: LIST THE NAME AND SALARY OF THE EMPLOYEES WHOSE SALARY IS
GREATER THAN 3000

SOL: SELECT ENAME,SAL FROM EMP WHERE SAL>3000;

65: LIST THE EMPLOYEE NUMBER AND NAME OF MANAGERS

SOL: SELECT EMPNO,ENAME FROM EMP WHERE JOB='MANAGER';

66: LIST THE EMPLOYEES WHOSE SALARY IS NOT EQUAL TO 3000

SOL: SELECT * FROM EMP WHERE SAL!=3000;

67: LIST THE EMPLOYEE NAME AND SALARY WHOSE SALARY IS BETWEEN
2000 AND 3000

SOL: SELECT ENAME,SAL FROM EMP WHERE SAL>=2000 AND SAL<=3000;

68: LIST ALL THE EMPLOYEES WHO HAVE JOINED BEFORE 30TH SEPTEMBER
1981

SOL: SELECT * FROM EMP WHERE HIREDATE<='30-SEP-81';

69: LIST THE NAMES OF EMPLOYEES WHO ARE NOT MANAGERS

SOL: SELECT ENAME FROM EMP WHERE JOB<>'MANAGER';


57

70: LIST ALL THE EMPLOYEES BELONGING TO THE DEPARTMENT 10,30

SOL: SELECT * FROM EMP WHERE DEPTNO IN(10,30);

71: LIST ALL EMPLOYEES NOT BELONGING TO MANAGER,PRESIDENT

SOL: SELECT * FROM EMP WHERE JOB NOT IN ('MANAGER','PRESIDENT');

72: LIST EMPLOYEES NAME AND JOB WHOSE SALARY IS BETWEEN 2000 AND
3000

SOL: SELECT ENAME,JOB FROM EMP WHERE SAL BETWEEN 2000 AND 3000;

73: LIST THE EMPLOYEE NAMES AND THEIR DESIGNATION WHO HAVE JOINED
BEFORE 30TH JUNE '81 AND AFTER DECEMBER '81
SOL: SELECT ENAME FROM EMP WHERE HIREDATE NOT BETWEEN '30-JUN-81' AND
'31-DEC-81';
74: LIST THE EMPLOYEE NAMES WHO ARE NOT ELIGIBLE FOR COMMISSION

SOL: SELECT ENAME FROM EMP WHERE COMM IS NULL;

75: LIST THE EMPLOYEE NAMES WHO ARE ELIGIBLE FOR COMMISSION

SOL: SELECT ENAME FROM EMP WHERE COMM IS NOT NULL;

76: LIST ALL THE EMPLOYEE NAMES BETWEEN THE LETTER 'M' AND 'O'

SOL: SELECT * FROM EMP WHERE ENAME BETWEEN 'M' AND 'O';

77: LIST THE NAME OF THE EMPLOYEE AND JOB OF THE EMPLOYEE , WHO DOES
NOT BELONGS TO ANY BODY

SOL: SELECT ENAME,JOB FROM EMP WHERE MGR IS NULL;

78: LIST THE EMPLOYEES WHOSE NAMES START WITH AN "S"

SOL: SELECT ENAME FROM EMP WHERE ENAME LIKE 'S%';

79: LIST THE EMPLOYEE NAMES ENDING WITH "S"

SOL: SELECT ENAME FROM EMP WHERE ENAME LIKE '%S';

80: LIST THE EMPLOYEES WHOSE NAMES HAVE EXACTLY 5 CHARACTERS

SOL: SELECT ENAME FROM EMP WHERE ENAME LIKE '_ _ _ _ _';

81: LIST THE EMPLOYEE NAMES HAVING 'I' AS THE SECOND CHARACTER

SOL: SELECT ENAME FROM EMP WHERE ENAME LIKE '_I%';

82: LIST THE DIFFERENT JOBS AVAILABLE IN THE EMP TABLE

SOL: SELECT DISTINCT JOB FROM EMP;

83: LIST THE DISTINCT JOB FROM EMP IN DEPARTMENT 30


58

SOL: SELECT DISTINCT JOB FROM EMP WHERE DEPTNO=30;

84: LIST THE EMPLOYEE NAME,SALARY, WHOSE SALARY IS BETWEEN 2000 AND
3000

SOL: SELECT ENAME,SAL FROM EMP WHERE SAL>=2000 AND SAL<=3000;

85: LIST THE NAMES OF ANALYSTS AND SALESMAN

SOL: SELECT ENAME FROM EMP WHERE JOB='SALESMAN' OR JOB='ANALYST';

86: LIST THE EMPLOYEE NAMES WHOSE JOB IS CLERK AND DEPTARTMENT IS 30

SOL: SELECT ENAME FROM EMP WHERE JOB='CLERK' AND DEPARTMENT=30;

87: DISPLAY ALL THE EMPLOYEE NAMES IN THE FORMAT AS "NAME IS ALLEN"

SOL: SELECT 'NAME IS '||ENAME FROM EMP;

88: DISPLAY THE ABSOLUTE VALUE OF -25

SOL: SELECT ABS(-25) "ABSOLUTE" FROM DUAL;

89: DISPLAY THE SMALLEST INTEGER GREATER THAN OR EQUAL TO 16.7

SOL: SELECT CEIL(16.7) "CEILING" FROM DUAL;

90: DISPLAY THE GREATEST INTEGER LESSER THAN OR EQUAL TO 15.34

SOL: SELECT FLOOR(15.34) "FLOOR" FROM DUAL;

91: DISPLAY THE COSINE OF THE ANGLE IN DEGREES

SOL: SELECT COS(180*3.14159265359/180)"COSINE OF 180 DEGREES" FROM


DUAL;

92: DISPLAY THE HYPERBOLIC COSINE OF 0

SOL: SELECT COSH(0) "HYPERBOLIC COSINE OF 0 " FROM DUAL;

93: DISPLAY THE EXPONENTIAL POWER OF THE VALUE 7

SOL: SELECT EXP(7) "e TO THE 7TH POWER " FROM DUAL;

94: DISPLAY THE NATURAL LOGARITHM OF 75

SOL: SELECT LN(75) "NATURAL LOG OF 75" FROM DUAL;

95: DISPLAY THE LOGARITHM, BASE 10, OF 100

SOL: SELECT LOG(10,100) "LOG BASE 10 OF 100" FROM DUAL;

96: DISPLAY REMAINDER ZERO WHEN A NUMBER IS DIVIDED BY AN EVEN


NUMBER

SOL: SELECT MOD(10,2) "MODULUS" FROM DUAL;


59

97: CHECK THE O/P WHEN A VALUE M>N IN A MOD FUNCTION AND NOTE DOWN
THE REASON FOR THAT KIND OF O/P

SOL: SELECT MOD(2,10) "MODULUS" FROM DUAL;

98: DISPLAY THE VALUE WHEN 9 RAISED TO 2

SOL: SELECT POWER(9,2) "RAISED AS " FROM DUAL;

99: DISPLAY THE VALUE FOR 15.193 ROUNDED TO FIRST DECIMAL PLACE
FORWARD

SOL: SELECT ROUND(15.193,1) "ROUND" FROM DUAL;

100: DISPLAY THE VALUE FOR 15.193 ROUNDED TO FIRST DECIMAL PLACE
BACKWARDS

SOL: SELECT ROUND(15.193,-1) "ROUND" FROM DUAL;

101: DISPLAY THE SIGN OF -15

SOL: SELECT SIGN(-15) FROM DUAL;

102: DISPLAY THE SINE OF ANGLE 30 DEGREES

SOL: SELECT SIN(30*3.14159265359/180) "SINE OF 30 DEGREES" FROM DUAL;

103: DISPLAY THE HYPERBOLIC SINE OF 1

SOL: SELECT SINH(1) "HYPERBOLIC SINE OF 1 " FROM DUAL;

104: DISPLAY THE SQUARE ROOT OF THE VALUE 25

SOL: SELECT SQRT(25) "SQUARE ROOT " FROM DUAL;

105: DISPLAY THE TANGENT OF THE VALUE 135 IN DEGREES

SOL: SELECT TAN(135*3.14159265359/180)"TANGENT OF 135 DEGREES" FROM


DUAL;

106: TRUNCATE THE VALUE 15.79 TO FIRST DECIMAL PLACES

SOL: SELECT TRUNC(15.79,1)" TRUNCATE " FROM DUAL;

107: TRUNCATE THE VALUE 15.79 TO FIRST DECIMAL PLACE N DIGITS


LEFT TO THE DECIMAL POINT

SOL: SELECT TRUNC(15.79,-1)"TRUNCATE" FROM DUAL;

108: DISPLAY THE CHARACTER VALUE FOR THE NUMBER 75

SOL: SELECT CHR(75) "CHARACTER " FROM DUAL;

109: DISPLAY THE ENAME AND JOB OF EMPNO=7900 IN THE FORMAT


eg:- ALLEN IS A SALESMAN

SQL: SELECT ENAME || ' IS A ' || JOB FROM EMP;


60

110: CAPITALISE THE FIRST LETTER OF "the soap "

SQL: SELECT INITCAP(' brainware infotech(p) ltd') from dual;

111: DISPLAY THE WORDS IN LOWER CASE LETTERS

SQL: SELECT LOWER('BRAINWARE INFOTECH(P) LTD') FROM DUAL;

112: DISPLAY THE LEFT PADDED CHAR'S TO THE STRING BRAINWARE WHEN
THE RETURN VALUE IS 15 AND PADDED CHARACTER IS '*'

SQL: SELECT LPAD('BRAINWARE',15,'*') FROM DUAL;

113: DISPLAY THE RIGHT PADDED CHAR'S TO THE STRING BRAINWARE WHEN
THE RETURN VALUE IS 15 AND PADDED CHARACTER IS '*'

SQL: SELECT RPAD('BRAINWARE',15,'*') FROM DUAL;

114: REMOVE CHARAECTER 'RE' TOWARDS RIGHT OF THE STRING


FROM THE LETTER 'BRAINWARE'

SQL: SELECT RTRIM('BRAINWARE','RE') FROM DUAL;

115: REMOVE CHARAECTER 'IN' TOWARDS LEFT OF THE STRING


FROM THE LETTER 'BRAINWARE'

SOL: SELECT LTRIM('INFOTECH','IN') FROM DUAL;

116: REPLACE THE CHARACTER 'J' WITH 'BL' FROM THE WORD
JACK AND JUE

SOL: SELECT REPLACE('JACK AND JUE','J','BL') FROM DUAL;

117: DISPLAY THE ENAME WITH THE PHONETIC REPRESENTATION OF


'SMYTHE' FROM TABLE EMP

SOL: SELECT ENAME FROM EMP WHERE SOUNDEX(ENAME)=SOUNDEX('SMYTHE');

118: DISPLAY THE FIRST THREE LETTERS OF THE EMPLOYEE NAMES

SOL: SELECT SUBSTR(ENAME,1,3) FROM emp;

119: DISPLAY THE CHARACTERS 'AR' FROM THE WORD 'BRAINWARE'

SOL: SELECT SUBSTR('BRAINWARE',-3,2) FROM DUAL;

120: CONVERT ALL THE CHARACTERS WHICH IS 'ABC..Z' TO LETTER 'T'


AND ALL DIGITS '012..9' TO DIGIT '9' FROM THE GIVEN CHARACTER
'0123KASL'

SOL: SELECT
TRANSLATE('0123KASL','0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ',
'9999999999TTTTTTTTTTTTTTTTTTTTTTTTTT') from dual;

121: DISPLAY THE ASCII VALUE OF THE CHARACTER 'A'


61

SOL: SELECT ASCII('A') FROM DUAL;

122: DISPlay THE ASCII VALUE OF CHARACTER'S 'AB' FROM DUAL

SOL: SELECT ASCII('AB') FROM DUAL


HINT:ASCII WILL DISPLAY ONLY THE FIRST LETTER 'A' ONLY

123: DISPLAY THE 3RD OCCURRENCE OF CD AT THE THIRD OCCURRENCE OF


WORD "ABCDABCDABCDJJ"

SOL: SELECT INSTR('ABCDABCDABCDJJ','CD',3,3) FROM DUAL;

124: DISPLAY THE LENGTH OF THE WORD 'ALLEN'

SOL: SELECT LENGTH('ALLEN') FROM DUAL;

125: DISPLAY THE DATE OF THE NEXT TUESDAY AFTER MARCH 15,1992.

SOL: SELECT NEXT_DAY('15-MAR-92','TUESDAY') "NEXT DAY" FROM DUAL;

126: DISPLAY THE LAST DAY OF THIS MONTH

SOL: SELECT LAST_DAY(SYSDATE) FROM DUAL;

127: DISPLAY THE DIFFERENCE DATE BETWEEN CURRENT DATE AND LAST DAY
OF THE SYSDATE

SOL: SELECT SYSDATE,LAST_DAY(SYSDATE) "LAST",LAST_DAY(SYSDATE)-


SYSDATE
"DAYS LEFT" FROM DUAL;

128: DISPLAY THE DIFFERENCE OF TWO DATES "02-02-1992" AND "01-01-


1992"

SOL: SELECT MONTHS_BETWEEN(TO_DATE('02-02-1992','DD-MON-YYYY'),


TO_DATE('01-01-1992','DD-MON-YYYY')) FROM DUAL;

129: DISPLAY THE CURRENT DATE AND TIME

SOL: SELECT TO_CHAR(SYSDATE,'DD-MON-YY HH24:MI:SS') FROM DUAL;

130: ADD TWO MONTHS TO SYSDATE

SOL: SELECT TO_CHAR(SYSDATE,2) FROM DUAL;

131: ADD 10 DAYS TO SYSDATE

SOL: SELECT TO_CHAR(TO_DATE(SYSDATE,'DD-MON-YY'),'DD')+10 FROM DUAL;

132: DISPLAY THE NUMBER FORMAT OF THE NUMBER 1234

SOL: SELECT TO_NUMBER('1234') FROM DUAL;

133: CONVERT ROWID OF EMPLOYEE NAME SMITH TO EMPLOYEE NAME

SOL: SELECT ENAME FROM EMP WHERE ROWID='00000707.0000.000D';


62

134: DISPLAY THE SYSTEM DATE AS "MON DD YYYY"

SOL: SELECT TO_CHAR(SYSDATE,'MON DD YYYY') FROM DUAL;

135: DISPLAY THE CURRENT DATE IN THE FORMAT DDTH MONTH YYYY

SOL: SELECT TO_CHAR(SYSDATE,'FMDDTH MONTH YYYY') FROM DUAL;

136: CONVERT THE FOLLOWING STRING TO ORACLE DATE FORMAT.


"12-AUGUST-97"

SOL: SELECT TO_DATE('12-AUGUST-97','DD-MONTH-YY') FROM DUAL;

137: DISPLAY THE USERNAME IN WHICH YOU ARE WORKING

SOL: SELECT USER FROM DUAL;

138: DISPLAY TH USERID NUMBER IN WHICH YOU ARE WORKING

SOL: SELECT UID FROM DUAL;

139: DISPLAY THE GREATEST OF THE LIST OF EXPRESSIONS "HARRY"


"HARRIOT"
"HAROLD"

SOL: SELECT GREATEST('HARRY','HARRIOT','HAROLD') FROM DUAL;

140: DISPLAY THE LEAST OF THE LIST OF EXPRESSIONS "HARRY" "HARRIOT"


"HAROLD"

SOL: SELECT LEAST('HARRY','HARRIOT','HAROLD') FROM DUAL;

141: DISPLAY ALL THE ENAMES WHERE COMMISSION IS NULL AND PLACE
THE EXPRESSION " NOT POSSIBLE " IN DEPTARTMENT 30 WHERE
COMMISSION
IS NULL ELSE DISPALY THEIR COMMISSION

SOL: SELECT ENAME,NVL(TO_CHAR(COMM),'NOT POSSIBLE') "COMMISSION"


FROM EMP WHERE DEPTNO=30;

142: DISPLAY THE GREENWICH TIME OF 05:15 A.M

SOL: SELECT TO_CHAR(NEW_TIME(TO_DATE('05:15','HH24:MI'),'PST','GMT'),


'HH24:MI') FROM DUAL;

143: DISPLAY THE LANGUAGE AND TERRITORY CURRENTLY USED BY YOUR


SESSION

SOL: SELECT USERENV('LANGUAGE') FROM DUAL;

144: DISPLAY THE NUMBER OF BYTES EACH EMPLOYEE OCCUPIES INTERNALLY

SOL: SELECT VSIZE(ENAME) "BYTES" FROM EMP;

145: DISPLAY THE AVERAGE SALARY DEPARTMENTWISE

SOL: SELECT AVG(SAL),DEPTNO FROM EMP GROUP BY DEPTNO;


63

146: DISPLAY THE SUMMATION OF SALARIES DEPARTMENTWISE

SOL: SELECT SUM(SAL),DEPTNO FROM EMP GROUP BY DEPTNO;

147: DISPLAY THE SUMMATION OF SALARIES OF FIRST FIVE RECORDS

SOL: SELECT SUM(SAL) FROM EMP WHERE ROWNUM<=5;

148: DISPLAY THE MINIMUM SALARY IN THE TABLE EMP

SOL: SELECT MIN(SAL) FROM EMP;

149: DISPLAY THE MAXIMUM SALARY FROM THE TABLE EMP

SOL: SELECT MAX(SAL) FROM EMP;

150: DISPLAY ALL THE SALARIES SUPRESSING THE DUPLICATES

SOL: SELECT DISTINCT SAL FROM EMP;

151: DISPLAY ALL THE JOB SUPRESSING THE DUPLICATES

SOL: SELECT DISTINCT JOB FROM EMP;

152: DISPLAY NUMBER OF RECORDS PRESENT IN EMP TABLE

SOL: SELECT COUNT(*) FROM EMP;

153: DISPLAY THE NUMBER OF JOBS IN EMP TABLE

SOL: SELECT COUNT(JOB) FROM EMP;

154: DISPLAY NUMBER OF RECORDS FOR DESIGNATION SUPRESSING THE


DUPLICATES

SOL: SELECT COUNT(DISTINCT JOB) FROM EMP;

155: DISPLAY THE MINIMUM HIREDATE HIRED FOR EMPLOYEES

SOL: SELECT MIN(HIREDATE) FROM EMP;

156: CALCULATE THE STANDARD DEVIATION OF SALARIES FROM EMP TABLE

SOL: SELECT STDDEV(SAL) FROM EMP;

157: CALCULATE THE VARIANCE OF ALL THE SALARIES FROM EMP TABLE

SOL: SELECT VARIANCE(SAL) FROM EMP;

158: DISPLAY THE YEAR 2017

SOL: SELECT TO_CHAR(TO_DATE('27-NOV-25','DD-MON-RR'),'YYYY') FROM


DUAL;

159: IF DEPARTMENT NUMBER IS 10 DISPLAY GOODCHOICE ELSE


DISPLAY BADCHOICE IN ALL OTHER DEPARTMENT FIELDS
64

SOL: SELECT DECODE(DEPTNO,10,'GOODCHOICE','BADCHOICE') FROM EMP;

PROBLEMS ON JOINS:-

160: LIST THE DEPARTMENT NAME,EMPLOYEES NAME,EMPLOYEE NUMBER

SOL: SELECT EMP.EMPNO,EMP.ENAME,DEPT.DNAME FROM EMP,DEPT;


WHERE EMP.DEPTNO=DEPT.DEPTNO;

161: LIST THE TOTAL SALARIES OF EACH DEPARTMENT

SOL: SELECT EMP.DEPTNO,SUM(SAL) FROM EMP,DEPT


WHERE EMP.DEPTNO=DEPT.DEPTNO GROUP BY EMP.DEPTNO;

162: LIST THE TOTAL EMPLOYEES SALARIES WHO DOES NOT BELONG
TO ANY DEPARTMENT

SOL: SELECT DEPTNO,SUM(SAL) FROM EMP,DEPT


WHERE EMP.DEPTNO=DEPT.DEPTNO(+);

163: LIST THE MANAGER'S NAME AND EMPLOYEES NAME WHO BELONGS TO
THEIR MANAGER'S

SOL: SELECT M.ENAME||' '||'IS THE MANAGER FOR'||' '|| E.ENAME


FROM EMP E,EMP M WHERE E.MGR=M.EMPNO;

164: LIST THE EMPLOYEES WHOSE SALARIES


BETWEEN 2000 AND 3000

SOL: SELECT * FROM EMP WHERE EMPNO IN (SELECT EMPNO


FROM EMP WHERE SAL BETWEEN 2000 AND 3000);

165: LIST THE DEPARTMENT NAME OF THE EMPLOYEE WHOSE NAME


IS OF JONES

SOL: SELECT DEPT.DNAME FROM EMP,DEPT


WHERE EMP.DEPTNO=DEPT.DEPTNO AND ENAME LIKE 'JONES%';

166: LIST THE DEPARTMENT OF THE EMPLOYEES

SOL: SELECT * FROM EMP


WHERE DEPTNO =ANY(SELECT DEPTNO FROM DEPT);

167: FIND OUT THE EMPLOYEES WITH SAME JOB AS JONES

SOL: SELECT ENAME,JOB FROM EMP


INTERSECT
SELECT ENAME,JOB FROM EMP
WHERE JOB IN (SELECT JOB FROM EMP WHERE ENAME LIKE 'JONES%');

168: DISPLAY INFORMATION ABOUT EMPLOYEES WHO EARN MORE THAN ANY
EMPLOYEES IN DEPARTMENT 30

SOL: SELECT * FROM EMP


WHERE SAL>ALL(SELECT SAL FROM EMP WHERE DEPTNO=30);
65

169: LIST ALL THE EMPLOYEES IN DEPARTMENT NUMBER 10 WITH THE


SAME JOB AS IN DEPARTMENT NUMBER 30

SOL: SELECT ENAME FROM EMP WHERE DEPTNO=10


INTERSECT
SELECT ENAME FROM EMP
WHERE JOB IN (SELECT JOB FROM EMP WHERE DEPTNO=30);

170: LIST THE EMPLOYEES WITH EITHER THE SAME JOB AS JONES
OR SALARY GREATER THAN OR SAME AS FORD

SOL: SELECT ENAME FROM EMP


INTERSECT
SELECT ENAME FROM EMP
WHERE JOB IN(SELECT JOB FROM EMP WHERE ENAME LIKE 'JONES%'
OR SAL>=(SELECT SAL FROM EMP WHERE ENAME LIKE 'FORD%'));

171: LIST THE EMPLOYEES IN DEPARTMENT 10 WITH THE SAME


JOB AS ANY ONE IN SALES DEPARTMENT

SOL: SELECT ENAME,JOB FROM EMP


WHERE JOB IN (SELECT JOB FROM EMP WHERE DEPTNO=10)
INTERSECT
SELECT ENAME,JOB FROM EMP
WHERE DEPTNO IN (SELECT DEPTNO FROM EMP WHERE JOB='SALESMAN');

172: LIST EMPLOYEES WHOSE SALARY IS SAME AS THAT OF SCOTT OR WARD

SOL: SELECT ENAME FROM EMP

173: TO LIST THE DEPARTMENT THAT HAS NO EMPLOYEES

SOL: SELECT DEPTNO FROM DEPT


MINUS
SELECT DEPTNO FROM EMP;

(OR)

SELECT DEPTNO FROM DEPT


WHERE DEPTNO NOT IN
(SELECT DEPTNO FROM EMP);

174: TO LIST THE DEPARTMENT AND COUNT OF JOB


IN WHICH THERE ARE MORE THAN ON SALESMANS.

SOL: SELECT DEPTNO,JOB,COUNT(*) FROM EMP


WHERE JOB='SALESMAN'
GROUP BY DEPTNO,JOB
HAVING COUNT(*)>1;

175: LIST THE DEPARTMENT IN WHICH THEIR ARE MORE THAN ONE
SALESMAN
66

SOL: SELECT DEPTNO,JOB FROM EMP WHERE JOB='SALESMAN'


AND DEPTNO IN (SELECT DEPTNO FROM EMP GROUP BY DEPTNO
HAVING COUNT(JOB)>1);
176: SELECT THE EVEN NUMBER OF ROWS FROM EMPLOYEE TABLE

SOL: SELECT * FROM EMP


WHERE ROWID IN
(SELECT DECODE(MOD(ROWNUM,2),0,ROWID,NULL) FROM EMP);

177: LIST THE ODD NUMBER OF ROWS FROM EMPLOYEE TABLE


SELECT * FROM EMP
WHERE ROWID IN
(SELECT DECODE(MOD(ROWNUM,2),1,ROWID,NULL) FROM EMP);

178: DELETE THE ODD NUMBER ROWS FROM EMPLOYEE TABLE

SOL: DELETE FROM EMP


WHERE ROWID IN
(SELECT DECODE (MOD(ROWNUM,2),1,ROWID,NULL) FROM EMP);

179: DELETE THE EVEN NUMBER ROWS FROM EMPLOYEE TABLE

SOL: DELETE FROM EMP


WHERE ROWID IN
(SELECT DECODE (MOD(ROWNUM,2),0,ROWID,NULL) FROM EMP);

180: LIST THE EMPLOYEES WHOSE SALARY IS GREATER THAN THE


AVERAGE SALARY OF HIS DEPARTMENT

SOL: SELECT DEPTNO,EMPNO,SAL FROM EMP X WHERE


SAL>(SELECT AVG(SAL) FROM EMP Y WHERE X.DEPTNO=Y.DEPTNO);

181: QUERY DEPARTMENTWISE AVERAGE/MAXIMUM/MINIMUM SALARIES

SOL: SELECT EMP.DEPTNO,DNAME,MAX(SAL),MIN(SAL),AVG(SAL)


FROM EMP,DEPT
WHERE EMP.DEPTNO=DEPT.DEPTNO
GROUP BY EMP.DEPTNO,DNAME;

182: COUNT THE NUMBER OF MALE AND FEMALE EMPLOYEES

SOL: ALTER TABLE EMP


ADD (SEX CHAR(1));

SELECT SEX,COUNT(*)
FROM EMP
GROUP BY SEX
HAVING SEX ='M';
UNION

SELECT SEX,COUNT(*)
FROM EMP
GROUP BY SEX
HAVING SEX='F';
67

183: DISPLAY THE YEAR AND NUMBER OF EMPLOYEES FOR THE YEAR
IN WHICH MORE THAN ONE EMPLOYEE WAS HIRED

SOL: SELECT TO_CHAR(HIREDATE,'YYYY') YEAR,COUNT(*)


FROM EMP GROUP BY TO_CHAR(HIREDATE,'YYYY')
HAVING COUNT(*)>1;

184: DELETE THE DUPLICATE ROWS FROM DEPT TABLE.

SOL: DELETE FROM DEPT


WHERE DEPTNO IN
(SELECT DEPTNO
FROM DEPT
GROUP BY DEPTNO
HAVING COUNT(DEPTNO)>1);

185: DELETE THE DUPLICATE ROWS EXCEPT ITS MINIMUM VALUE

SOL: DELETE FROM EMP A


WHERE ROWID<>(SELECT MIN(ROWID) FROM EMP B
WHERE A.EMPNO=B.EMPNO);

186: LIST LAST FIVE RECORDS FROM EMP TABLE

SOL: SELECT ENAME,SAL FROM EMP MINUS SELECT ENAME,SAL FROM EMP
WHERE ROWNUM<(SELECT MAX(ROWNUM)-4 FROM EMP );

187: LIST THE THIRD HIGHEST SALARY FROM EMP TABLE

SOL: SELECT MAX(SAL) FROM EMP WHERE


SAL<(SELECT MAX(SAL) FROM EMP WHERE
SAL<(SELECT MAX(SAL) FROM EMP));

188: LIST FIVE EMPLOYEES IN LOWEST ORDER OF SALARY

SOL: SELECT ENAME,SAL FROM EMP


MINUS
SELECT ENAME,SAL FROM EMP WHERE
SAL>(SELECT MIN(SAL) FROM EMP WHERE
SAL>(SELECT MIN(SAL) FROM EMP WHERE
SAL>(SELECT MIN(SAL) FROM EMP WHERE
SAL>(SELECT MIN(SAL) FROM EMP))));

189: LIST THE GIVEN RANGE OF RECORDS AS PER THE STORAGE OF


ROWS IN A GIVEN DATABASE TABLE NAMED EMP
SOL: SELECT ROWID FROM EMP X WHERE NOT &N>(SELECT COUNT(ROWID)
FROM EMP Y WHERE Y.ROWID<X.ROWID)
INTERSECT
SELECT ROWID FROM EMP X WHERE &M>=(SELECT COUNT(ROWID)
FROM EMP Y WHERE Y.ROWID<X.ROWID);

190: LIST THE NTH HIGHEST SALARY IN THE EMPLOYEE TABLE

SOL: SELECT DISTINCT SAL FROM EMP WHERE


SAL=(SELECT DISTINCT SAL FROM EMP X WHERE &N=(SELECT
COUNT(DISTINCT SAL) FROM EMP Y WHERE Y.SAL>X.SAL));
68

191: LIST THE NTH LOWEST SALARY IN THE EMPLOYEE TABLE

SOL: SELECT DISTINCT SAL FROM EMP X WHERE


&N=(SELECT COUNT(DISTINCT SAL) FROM EMP Y
WHERE X.SAL>Y.SAL);

192: LIST EMPLOYEES IN THE EMPLOYEE TABLE ACCEPTING THOSE


FIRST FIVE AND LAST THREE IN THE ORDER OF DATA STORAGE

SOL: SELECT ROWID FROM EMP X WHERE 5>(SELECT COUNT(ROWID)


FROM EMP Y WHERE Y.ROWID<X.ROWID)
UNION
SELECT ROWID FROM EMP X WHERE 3 >(SELECT COUNT(ROWID)
FROM EMP Y
WHERE Y.ROWID>X.ROWID);

193: LIST THE TREE STRUCTURED QUERY WITH EMPLOYEE NAME STARTING
WITH KING

SOL: SELECT LPAD(' ',6*(LEVEL-1))||ENAME NAME FROM EMP


START WITH ENAME='KING'
CONNECT BY MGR=PRIOR EMPNO;

194: LIST THE EMPLOYEES WHOSE SALARY GREATER THAN OR EQUAL TO


AVERAGE SALARY OF DEPARTMENT NUMBER 10

SOL: SELECT SAL,ENAME FROM EMP


WHERE SAL>=(SELECT AVG(SAL) FROM EMP
GROUP BY DEPTNO HAVING DEPTNO=10);

195: SELECT ALL THE ENAMES WITH THE OCCURANCES OF THE LETTER 'S'

SOL: SELECT INSTR(ENAME,'A') FROM EMP;

196: LIST THE DIFFERENT DESIGNATIONS IN DEPARTMENT 20 AND 30

SOL: SELECT DISTINCT JOB FROM EMP


WHERE DEPTNO=20
UNION
SELECT DISTINCT JOB FROM EMP
WHERE DEPTNO=30;

197: LIST THE JOBS COMMON IN DEPARTMENT 20 AND 30

SOL: SELECT JOB FROM EMP


WHERE DEPTNO=20
INTERSECT
SELECT JOB FROM EMP
WHERE DEPTNO=30;

198: LIST THE JOBS UNIQUE TO DEPARTMENT 20

SOL: SELECT JOB FROM EMP


WHERE DEPTNO=20
69

MINUS
SELECT JOB FROM EMP
WHERE DEPTNO=10
MINUS
SELECT JOB FROM EMP
WHERE DEPTNO=30;

199: LIST THE EMPLOYEES IF AND ONLY IF MORE THAN 10 EMPLOYEES ARE
PRESENT IN DEPARTMENT NUMBER 10

SOL: SELECT * FROM EMP


WHERE EXISTS (SELECT DEPTNO,COUNT(*) FROM EMP
WHERE DEPTNO=10
GROUP BY DEPTNO
HAVING COUNT(*)>=3);

200: LIST THE EMPLOYEE NAMES WHOSE SALARY IS GREATER THAN THE
LOWEST SALARY OF AN EMPLOYEE BELONGING TO DEPARTMENT 20

SOL: SELECT ENAME FROM EMP


WHERE SAL>ANY(SELECT SAL FROM EMP WHERE DEPTNO=20);

201: LIST THE EMPLOYEE NAMES WHOSE SALARY IS GREATER THAN THE
HIGHEST SALARY OF AN EMPLOYEE BELONGING TO DEPARTMENT NUMBER 20

SOL: SELECT ENAME FROM EMP


WHERE SAL>ALL(SELECT SAL FROM EMP WHERE DEPTNO=20);

202: CREATE A VIEW WITH COLUMNS EMPNO AND A 10% HIKE SALARY COLUMN
AND TRY TO INSERT A ROW IN THIS VIEW AND VERIFY IT

SOL: CREATE VIEW EMPSAL AS SELECT EMPNO,SAL*.1 TOT_SAL FROM EMP;

HINT: THE FOLLOWING VIEWS ARE READ - ONLY VIEWS


i.e NO INSERT OR UPDATE THROUGH THESE VIEWS IS POSSIBLE
THIS IS A READ - ONLY VIEW BECAUSE OF THE PRESENCE
OF AN AGGREGATE FUNCTION

203: CREATE A VIEW WITH THE COLUMNS EMPNO,ENAME,DEPTNO SELECTED


FROM THE TABLE EMP AND CORRESPONDING DEPARTMENT NUMBER 30
INSERT ROWS INTO THIS VIEW AND VERIFY THE RESULT

SOL: CREATE VIEW EMPDEPT AS


SELECT EMPNO,ENAME,DEPTNO FROM EMP WHERE DEPTNO=30;

HINT: THIS IS NOT A READ - ONLY VIEW. ROWS CAN BE INSERTED


INTO THE EMP TABLE USING THIS VIEW , BUT CANNOT BE VIEWED
BY THE EMPDEPT VIEW AS THE VIEW CAN ONLY RETRIEVE ROWS
BELONGING TO DEPARTMENT 30

204: CREATE A VIEW WITH COLUMNS EMPNO,ENAME,DEPTNO AND DEPTNO=30


WITH A CHECK OPTION AND INSERT A ROW INTO THE VIEW WITH
DEPARTMENT NUMBER 20 AND VERIFY THE RESULT

SOL: CREATE VIEW EMPDEPT1 AS


70

SELECT EMPNO,ENAME,DEPTNO FROM EMP


WHERE DEPTNO=30
WITH CHECK OPTION;

205: DERIVE A VIEW FROM ANOTHER VIEW HAVING CHECK OPTION

SOL: CREATE VIEW EMPDEPT2 AS


SELECT EMPNO,ENAME,DEPTNO FROM EMPDEPT1;

206: LIST ALL THE VIEW NAMES CREATED IN YOUR LOGIN

SOL: SELECT * FROM USER_VIEWS;

207: CREATE A SIMPLE SEQUENCE

SOL: CREATE SEQUENCE S1 INCREMENT BY 1 START WITH 1000;

208: INSERT THE SEQUENCE NUMBER INTO THE EMPNO COLUMN


OF EMP TABLE

SOL: INSERT INTO EMP(EMPNO) VALUES(S1.NEXTVAL);

209: CREATE A SEQUENCE WITH STEP VALUE=1;


START VALUE=2;MINIMUM VALUE=1;MAXIMUM VALUE=22
AND THE SEQUENCE TO RESET AUTOMATICALLY WHEN IT COMES
TO START VALUE

SOl: CREATE SEQUENCE S2


INCREMENT BY 1
START WITH 2
MINVALUE 1
MAXVALUE 22
CYCLE;

210: DROP THE SEQUENCE

SOL: DROP SEQUENCE S2;

211: LIST ALL THE SEQUNCES CREATED IN YOUR LOGIN

SOL: SELECT * FROM USER_SEQUENCES;

212: CREATE AN INDEX ON COLUMN ENAME OF EMP TABLE

SOL: CREATE INDEX ID1 ON EMP(ENAME);

213: CREATE INDEX ON TWO COLUMNS EMPNO,ENAME

SOL: CREATE INDEX ID2 ON EMP (EMPNO,ENAME);

214: DROP THE INDEX YOU HAVE CREATED

SOL: DROP INDEX ID1;

215: LIST THE INDEXES CREATED ON THE TABLE EMP


71

SOL: SELECT * FROM USER_INDEXES WHERE TABLE_NAME='EMP';

216: CREATE A CLUSTER BASED ON THE DEPT AND EMP TABLE FOR
THE FIELD DEPTNO

SOL: CREATE CLUSTER C1 (DEPTNO NUMBER(2));


CREATE INDEX ID3 ON CLUSTER C1;
CREATE TABLE DEPT1
(DNO NUMBER(2) PRIMARY KEY,
DNAME CHAR(15),
LOC CHAR(15))
CLUSTER C1(DNO);

CREATE TABLE EMP1


(EMPNO NUMBER(4) PRIMARY KEY,
ENAME CHAR(15),
HIREDATE DATE,
SALARY NUMBER(9,2),
DEPTARTMENTNO NUMBER(2) REFERENCES DEPT1(DNO))
CLUSTER C1(DEPTARTMENTNO);

217: INSERT INTO TABLES DEPT1 AND EMP1 EACH THREE ROWS AND
CHECK THE ROWID OF THE TWO CLUSTER TABLES;

SOL: INSERT INTO DEPT1 VALUES(&DNO,'&DNAME','&LOC');


INSERT INTO EMP1 VALUES(&EMPNO,'&ENAME','&HIREDATE',&SALARY,
&DEPARTMENTNO);
SELECT DEPT1.ROWID,EMP1.ROWID FROM DEPT1,EMP1;

218: LIST ALL THE CLUSTERS CREATED IN YOUR LOGIN

SOL: SELECT * FROM USER_CLUSTERS;

219: CREATE A SYNONYM FOR TABLE EMP

SOL: CREATE SYNONYM SY1 FOR EMP;

220: LIST INFORMATION OF SYNONYM

SOL: SELECT * FROM SY1;

221: LIST ALL THE SYNONYM CREATED IN YOUR LOGIN

SOL: SELECT * FROM USER_SYNONYMS;

222: DROP THE SYNONYM CREATED

SOL: DROP SYNONYM SY1;

EMPNO ENAME JOB MGR HIREDATE SAL


COMM DEPTNO

223: CREATE THE EMPLOYEE REPORT OF THE COLUMNS EMPNO,ENAME,JOB


MGR,HIREDATE,SAL,COMM,DEPTNO IN THE FORMAT BELOW:

HEADER: BRAINWARE INFOTECH(P) LTD


72

EMPLOYEES REPORT

COLUMN:
NAMES EMPLOYEE EMPLOYEE DESIGNATION MANAGER DATE OF CURRENT
NUMBER NAME NUMBER JOINING SALARY

COMMISION DEPARTMENT
NUMBER

FOOTER: HAVE A NICE DAY !

SOL: TTITLE LEFT'BRAINWARE INFOTECH(P) LTD| CENTER 'EMPLOYEES REPORT'


BTITLE 'HAVE A NICE DAY!'
COLUMN EMPNO HEADING 'EMPLOYEE | NUMBER'
COLUMN ENAME HEADING 'NAME OF | EMPLOYEE'
COLUMN JOB HEADING ' DESIGNATION'
COLUMN MGR HEADING 'MANAGER | NUMBER'
COLUMN HIREDATE HEADING ' DATE OF | JOINING '
COLUMN SAL HEADING ' CURRENT | SALARY '
COLUMN COMM HEADING 'COMMISION '
COLUMN DEPTNO HEADING 'DEPARTMENT | NUMBER'

Package Specification

The package specification contains public declarations. The scope of


these declarations is local to your database schema and global to the
package. So, the declared objects are accessible from your application
and from anywhere in the package.

#****************#

PACKAGES

#****************#

#****************##****************##****************##****************#

1. WRITE A FUNCTION TO RETURN MAX(EMPNO)+1 .


WRITE A PROCEDURE TO FETCH THE DETAILS WHEN EMPNO=RESULT OF
FUNCTION.
WRITE A FUNCTION TO PASS EMPLOYEE NUMBER AND GET THE JOB
WRITE A PROCEDURE TO ACCEPT DEPTNO AND DISPLAY THE DETAILS OF
ALL
EMPLOYEES OF THAT PARTICULAR DEPARTMENT.(HINT : CURSOR)
WRITE A PACKAGE WHICH INCLUDES ALL THESE PROCEDURES AND FUNCTIONS
73

_________________________________________________________________-

CREATE OR REPLACE PACKAGE EMP_PACK IS


FUNCTION NEXTEMP RETURN NUMBER;
PROCEDURE P1;
FUNCTION F2(ENO NUMBER) RETURN VARCHAR;
PROCEDURE P2(DNO NUMBER);
CURSOR C1 IS SELECT * FROM EMP;
END emp_pack;

CREATE OR REPLACE PACKAGE BODY EMP_PACK IS


FUNCTION NEXTEMP RETURN NUMBER IS
CURR_MAX NUMBER:=0;
BEGIN
SELECT MAX(EMPNO) INTO CURR_MAX FROM EMP;
CURR_MAX:=CURR_MAX+1;
RETURN CURR_MAX;
END NEXTEMP;

PROCEDURE P1 IS
ENO NUMBER;
NAME VARCHAR2(10);
DEPNO NUMBER;
SALARY EMP.SAL%TYPE;
BEGIN
ENO:=EMP_PACK.NEXTEMP;
PRINT('NEW EMPLOYEE NUMBER IS'||ENO);
SELECT ENAME,SAL,DEPTNO INTO NAME,SALARY,DEPNO FROM EMP WHERE
EMPNO=ENO;
PRINT(ENO||' '||NAME||' '||DEPNO||' '||SALARY);
EXCEPTION
WHEN NO_DATA_FOUND THEN
PRINT('NO DATA FOUND');
END P1;

PROCEDURE P2(DNO NUMBER) IS


CURSOR C1 IS SELECT * FROM EMP WHERE DEPTNO=DNO;
BEGIN
FOR I IN C1 LOOP
DBMS_OUTPUT.PUT_lINE(I.ENAME||' '||I.JOB||' '||I.DEPTNO);
END LOOP;
EXCEPTION
WHEN NO_dATA_FOUND THEN
PRINT('NO DATA FOUND');
END P2;

FUNCTION F2(ENO NUMBER) RETURN VARCHAR IS


DESIG EMP.JOB%TYPE;
BEGIN
SELECT JOB INTO DESIG FROM EMP WHERE EMPNO=ENO;
RETURN DESIG;
END F2;
74

END EMP_PACK;

DECLARE
NEXTEMP NUMBER;
F2 EMP.JOB%TYPE;
BEGIN
NEXTEMP:=EMP_PACK.NEXTEMP;
PRINT('NEXTEMP IS '||NEXTEMP);
EMP_PACK.P1;
F2:=EMP_PACK.F2(&EMPNO);
PRINT('PRINTING JOB FROM F2 '||F2);
EMP_PACK.P2(&DEPTNO);
END;

#****************##****************##****************##****************#

1. Create a package that contains the following sub programs


(a) Procedure NEW_EMP to add a new employee to the emp table.
(b) Procedure UPDATE_EMP to update the employee details
(display error message if i.e error)
(c) Function CHECK_EMP to check if an employee is
existing in the table

_______________________________________________________________________

CREATE OR REPLACE PACKAGE GEEPACK IS


PROCEDURE NEW_EMP(eno number,dno number,mg number,name varchar2);
PROCEDURE UPDATE_EMP(N NUMBER);
FUNCTION CHECK_eMP(N NUMBER) RETURN NUMBER;
END GEEPACK;

CREATE OR REPLACE PACKAGE BODY GEEPACK IS

PROCEDURE NEW_EMP(ENO NUMBER, DNO NUMBER,MG NUMBER,NAME VARCHAR2) IS


BEGIN
INSERT INTO EMP(EMPNO,DEPTNO,MGR,ENAME) VALUES(ENO,DNO,MG,NAME);
END NEW_EMP;

PROCEDURE UPDATE_EMP (N NUMBER) IS


DESIG VARCHAR2(10);
BEGIN
SELECT JOB INTO DESIG FROM EMP WHERE EMPNO=N;
DBMS_OUTPUT.PUT_LINE('EMPNO = '||N||' JOB = '||DESIG);
IF DESIG='CLERK' THEN
UPDATE EMP SET JOB='FDC' WHERE EMPNO=N;
print('job updated to fdc');
ELSIF DESIG='MANAGER' THEN
UPDATE EMP SET JOB='DGM' WHERE EMPNO=N;
print('job updated to dgm');
END IF;
END UPDATE_EMP;
75

FUNCTION CHECK_eMP (N NUMBER) RETURN NUMBER


IS
N1 NUMBER;
BEGIN
SELECT COUNT(*) INTO N1 FROM EMP WHERE EMPNO=N;
IF n1=0 then
PRINT('EMPLOYEE '||n||' does not EXISTS ');
ELSE
PRINT('EMPLOYEE '||n||' EXISTs');
END IF;
return n1;
END CHECK_EMP;

END GEEPACK;

declare
eno number:=&empno;
dno number:=&deptno;
mg number:=&mgr;
name varchar2(10):='&name';
res number;
begin
print('new_emp is called and values will be inserted');
geepack.new_emp(eno,dno,mg,name);
geepack.update_emp(&updateno);
res:=geepack.CHECK_eMP(&checkno);
print(res);
end;

#****************##****************##****************##****************#

WRITE A FUNCTION TO RETURN MAX(EMPNO)+1 .


WRITE A PROCEDURE TO FETCH THE DETAILS WHEN EMPNO=RESULT OF FUNCTION.
WRITE A PROCEDURE TO ACCEPT DEPTNO AND DISPLAY THE DETAILS OF
ALL
EMPLOYEES OF THAT PARTICULAR DEPARTMENT.(HINT : CURSOR)
WRITE A PACKAGE WHICH INCLUDES ALL THESE PROCEDURES AND FUNCTIONS

CREATE OR REPLACE PACKAGE PACK IS


FUNCTION F1 RETURN NUMBER ;
PROCEDURE P1(N NUMBER);
PROCEDURE P2(DNO NUMBER);
END;
76

CREATE OR REPLACE PACKAGE BODY PACK IS


FUNCTION F1 RETURN NUMBER IS
Z NUMBER;
BEGIN
SELECT MAX(EMPNO)+1 INTO Z FROM EMP;
RETURN Z;
END;

PROCEDURE P1(N NUMBER) IS


A NUMBER;
NAME VARCHAR2(10);
BEGIN
A:=F1;
SELECT ENAME INTO NAME FROM EMP WHERE EMPNO=A;
PRINT('THE NAME IS '||A);
EXCEPTION
WHEN NO_DATA_FOUND THEN
PRINT('NO DATA');
END;

PROCEDURE P2(DNO NUMBEr) IS


CURSOR C2 IS SELECT * FROM EMP WHERE DEPTNO=DNO;
BEGIN
FOR I IN C2 LOOP
PRINT(I.ENAME||' '||I.DEPTNO);
END LOOP;
END ;
END;

DECLARE
F1RES NUMBER;
BEGIN
F1RES:=PACK.F1;
PRINT('THE RESULT OF FUNCTION IS '||F1RES);
PACK.P1(F1RES);
PACK.P2(&DEPTNO);
END;

create table OrdTab


(
OrdId Number,
Customer_Name varchar2(10),
OrdDate Date,
Total Number
)
Partition By Range(OrdId)
(
Partition P1 VAlues Less Than (100),
Partition P2 Values Less Than (200),
partition p3 values less than(300)
77

);

For the column ordid of the ordtab table i have inserted the below
specified values
99
98
100
150
199
200
250
290

when i was above to insert 300 this is what happened

insert into ordtab(ordid) values(300)


*
ERROR at line 1:
ORA-14400: inserted partition key is beyond highest legal partition key

So,to overcome this

create table OrdTab


(
OrdId Number,
Customer_Name varchar2(10),
OrdDate Date,
Total Number
)
Partition By Range(OrdId)
(
Partition P1 VAlues Less Than (100),
Partition P2 Values Less Than (200),
Partition P3 Values Less Than (MaxValue)
);
NOW I INSERTED THE VALUES

90
1000
250
350
450
200

SELECT * FROM ORDTAB PARTITION (P1);

ORDID CUSTOMER_N ORDDATE TOTAL


--------- ---------- --------- ---------
90

TRY THE SAME THING WITH P2 AND P3.


78

SQL> SELECT PARTITION_NAME FROM USER_TAB_PARTITIONS;

PARTITION_NAME
------------------------------
P1
P2
P3

SQL> ALTER TABLE ORDTAB SPLIT PARTITION P1 AT (50);

Table altered.

SQL> SELECT PARTITION_NAME FROM USER_TAB_PARTITIONS;

PARTITION_NAME
------------------------------
P2
P3
SYS_P61
SYS_P62

SQL> SELECT * FROM ORDTAB PARTITION(SYS_P61);

ORDID CUSTOMER_N ORDDATE TOTAL


--------- ---------- --------- ---------
45

SQL> SELECT * FROM ORDTAB PARTITION(SYS_P62);

ORDID CUSTOMER_N ORDDATE TOTAL


--------- ---------- --------- ---------
90
65

ALTER TABLE ORDTAB SPLIT PARTITION P2 AT


(150) INTO (PARTITION P5,PARTITION P6);

Table altered.

SQL> SELECT PARTITION_NAME FROM USER_TAB_PARTITIONS;

(ALSO GIVE THE COMMAND


SELECT PARTITION_NAME,TABLE_NAME FROM USER_tAB_PARTITIONS)

SELECT TABLE_NAME,PARTITION_NAME,HIGH_VALUE FROM


USER_tAB_PARTITIONS;

PARTITION_NAME
------------------------------
P5
P3
SYS_P61
SYS_P62
P6

ADD PARTITION
79

~~~~~~~~~~~~~

CREATE TABLE GG
( ACNO NUMBER(3),
actype varchar2(3),
acbal number(4))
partition by range(acbal)
(partition p1 values less than(5000),
partition p2 values less than(6000));

Table created.

SQL> alter table gg add partition maxp values less than(maxvalue);

Table altered.

DROP PARTITION
~~~~~~~~~~~~~~~~~
ALTER TABLE GG DROP PARTITION P1;
ALTER TABLE <TABLENAME> DROP PARTITION <PARTITION NAME>

RENAME PARTITION
~~~~~~~~~~~~~~~~~~
ALTER TABLE EMP RENAME PARTITION P5 TO P6;

create table ordtab


( ordid number(4),
prdid number(4),
ordname varchar2(10)
)
partition by range(ordid,prdid)
( partition p1 values less than(25,50),
partition p2 values less than(50,75),
partition p3 values less than(75,100)
);

************************************************************************

TO CREATE AN INDEXED PARTITION

create table OrdTab


(
OrdId Number,
Customer_Name varchar2(10),
OrdDate Date,
Total Number
)
Partition By Range(OrdId)
(
Partition P1 VAlues Less Than (100),
Partition P2 Values Less Than (200),
partition p3 values less than(MAXVALUE)
);
80

CREATE INDEX ORDID ON ORDTAB(ORDID)


LOCAL
(PARTITION P1,PARTITION P2,PARTITION P3);

CREATE INDEX ORDID ON ORDTAB(ORDID)


GLOBAL PARTITION BY RANGE(ORDID)
(PARTITION P1 VALUES LESS THAN(10),
PARTITION P2 VALUES LESS THAN(20),
PARTITION P3 VALUES LESS THAN(MAXVALUE));

LIST THE TREE STRUCTURED QUERY WITH EMPLOYEE NAME STARTING


WITH KING

SOL: SELECT LPAD(' ',6*(LEVEL-1))||ENAME NAME FROM EMP


START WITH ENAME='KING'
CONNECT BY MGR=PRIOR EMPNO;

~~~~~~~~~~~~~~~~~~~~
SIMPLE PL/SQL BLOCKS
~~~~~~~~~~~~~~~~~~~~

declare
a number;
b number;
begin
A:=25;
B:=50;
dbms_output.put_line('THE CONTENT OF A IS'||A);
dbms_output.put_line('THE CONTENT OF B IS'||B);
end;

declare
a number:=&A;
b numbeR:=&B;
begin
dbms_output.put_line('THE CONTENT OF A IS '||A);
dbms_output.put_line('THE CONTENT OF B IS '||B);
end;

declare
a number:=&A;
b numbeR:=&B;
PROD NUMBER;
begin
PROD:=A*B;
dbms_output.put_line('THE CONTENT OF A IS '||A);
dbms_output.put_line('THE CONTENT OF B IS '||B);
dbms_output.put_line('THE PRODUCT IS '||PROD);
81

end;

declare
a number:=10;
b number:=20;
res number;
begin
res:=a+b;
dbms_output.put_line(a|| ' '||b);
dbms_output.put_line('The sum is '||res);
end;

declare
a number:=&a;
b number:=&b;
res number;
begin
res:=a+b;
dbms_output.put_line(a|| ' '||b);
dbms_output.put_line('The sum is '||res);
end;

declare
a number:=&a;
b number:=&b;
begin
if (a>b) then
dbms_output.put_line('Biggest number is'||' '||a);
else
dbms_output.put_line('Biggest number is'||' '||b);
end if;
end;

declare
a number:=&a;
begin
if mod(a,5)=0 then
dbms_output.put_line('It is divisible by 5');
else
dbms_output.put_line('It is not divisible by 5');
end if;
end;

declare
n char(10):='&n';
begin
SELECT UPPER(N) INTO N FROM DUAL;
if n='F' then
dbms_output.put_line('FIRST CLASS');
ELSIF N='S' THEN
dbms_output.put_line('SECOND CLASS');
82

ELSIF N='T' THEN


dbms_output.put_line('THIRD CLASS');
else
dbms_output.put_line('FAILED');
END IF;
END;

declare
n number:=1;
begin
loop
dbms_output.put_line(n);
n:=n+1;
exit when n=11;
end loop;
end;

declare
a number:=1;
begin
while (a<=10) loop
dbms_output.put_line(a);
a:=a+1;
end loop;
end;

declare
begin
for a in 1..10 loop
dbms_output.put_line(a);
end loop;
end;

declare
begin
for a in reverse 1..10 loop
dbms_output.put_line(a);
end loop;
end;

declare
n number:=&n;
i number:=1;
begin
while i<=n loop
dbms_output.put_line(i);
i:=i+2;
end loop;
end;

declare
n number:=&n;
i number:=1;
83

begin
while i<=n loop
dbms_output.put(i);
i:=i+2;
end loop;
dbms_output.new_line;
end;

DECLARE
BEGIN
FOR I IN 1..10 LOOP
DBMS_OUTPUT.PUT_LINE(I);
IF I=5 THEN
EXIT;
END IF;
END LOOP;
END;
declare
n number:=&n;
begin
dbms_output.put_line('even numbers are');
for i in 1..n loop
if mod(i,2)=0 then
dbms_output.put_line(i);
end if;
end loop;
end;

to display numbers from 1 to n in same line.

declare
n number:=&n;
begin
for i in 1..n loop
dbms_output.put(i);
end loop;
dbms_output.new_line;
end;

to display the sum of n numbers

declare
n number:=&n;
sum1 number:=0;
begin
dbms_output.put_line('the numbers are');
for i in 1..n loop
dbms_output.put_line(i);
sum1:=sum1+i;
end loop;
dbms_output.put_line('SUM IS '||SUM1);
END;
84

DECLARE
N NUMBER:=&N;
RES NUMBER;
BEGIN
FOR I IN 1..10 LOOP
RES:=N*I;
DBMS_OUTPUT.PUT_LINE(N || ' * '|| I || ' = '|| RES );
END LOOP;
END;

GENERAL PROBLEMS

1 . Write a PL/SQL Program to display all the EVEN Number from 1 to


100.

2. Write a PL/SQL Program to list all the EVEN & ODD Number from 1 to
100 as Follows
Even Numbers Odd Numbers
------------------- ----------------
-
0 1
2 3
4 5
85

. .
. .

3. Write a PL/SQL Program to Find the sum of numbers between 1 and 100
that are divisible by 5 but not
divisible by 7

4. Write a PL/SQL Script to find all the PRIME NUMBERS from 1 to 100

5. Write a PL/SQL program to find ARMSTRONG NUMBERS from 100 to 999.

6. Write a PL/SQL program to List to FIBBNOCI SERIES FROM 0 TO 100

7. Write a PL/SQL Program to Display the Multiplication Table for the


given input.

8. Write a PL/SQL Program to Display the given input string is


PALINDROME OR NOT.

9. Write a PL/SQL Program to REVERSE the given input string.

10. Write a PL/SQL Program to Find out the Given Input data is LEAP
YEAR OR NOT.

11. Write a PL/SQL Program to display First, Second,Third Greatest


number From give three numbers

12. Write a PL/SQL Program to find out the RAMAN NUMBER between
1000 and 9999
ex : 1233 , 12*12+33*33 = 1233
13. Write a PL/SQL Program to display the vowels from the input
string

14. Write a PL/SQL Program to display the vowels, No.of


vowels,position of each vowels and
occurrences of each vowels.

15. Write a PL/SQL Program to find out a given sub string from the
given Main string.(Without using
INSTR FUNCTION).

16. Write a PL/SQL Program to find out No.of characters, No.of


digits, No.of special Characters from
the given input.

************************************************************************
*****

CURSOR PROBLEMS

1. Write a PL/SQL Program to Copy the data from One table to


another which has the same structure with
the RECORD NUMBER.

2. Assume the following table for the given problem :


86

ID
NAME
MARK1
MARK2
MARK3
MARK4

1000
AYYAPPAN
100
99
90
95

1002
BASKER
30
20
25
70

1001
N.B.SING
90
60
50
35

Write a PL/SQL Program to display all the student information


with the TOTAL, AVERAGE,
GRADE. The GRADE is base on the following condition.
1 . between 100 and 90 A GRADE
2. between 89 and 80 B GRADE
3. between 79 and 70 C GRADE
4. otherwise WASTE.

3. Write a PL/SQL Program to display the following output


base on the department :

Department No. Department Name Loc


10 computer Bangalore

Empno Ename Sal Comm


Hiredate
1000 john 5000 100
12-MAR-98
1001 SMITH 6000 NULL
30-JAN-98
....... ......... ....... ........
. ...........

4. Write a PL/SQL Program to display the following output :


job : MANAGER
No. of Managers Sum of Salary Names
3 54000
87

John,smith,miller
job : CLERK
------- --------
-------------

5. Write a PL/SQL Program to Display the First 5 Maximum Salary by


using Parameter to The cursor

6. Write a PL/SQL Program to display all the salary in the descending


order without using the order by
clause in the CURSOR SELECT statement

************************************************************************
*****

EXCEPTION

Assume the following table for the problems given below:

Table Name : BANK


Acc_no number(6)
Acc_name varchar(40)
Curr_balance number(20,4)

1. Write a PL/SQL Program to WITHDRAW money from a particular account.


The Acc_no and
Curr_balace should be entered from keyboard. The exceptions raised are
a) Acc_no not found
b) Over Drawn
c) too many rows returned

2. Write a PL/SQL Program to CREDIT money to a particular account and


return the current balance. The
account number and amount should be entered through keyboard. The
exceptions are :
a) account number not found
b)

3. Write a PL/SQL Program to add a NEW account holder by getting the


input from the user using the
exception
a) duplicate account number
b) too many rows
c) invalid number and value error

4. Write a PL/SQL Program to DELETE account holder by entering the


account number. The exception
a)no data found
b)Before delete display the current balance

************************************************************************
*****

SUBPROGRAM
88

1. Write a PL/SQL Program to SWAP the two input number without using
the temporary variable, by
using the PROCEDURE.

2. Write a PL/SQL Program to find out the factorial of a given input


number using recursive function.

************************************************************************
*****

DATABASE TRIGGERS

1. Write a database trigger to implement the PRIMARY KEY CONSTRAINT.

2. Write a database trigger to implement the FOREIGN KEY CONSTRAINT.

3. Write a database trigger to implement the ON DELETE CASCADE.

4. Write a database trigger to disallow the DELETE operation from


others User except Owner.

5. Write a database trigger to automatically convert the lower case


employee name to UPPER CASE
employee name while entering.

6. Write a database trigger to disallow any operation on SUNDAY and any


day BEFORE 9 AM AND
AFTER 6 PM

7. Write a database trigger to copy the record which has been


deleted with USER,DATE,TIME

8. Write a database trigger to generate the serial number for the


particular table.

9. Write a database trigger to validate the empno as a 4 digit


number.

10. Write a database trigger to validate the comm may be NULL or


less then 1/4 of the salary and must
not be negative

************************************************************************
*****

PACKAGES

1. Create a package that contains the following sub programs


(a) Procedure NEW_EMP to add a new employee to the emp table.
(b) Procedure UPDATE_EMP to update any empoyees details with
proper
error message
(c) Function CHECK_EMP to check if an employee is existing the
table
89

(d) Procedure DELETE_EMP to delete an employee `s record.


(e) Procedure ERROR_MESSAGE to display error message generated
by any
of the above
procedure or functions.

2. Create a package to conduct bank transactions involving the


following procedures and functions.
(a) Debit
(b) Credit
(c) New account
(d) Journal entry recording all transaction(Acct_id, Trans_type,
sysdate)
(e) Enter the transactions with status pending

BLOCKS CREATED ON

1. GOTO
2. EXIT
3. EXIT WHEN
4. GENERATE EVEN/ODD SERIES
5. GENERATE MULTIPLICATION TABLES
6. REVERSE OF NUMBER
7. REVERSE OF STRING
8. PRIME OR NOT
9. SQUARE
10. M TO POWER N
11. ODD AND EVEN SERIES TOGETHER
12. ACCEPT SYMBOL FROM USER AND DEPENDING ON THAT
ADD,SUBTRACT,MULTIPLY
OR DIVIDE 2 NUMBERS.
13. GENERATE NUMBERS IN FIBONACCI SERIES.
14. FACTORIAL OF NUMBER

1.---------GOTO STATEMENT
~~~~~~~~~~~~~~
DECLARE
BEGIN
FOR I IN 1..10 LOOP
DBMS_OUTPUT.PUT_lINE(I);
IF I=5 THEN
GOTO AA;
END IF;
END LOOP;
<<AA>>
DBMS_OUTPUT.PUT_lINE('OUTSIDE THE LOOP');
END;

OUTPUT IS
1
2
3
4
90

5
HELLO

DECLARE
A NUMBER:=&A;
B NUMBER:=&B;
BEGIN
a:=a+b+100;
if a>1000 then
goto zz;
else
dbms_output.put_line('out put not greater than 1000');
end if;
<<zz>>
dbms_output.put_line(a);
END ;

2.-----------------EXIT STATEMENT
~~~~~~~~~~~~~~
DECLARE
BEGIN
FOR I IN 1..10 LOOP
DBMS_OUTPUT.PUT_lINE(I);
IF I=5 THEN
EXIT;
END IF;
END LOOP;
END;

OUTPUT IS
1
2
3
4
5

3.----------------EXIT WHEN STATEMENT


~~~~~~~~~~~~~~~~~~~
DECLARE
BEGIN
FOR I IN 1..10 LOOP
DBMS_OUTPUT.PUT_lINE(I);
EXIT WHEN I=5;
END LOOP;
END;

OUTPUT IS
1
2
3
4
5
91

4.-----------------------WHILE LOOP
~~~~~~~~~~
GENERATE ODD/EVEN NUMBERS

DECLARE
N NUMBER:=&N;
I NUMBER:=1;
BEGIN
WHILE(I<N) LOOP
DBMS_OUTPUT.PUT_lINE(I);
I:=I+2;
END LOOP;
END;

(FOR EVEN SERIES REPLACE 1 WITH 0);

DECLARE
N NUMBER:=&N;
BEGIN
FOR I IN 1..N LOOP
IF MOD(I,2)=0 THEN
DBMS_OUTPUT.PUT_lINE(I);
END IF;
END LOOP;
END;

5.--------------------MULTIPLICATION TABLES
~~~~~~~~~~~~~~~~~~~~~
DECLARE
N NUMBER:=&N;
RES NUMBER;
BEGIN
DBMS_OUTPUT.PUT_lINE('THE MULTIPLICATION TABLE IS');
FOR I IN 1..10 LOOP
RES:=N*I;
DBMS_OUTPUT.PUT_LINE(N ||' * '||I ||' = '||RES);
END LOOP;
END;

~~~~~~~~~~~~~~~~~~~~~
6.----------------REVERSE OF A NUMBER
~~~~~~~~~~~~~~~~~~~

DECLARE
N NUMBER:=&N;
R NUMBER:=0;
L NUMBER;
BEGIN
L:=LENGTH(N);
FOR I IN 1..L LOOP
R:=R*10+MOD(N,10);
N:=FLOOR(N/10);
END LOOP;
92

--DBMS_OUTPUT.PUT_LINE(N);
DBMS_OUTPUT.PUT_LINE(R);
END;

DECLARE
N NUMBER:=&N;
R NUMBER;
L NUMBER;
BEGIN
DBMS_OUTPUT.PUT_LINE('THE NUMBER IS '||N);
L:=LENGTH(N);
FOR I IN 1..L LOOP
R:=R||MOD(N,10);
N:=FLOOR(N/10);
END LOOP;
DBMS_OUTPUT.PUT_LINE('THE REVERSE OF THE NUMBER IS '||R);
END;

7. ------------------REVERSE OF A STRING

DECLARE
N VARCHAR2(12):='&N';
REV VARCHAR2(12);
LEN NUMBER;
BEGIN
DBMS_OUTPUT.PUT_LINE('STRING IS '||N);
LEN:=LENGTH(N);
FOR I IN REVERSE 1..LEN LOOP
REV:=REV||SUBSTR(N,I,1) ;
END LOOP;
DBMS_OUTPUT.PUT_LINE('REVERSED STRING IS '||rEV);
END;

8---------------------PRIME OR NOT
~~~~~~~~~~~~

DECLARE
N NUMBER:=&N;
FLAG NUMBER:=1;
BEGIN
FOR I IN 2..N-1 LOOP
IF MOD(N,I)=0 THEN
FLAG:=0;
EXIT;
END IF;
END LOOP;
IF FLAG=0 THEN
DBMS_OUTPUT.PUT_LINE('NUMBER IS NOT PRIME');
ELSE
DBMS_OUTPUT.PUT_lINE('NUMBER IS PRIME');
END IF;
93

END;

9.------------------DRAW A SQUARE

DECLARE
BEGIN
FOR I IN 1..10 LOOP
DBMS_OUTPUT.PUT('?');
DBMS_OUTPUT.PUT(' ');
END LOOP;
DBMS_OUTPUT.NEW_LINE;
FOR I IN 1..10 LOOP
DBMS_OUTPUT.PUT_LINE('? ?');
END LOOP;
FOR I IN 1..10 LOOP
DBMS_OUTPUT.PUT('?');
DBMS_OUTPUT.PUT(' ');
END LOOP;
DBMS_OUTPUT.NEW_LINE;
END;

10.-----------------M RAISED TO NTH POWER

DECLARE
M NUMBER:=&M;
N NUMBER:=&N;
RES NUMBER;
BEGIN
RES:=POWER(M,N);
DBMS_OUTPUT.PUT_lINE('M TO POWER OF N IS '||RES);
END;

11.----------------DISPLAY ODD AND EVEN SERIES

DECLARE
BEGIN
DBMS_OUTPUT.PUT_LINE('ODD-----------EVEN');
DBMS_OUTPUT.PUT_lINE('__________________');
FOR I IN 1..20

LOOP
IF MOD(I,2) = 0 THEN
DBMS_OUTPUT.PUT_LINE(' '||I);
ELSE
DBMS_OUTPUT.PUT(I);
END IF;
END LOOP;
END;
94

12.---------------------------
ACCEPT SYMBOL FROM USER AND DEPENDING ON THAT ADD,SUBTRACT,MULTIPLY
OR DIVIDE 2 NUMBERS.

DECLARE
NUM1 NUMBER:=&NUMBER1;
SYB CHAR:='&SYMBOL';
NUM2 NUMBER:=&NUMBER2;
RESULT NUMBER;
BEGIN
IF SYB='+' THEN
RESULT:=NUM1+NUM2;
ELSE
IF SYB='-' THEN
RESULT:=NUM1-NUM2;
ELSE
IF SYB='*' THEN
RESULT:=NUM1*NUM2;
ELSE
IF SYB='/' THEN
RESULT:=NUM1/NUM2;
END IF;
END IF;
END IF;
END IF;

DBMS_OUTPUT.PUT_LINE(RESULT);
END;
95

PL/SQL Tables

Objects of type TABLE are called "PL/SQL tables," which are modelled
on (but not the same as) database tables. PL/SQL tables use a primary
key to give you array-like access to rows. The size of a PL/SQL table
is unconstrained. That is, the number of rows in a PL/SQL table can
increase dynamically.
96

PL/SQL tables can have one column and a primary key, neither of which
can be named. The column can belong to any scalar type, but the
primary

key must belong to type BINARY_INTEGER.

Declaring PL/SQL Tables

PL/SQL tables must be declared in two steps. First, you define a TABLE
type, then declare PL/SQL tables of that type. You can declare TABLE
types in the declarative part of any block, subprogram, or package
using the syntax

TYPE type_name IS TABLE OF


{ column_type | variable%TYPE | table.column%TYPE 'D [NOT NULL]

INDEX BY BINARY_INTEGER;

where "type_name" is a type specifier used in subsequent declarations


of PL/SQL tables and "column_type" is any scalar datatype such as CHAR,
DATE, or NUMBER. You can use the %TYPE attribute to specify a column
datatype.

In this example, you declare a TABLE type called "EnameTabTyp":

DECLARE
TYPE EnameTabTyp IS TABLE OF CHAR(10)
INDEX BY BINARY_INTEGER;

You could have used %TYPE to provide the column datatype, as follows:

DECLARE
TYPE EnameTabTyp IS TABLE OF emp.ename%TYPE
INDEX BY BINARY_INTEGER;

Once you define type "EnameTabTyp," you can declare PL/SQL tables of
that type, as follows:

ename_tab EnameTabTyp;

The identifier "ename_tab" represents an entire PL/SQL table.

Like scalar variables, PL/SQL tables can be declared as the formal

parameters of procedures and functions. Some packaged examples follow:

PACKAGE emp_actions IS
TYPE EnameTabTyp IS TABLE OF emp.ename%TYPE
INDEX BY BINARY_INTEGER;
TYPE SalTabTyp IS TABLE OF emp.sal%TYPE
INDEX BY BINARY_INTEGER;
ename_tab EnameTabTyp;
sal_tab SalTabTyp;
...
PROCEDURE hire_batch
97

(ename_tab EnameTabTyp,

sal_tab SalTabTyp,
...);
PROCEDURE log_names
(ename_tab EnameTabTyp,
num BINARY_INTEGER);
...
END emp_actions;

Referencing PL/SQL Tables

To reference rows in a PL/SQL table, you specify a primary key value


using the array-like syntax

plsql_table_name(primary_key_value)

where "primary_key_value" belongs to type BINARY_INTEGER. For example,

you reference the third row in PL/SQL table "ename_tab" as follows:

ename_tab(3) ...

You can assign the value of a PL/SQL expression to a specific row using
the following syntax:

plsql_table_name(primary_key_value) := plsql_expression;

In the next example, you assign the sum of variables "salary" and
"increase" to the fifth row in PL/SQL table "sal_tab":

sal_tab(5) := salary + increase;

Until a row is assigned a value, it does not exist. If you try to


reference an uninitialized row, PL/SQL raises the predefined exception
NO_DATA_FOUND. Consider the following example:

DECLARE
TYPE JobTabTyp IS TABLE OF CHAR(14)
INDEX BY BINARY_INTEGER;
job_tab JobTabTyp;
BEGIN
job_tab(1) := 'CLERK';
IF job_tab(2) = 'CLERK' THEN -- raises NO_DATA_FOUND

...
END IF;
...
EXCEPTION
WHEN NO_DATA_FOUND THEN
-- here because job_tab(2) does not exist
...
END;
98

Inserting/Fetching Rows

You must use a loop to INSERT values from a PL/SQL table into a
database
column. Likewise, you must use a loop to FETCH values from a database
column into a PL/SQL table. For example, given the declarations

DECLARE
TYPE EmpnoTabTyp IS TABLE OF NUMBER(4)
INDEX BY BINARY_INTEGER;
TYPE EnameTabTyp IS TABLE OF CHAR(10)
INDEX BY BINARY_INTEGER;
...
empno_tab EmpnoTabTyp;
ename_tab EnameTabTyp;
...

you might use the following procedure to INSERT values from the PL/SQL
tables into the "emp" database table:

PROCEDURE insert_emp_data
(rows BINARY_INTEGER,
empno_tab EmpnoTabTyp,
ename_tab EnameTabTyp,
...) IS
BEGIN
FOR i IN 1..rows LOOP
INSERT INTO emp (empno, ename, ...)
VALUES (empno_tab(i), ename_tab(i), ...);
END LOOP;
END;

Conversely, you might use the next procedure to FETCH all rows from the

database table into PL/SQL tables "empno_tab" and "ename_tab":

PROCEDURE fetch_emp_data
(rows OUT BINARY_INTEGER,
empno_tab OUT EmpnoTabTyp,
ename_tab OUT EnameTabTyp,
...) IS
BEGIN
rows := 0;
FOR emprec IN (SELECT * FROM emp) LOOP
rows := rows + 1;
empno_tab(rows) := emprec.empno;

ename_tab(rows) := emprec.ename;
...
END LOOP;
END;

However, you cannot reference PL/SQL tables in the INTO clause. For
example, the following SELECT statement is illegal:
99

PROCEDURE fetch_emp_data
(rows OUT BINARY_INTEGER,
empno_tab OUT EmpnoTabTyp,
ename_tab OUT EnameTabTyp,
...) IS

BEGIN
SELECT empno, ename
INTO empno_tab, ename_tab -- illegal
FROM emp;
...
END;

Deleting Rows

You cannot delete individual rows from a PL/SQL table because the
DELETE statement cannot specify PL/SQL tables. However, you can use
a simple workaround to delete entire PL/SQL tables. When you want to
delete a PL/SQL table, simply assign a null to it, as shown in the

following example:

DECLARE
TYPE NumTabTyp IS TABLE OF NUMBER
INDEX BY BINARY_INTEGER;
sal_tab NumTabTyp;
...
BEGIN
/* Load salary table. */
FOR i IN 1..50 LOOP
sal_tab(i) := i;
END LOOP;
...
/* Delete salary table. */
sal_tab := NULL; -- releases all PL/SQL table resources

...
END;

See also: Datatypes, Variables and Constants, Records,


FETCH Statement, INSERT, DELETE

1. pl/sql block to print details of employees when number=7788;


~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

declare
num number(5);
name varchar(10);
sal number(7,2);
begin
select empno,ename,sal into num,name,sal from emp where empno=7902;
dbms_output.put_Line(num||' '||name||' '||sal);
100

end;

2. pl/sql block to print details of employees when number=n


~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

declare
num number(5);
name varchar(10);
sal number(7,2);
begin
select empno,ename,sal into num,name,sal from emp where empno=&n;
insert into areas values(100,4000);
dbms_output.put_Line(num||' '||name||' '||sal);
end;

DECLARE
NAME VARCHAR2(10):='&NAME';
DESIG VARCHAR2(12);
SALARY NUMBER(7,2);
NETSAL NUMBER(7,2);
BEGIN
SELECT JOB,SAL INTO DESIG,SALARY FROM EMP WHERE ENAME=NAME;
DBMS_OUTPUT.PUT_LINE(NAME||' '||DESIG||' '||SALARY);
IF DESIG='CLERK' THEN
UPDATE EMP SET SAL=SALARY*0.1 +SALARY WHERE ENAME=NAME;
NETSAL:=SALARY*0.1+SALARY;
DBMS_OUTPUT.PUT_LINE('THE NET SALARY IS '||NETSAL);
ELSE
UPDATE EMP SET SAL=SALARY*0.2 +SALARY WHERE ENAME=NAME;
NETSAL:=SALARY*0.1+SALARY;
DBMS_OUTPUT.PUT_LINE('THE NET SALARY IS '||NETSAL);
END IF;
END;
3. update statement in pl/sql

block
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

declare
num number(5):=&EMPNO;
name varchar(10);
salary number(7,2);
desig varchar2(10);
begin
select empno,ename,sal,job into num,name,salary,desig
from emp where empno=NUM;
dbms_output.put_Line(num||' '||name||' '||salARY||' '||DESIG);
if desig='CLERK' THEN
UPDATE EMP SET SAL=SAL+200 WHERE EMPNO=NUM;
ELSIF DESIG='MANAGER' THEN
UPDATE EMP SET SAL=SAL+300 WHERE EMPNO=NUM;
END IF;
COMMIT;
end;

4. DELETE STATEMENT IN PL/SQL BLOCK


101

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

declare
num number(5);
name varchar(10);
salary number(7,2);
desig varchar2(10);
begin
select empno,ename,sal,job into num,name,salary,desig
from emp where empno=&n;
if desig='CLERK' THEN
DBMS_OUTPUT.PUT_LINE('RECORD DELETED');
DELETE FROM EMP WHERE EMPNO=NUM;
ELSE
DBMS_OUTPUT.PUT_LINE('RECORD NOT DELETED');
END IF;
dbms_output.put_Line(num||' '||name||' '||salARY||' '||DESIG);
end;

5. INSERT STATEMENT IN PL/SQL BLOCK


~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

DECLARE
ENO NUMBER(4);
MGR NUMBER(4);
DEPNO NUMBER(3);
BEGIN
INSERT INTO EMP(EMPNO,MGR,DEPTNO)VALUES(&ENO,&MGR,&DEPNO);
DBMS_OUTPUT.PUT_LINE(ENO||' '||MGR||' '||DEPNO);
COMMIT;
END;

6. SELECTING THE VALUES FROM EMP & INSERTING TO TEMP TABLE


~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

declare
num number(5);
name varchar(10);
salary number(7,2);
desig varchar2(10);
begin
select empno,ename,sal,job into num,name,salary,desig
from emp where empno=&n;
if desig='CLERK' THEN
DBMS_OUTPUT.PUT_LINE('RECORD INSERTED');
INSERT INTO TEMP VALUES(NUM,NAME,SALARY,DESIG);
END IF;
dbms_output.put_Line(num||' '||name||' '||salARY||' '||DESIG);
COMMIT;
end;
102

7. DISPLAY NAME AND DESIGNATION OF MANAGERS


~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

(THE BLOCK GIVES ERRORS.


IT IS JUST TO ILLUSTRATE THAT
exact fetch returns more than requested number of rows )

DECLARE
N NUMBER;
NAME EMP.ENAME%TYPE;
DESIG EMP.JOB%TYPE;
BEGIN
SELECT COUNT(*) INTO N FROM EMP WHERE JOB='MANAGER';
FOR I IN 1..N LOOP
SELECT ENAME,JOB INTO NAME,DESIG FROM EMP WHERE JOB='MANAGER';
DBMS_OUTPUT.PUT_LINE(NAME||' '||DESIG);
END LOOP;
END;

EXAMPLE FOR SELECT,INSERT,UPDATE,DELETE STATEMENTS IN PL/SQL


~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
CREATE TABLE TEMP
( ENAME VARCHAR2(10),
DESIG VARCHAR2(10),
SAL NUMBER(7,2));

DECLARE
NAME VARCHAR2(10);
DESIG VARCHAR2(10);
SALARY NUMBER(7,2);
ENO NUMBER(4):=&EMPNO;
BEGIN
SELECT ENAME,JOB,SAL INTO NAME,DESIG,SALARY FROM EMP WHERE EMPNO=ENO;
DBMS_OUTPUT.PUT_LINE(ENO||' '||NAME||' '||SALARY||' '||DESIG);
IF DESIG='CLERK' THEN
DELETE FROM EMP WHERE EMPNO=ENO;
INSERT INTO TEMP VALUES(NAME,DESIG,SALARY);
DBMS_OUTPUT.PUT_LINE('DELETED FROM EMP AND INSERTED TO TEMP');
COMMIT;
ELSIF DESIG='MANAGER' THEN
UPDATE EMP SET SAL=SALARY+200 WHERE EMPNO=ENO;
DBMS_OUTPUT.PUT_LINE('INCREMENTED SALARY IS '||TO_CHAR(SALARY+200));
END IF;
END;

8.SELECT MAX(DEPTNO) FROM DEPT TABLE AND INSERT TO TEMP TABLE


~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

DECLARE
MDEPNO NUMBER(3);
BEGIN
FOR I IN 1..4 LOOP
SELECT MAX(DEPTNO) INTO MDEPNO FROM DEPT5;
103

INSERT INTO TEMP VALUES(MDEPNO);


DBMS_OUTPUT.PUT_LINE(MDEPNO);
DELETE FROM DEPT5 WHERE DEPTNO=MDEPNO;
COMMIT;
END LOOP;
END;

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
~
9. 2 tables are created. In one table the quantiy and the product name
is stored and the other table is dummy table. If we give product name
the details will be displayed.If the number of products is below 5 then
insert into temp table out of stock and sysdate
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
~
inventory table (inv)
~~~~~~~~~~~~~~~
quantity prodname
9 Racket
8 Book
5 Pencil
1 Marker

create table inv(quantity number(3),prodname varchar(10));

temp
~~~~
prodname comment date1

create table temp( prodname varchar2(10), comm varchar2(16),


date1 date);

declare
qty NUMBER(5);
pname VARCHAR2(10);
begin
select quantity,prodname into qty,pname from inv where
prodname='&productname';
if qty>5 then
DBMS_OUTPUT.PUT_LINE('THANK U FOR THE PURCHASES MADE VISIT AGAIN');
update inv set quantity=quantity-1 where prodname=pname;
commit;
else
DBMS_OUTPUT.PUT_LINE('STOCK LEVEL IS BELOW ORDER LEVEL');
insert into temp values(pname,'out of stock',sysdate);
commit;
end if;
end;

10. example for constant


~~~~~~~~~~~~~~~~~~~~~~~~
declare
a constant number:=5;
begin
dbms_output.put_Line(a);
end;
104

(If we make a as an constant we cannot use a as a assignment target.


We can just print a+2,a+3 etc.....)

declare
a constant number:=5;
begin
dbms_output.put_Line(a);
dbms_output.put_Line(a+2);
end;

11.example for default


***********************

declare
a number default 3;
begin
dbms_output.put_Line(a);
end;
(hERE A CAN BE USED AS ASSIGNMENT TARGET).

12. Write a pl/sql block to fetch the details of all the employees
whose
number is 7902. Now if his sal is less than 4000 then fetch salary
mgr and name of the employees whose empno should be equal to
MGR.

13. WAP TO CHECK THE BANK DETAILS. IN BANK TABLE ACCNO AND BALANCE
IS STORED. USER HAS TO ENTER THE ACCOUNT NUMBER AND WITHDRAW
AMOUNT.
IF WITHDRAWL AMOUNT < BALANCE THEN UPDATE BALANCE OF BANK TABLE
AND SUBTRACT THE WITHDRAWL AMOUNT FROM BALANCE ELSE INSERT A
MESSAGE LIKE INSUFFICIENT FUNDS TO TEMP TABLE

create table bank


( accno number(3),
bal number(6));

ACCNO BAL
-------- ---------
10 5000
20 6000
30 20

create table temp


( accno number(3),
bal number(6),
rem varchar2(20));

declare
awith number(3):=&awith;
ac_no number(3):=&accno;
abal number(6);
105

begin
select bal into abal from bank where accno=ac_no;
if abal>awith then
update bank set bal=bal-awith where accno=ac_no;
commit;
else
insert into temp values(ac_no,abal,'insuffunds');
commit;
end if;
end;

14. ILLUSTRATE %TYPE


*********************
declare
a emp.deptno%type;
begin
select deptno into a from emp where empno=&A;
dbms_output.put_line(a);
end;

15.ILLUSTRATE %ROWTYPE
***********************

declare
a emp%ROWtype;
begin
select * into a from emp where empno=&N;
dbms_output.put_line(A.ENAME||' '||A.SAL||' '||A.COMM);
end;

16
write a pl/sql block to calculate the sum and average salaries of
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
all the employees of a particular department.
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

DECLARE
NO NUMBER:=&DEPTNO;
SUM1 NUMBER(7,2);
AVG1 NUMBER(7,2);
BEGIN
SELECT SUM(SAL),AVG(SAL) INTO SUM1,AVG1
FROM EMP
WHERE DEPTNO=NO;
DBMS_OUTPUT.PUT_line('Sum of salary is'||SUM1);
DBMS_OUTPUT.PUT_Line('Average salary is'||AVG1);
END;
106

NESTED TABLE
CREATE OR REPLACE TYPE EMPLOYEE AS OBJECT
_ CREATE TYPE EMPLOYEE AS OBJECT
(NO NUMBER(4),
NAME VARCHAR2(20),
JOB VARCHAR2(10),
SAL NUMBER(7,2));

-------------------------------------------

CREATE TYPE EMPTAB AS TABLE OF EMPLOYEE;

-------------------------------------------

CREATE TABLE DEPTNEST


(DNO NUMBER(2),
DNAME VARCHAR2(20),
EMPL EMPTAB) NESTED TABLE EMPL STORE AS EMPNEST;

---------------------------------------------

INSERT INTO DEPTNEST VALUES (10,'ACCOUNTS',EMPTAB(


EMPLOYEE(1,'RAJ','CLERK',1000),
EMPLOYEE(2,'SARAV','SALES',2000)));

-------------------------------------------------------------

INSERT INTO THE(SELECT EMPL FROM DEPTNEST WHERE


107

DEPTNO=10) VALUES (EMPTAB(3,'SHIV','SUPERV',2300));

SELECT X.EMPL.NAME FROM DEPTNEST X WHERE X.DNO=10;

-----------------------------------------------------
SELECT TYPE_CODE,ATTRIBUTES FROM USER_TYPES WHERE TYPE_NAME='DEPTNEST';

SELECT COLL_TYPES,ELEM_TYPE FROM USER_COL_TYPES WHERE TYPE_NAME='


';

------------------------------------------------------------------------
-------------------------
VARRAY:
-------------
CREATE TYPE PHONE AS OBJECT
(NO NUMBER(6));

----------
CREATE TYPE PHONETYPE AS VARRAY(5) OF PHONE;
----------
CREATE TABLE CUST
(NAME VARCHAR2(20),
PHONENO PHONETYPE);

-----------
INSERT INTO CUST VALUES ('XXXX',
PHONETYPE(PHONE(232322),PHONE(345345));

-----------

SELECT COLumn_NAME,DATA_TYPE_NAME FROM USER_TAB_COLUMNS


WHERE TABLE_NAME=' ';

SELECT TYPE_CODE,ATTRIBUTES FROM USER_TYPES WHERE


TYPE_NAME=' ';

------------------------------------------------------------------------
----------------------

---------------------------------------------------------------
108

#**************#
PROCEDURES
#**************#

#**************##**************##**************##**************##*******
*******#

1. WRITE A PROCEDURE TO DRAW A LINE


2. WRITE A PROCEDURE WHICH ACTS JUST LIKE DBMS_OUTPUT.PUT_LINE
3. WRITE A PROCEDURE TO FETCH THE NAME AND JOB WHEN NO IS PASSED
(this is to illustrate both in and out parameters)
4. WRITE A PROCEDURE TO PASS THE EMPLOYEE NUMBER AND THE AMOUNT TO
BE INCREMENTED.
example to illustrate in out parameter.
5. EXAMPLE TO ILLUSTRATE LOCAL PROCEDURE
I.E DYNAMIC CREATION OF PROCEDURES.(PROCEDURE WITHIN A BLOCK)

#**************##**************##**************##**************##*******
*******#

1.---------- WRITE A PROCEDURE TO DRAW A LINE

CREATE OR REPLACE PROCEDURE LINE IS


BEGIN
FOR I IN 1..40 LOOP
DBMS_OUTPUT.PUT('_');
END LOOP;
DBMS_OUTPUT.NEW_LINE;
END;

EXEC LINE
OR
DECLARE
CURSOR C1 IS SELECT * FROM EMP WHERE JOB='CLERK';
CURSOR C2 IS SELECT * FROM EMP WHERE JOB='MANAGER';
BEGIN
LINE;
LINE;
FOR I IN C1 LOOP
DBMS_OUTPUT.PUT_LINE(I.ENAME||' '||I.JOB);
END LOOP;
LINE;
LINE;
FOR I IN C2 LOOP
DBMS_OUTPUT.PUT_LINE(I.ENAME||' '||I.JOB);
END LOOP;
LINE;
LINE;
END;
________________________________________________________________________
__
109

2---------------WRITE A PROCEDURE WHICH ACTS JUST LIKE


DBMS_OUTPUT.PUT_LINE
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

CREATE OR REPLACE PROCEDURE PRINT( N VARCHAR2) is


begin
dbms_output.put_line(n);
end;

declare
A NUMBER:=25;
begin
PRINT(A);
print('BRAINWARE');
end;

________________________________________________________________________

3------------WRITE A PROCEDURE TO FETCH THE NAME AND JOB WHEN NO IS


PASSED
-------(this is to illustrate both in and out parameters)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

CREATE OR REPLACE PROCEDURE DISP(N NUMBER)


IS
NAME EMP.ENAME%TYPE;
DESIG EMP.JOB%TYPE;
BEGIN
SELECT ENAME,JOB INTO NAME,DESIG FROM EMP WHERE EMPNO=N;
DBMS_OUTPUT.PUT_LINE(NAME||' '||DESIG);
END;

EXEC DISP(7499)

DECLARE
BEGIN
DISP(&N);
END;
OR

CREATE OR REPLACE PROCEDURE DISP1(ENO NUMBER,


NAME OUT VARCHAR,DESIG OUT VARCHAR)
IS
BEGIN
SELECT ENAME,JOB INTO NAME,DESIG FROM EMP WHERE EMPNO=ENO;
END;

DECLARE
NAME1 VARCHAR2(30);
DESIG1 VARCHAR2(10);
N NUMBER:=&EMPNO;
BEGIN
DISP1(N,NAME1,DESIG1);
DBMS_OUTPUT.PUT_LINE(NAME1||' '||DESIG1||' '||N);
110

END;

________________________________________________________________________
__

4---------------WRITE A PROCEDURE TO PASS THE EMPLOYEE NUMBER AND THE


AMOUNT TO
BE INCREMENTED.
example to illustrate in out parameter.

create or replace procedure hike_sal(a in out number,incre number)


is
begin
update emp set sal=sal+incre where empno=a;
if sql%found then
a:=1;
else
a:=0;
end if;
end;

declare
n number:=&empno;
incre number:=&increment;
begin
dbms_output.put_line('n = '|| n||' '||' increment='||incre);
hike_sal(n,incre);
dbms_output.put_line('n = '|| n||' '||' increment='||incre);
if n=1 then
dbms_output.put_line('salary incremented');
else
dbms_output.put_line('salary is not incremented');
end if;
end;
______________________________________________________________________

5-----------EXAMPLE TO ILLUSTRATE LOCAL PROCEDURE


------------I.E DYNAMIC CREATION OF PROCEDURES.(PROCEDURE WITHIN A
BLOCK)

DECLARE
A NUMBER:=10;
J VARCHAR2(10);
ENO NUMBER;
PROCEDURE DISPJOB(N NUMBER,J OUT VARCHAR2) IS
BEGIN
SELECT JOB INTO J FROM EMP WHERE EMPNO=N;
END;
BEGIN
ENO:=&EMPNO;
DBMS_OUTPUT.PUT_LINE('EMPLOYEE NUMBER IS'||ENO);
DISPJOB(ENO,J);
DBMS_OUTPUT.PUT_lINE('EMPNO='||ENO||' JOB='||J);
111

EXCEPTION
WHEN NO_DATA_FOUND THEN
DBMS_OUTPUT.PUT_LINE('MESSAGE');
PRINT('SORRRY NO EMPLOYEE EXISTS WITH THAT NUMBER');
END;

_________________________________
______________________________________

CURSORS
-------

DECLARE
CURSOR C1 IS SELECT ENAME,COMM FROM EMP WHERE EMPNO=7900;
NAME EMP.ENAME%TYPE;
COMMISSION EMP.COMM%TYPE;
BEGIN
OPEN C1;
FETCH C1 INTO NAME,COMMISSION;
DBMS_OUTPUT.PUT_LINE('THE VALUES ARE'||' '||NAME||' '||COMMISSION);
CLOSE C1;
END;

DECLARE
CURSOR C1 IS SELECT EMPNO,ENAME ,DEPTNO FROM EMP;
EMPNUM EMP.EMPNO%TYPE;
EMPNAME EMP.ENAME%TYPE;
DEPTNUM EMP.DEPTNO%TYPE;
BEGIN
OPEN C1;
LOOP
FETCH C1 INTO EMPNUM,EMPNAME,DEPTNUM;
if c1%notfound then
exit;
else
dbms_output.put_line(EMPNUM||' '||EMPNAME||' '||DEPTNUM);
end if;
END LOOP;
end;

DECLARE
CURSOR C1 IS SELECT EMPNO,ENAME ,SAL FROM EMP WHERE DEPTNO=10;
EMPNUM EMP.EMPNO%TYPE;
NAME EMP.ENAME%TYPE;
SALARY EMP.SAL%TYPE;
BEGIN
OPEN C1;
LOOP
FETCH C1 INTO EMPNUM,NAME,SALARY;
IF C1%NOTFOUND THEN EXIT;
END IF;
INSERT INTO TEMP VALUES(EMPNUM,NAME,SALARY);
END LOOP;
--CLOSE C1;
112

END;

//CURSOR ALREADY OPEN


DECLARE
CURSOR C1 IS SELECT EMPNO,ENAME,DEPTNO FROM EMP;
EMPNUM EMP.EMPNO%TYPE;
EMPNAME EMP.ENAME%TYPE;
DEPTNUM EMP.DEPTNO%TYPE;
BEGIN
OPEN C1;
OPEN C1;
FOR I IN 1..5
LOOP
FETCH C1 INTO EMPNUM,EMPNAME,DEPTNUM;
IF C1% NOTFOUND THEN
EXIT;
END IF;
--INSERT INTO TEMP VALUES(EMPNUM,EMPNAME,DEPTNUM);
END LOOP;
CLOSE C1;
END;

DECLARE
CURSOR C1 IS SELECT EMPNO,SAL,COMM FROM EMP;
EMPCODE EMP.EMPNO%TYPE;
SALARY EMP.SAL%TYPE;
COM EMP.COMM%TYPE;
BEGIN
OPEN C1;
LOOP
FETCH C1 INTO EMPCODE,SALARY,COM;
EXIT WHEN C1%NOTFOUND;
INSERT INTO TEMP VALUES(EMPCODE,SALARY,COM);
END LOOP;
CLOSE C1;
END;
////////(ISOPEN WITH CLOSE)

DECLARE
CURSOR C1 IS SELECT EMPNO,SAL,COMM FROM EMP;
EMPCODE EMP.EMPNO%TYPE;
SALARY EMP.SAL%TYPE;
COM EMP.COMM%TYPE;
BEGIN
LOOP
IF C1%ISOPEN THEN
DBMS_OUTPUT.PUT_LINE('CURSOR IS OPEN');
EXIT;
ELSE
OPEN C1;
FETCH C1 INTO EMPCODE,SALARY,COM;
EXIT WHEN C1%NOTFOUND;
INSERT INTO TEMP VALUES(EMPCODE,SALARY,COM);
END IF;
113

END LOOP;
CLOSE C1;
END;

DECLARE
CURSOR C1 IS SELECT EMPNO,ENAME,COMM FROM EMP;
BEGIN
--OPEN C1;
FOR I IN C1
LOOP
DBMS_OUTPUT.PUT_LINE(I.EMPNO||' '||I.ENAME||' '||I.COMM);
INSERT INTO TEMP VALUES(I.EMPNO,I.ENAME,I.COMM);
END LOOP;
--CLOSE C1;
END;

%ROWTYPE
--------

DECLARE
CURSOR C1 IS SELECT * FROM EMP;
TEMPROW EMP%ROWTYPE;
BEGIN
OPEN C1;
LOOP
FETCH C1 INTO TEMPROW;
EXIT WHEN C1%NOTFOUND;
DBMS_OUTPUT.PUT_LINE(TEMPROW.EMPNO||' '||TEMPROW.SAL);
END LOOP;
CLOSE C1;
DECLARE
CURSOR C1 IS SELECT EMPNO,ENAME,SAL FROM EMP;
TEMPROW C1%ROWTYPE;
BEGIN
OPEN C1;
LOOP
FETCH C1 INTO TEMPROW;
EXIT WHEN C1%NOTFOUND;
DBMS_OUTPUT.PUT_LINE(TEMPROW.EMPNO||' '||TEMPROW.SAL);
END LOOP;
CLOSE C1;
END;
END;

IMPLICIT CURSOR
----------------

BEGIN
UPDATE EMP SET HIREDATE='01-SEP-98' WHERE DEPTNO=20;
DBMS_OUTPUT.PUT_LINE(SQL%ROWCOUNT||'ROW UPDATED');
END;

ROWCOUNT
--------
114

DECLARE CURSOR C1 IS SELECT * FROM EMP;


A C1%ROWTYPE;
BEGIN
IF NOT C1%ISOPEN THEN
OPEN C1;
END IF;
LOOP
FETCH C1 INTO A;
IF C1%FOUND THEN
IF C1%ROWCOUNT<5 THEN
DBMS_OUTPUT.PUT_LINE(A.EMPNO||' '||A.ENAME||' '||A.DEPTNO);
ELSE
EXIT;
END IF;
ELSE
EXIT;
END IF;
END LOOP;
CLOSE C1;
END;

EXCEPTION;
----------
(ZERO_DIVIDE)
------------

DECLARE
A NUMBER:=&A;
B NUMBER:=&B;
C NUMBER;
BEGIN
C:=A/B;
DBMS_OUTPUT.PUT_LINE(C);
EXCEPTION
WHEN ZERO_DIVIDE THEN
DBMS_OUTPUT.PUT_LINE('THE DENOMINATOR IS ZERO');
B:=A;
C:=A/B;
DBMS_OUTPUT.PUT_LINE(C);
END;

VALUE error;
---------------

DECLARE
EMPNUM NUMBER(3);
NAME VARCHAR2(10);
NO NUMBER:=&NO;
BEGIN
SELECT EMPNO,ENAME INTO EMPNUM,NAME FROM EMP WHERE EMPNO=NO;
DBMS_OUTPUT.PUT_LINE(EMPNUM||' '||NAME);
EXCEPTION
WHEN VALUE_ERROR THEN
DBMS_OUTPUT.PUT_LINE('WIDTH IS NOT SUFFICIENT');
DECLARE
ENUM EMP.EMPNO%TYPE;
115

BEGIN
SELECT EMPNO,ENAME INTO ENUM,NAME FROM EMP WHERE EMPNO=NO ;
DBMS_OUTPUT.PUT_LINE(ENUM||' '||NAME);
END;
END;

INVALID NUMBER;
---------------

DECLARE
NAME VARCHAR2(10):='&NAME';
NUM NUMBER(3);
BEGIN
SELECT TO_NUMBER(NAME) INTO NUM FROM DUAL;
DBMS_OUTPUT.PUT_LINE(NUM);
EXCEPTION
WHEN INVALID_NUMBER THEN
DBMS_OUTPUT.PUT_LINE('INVALID NUMBER IS RAISED');
END;

TOO MANY ROWS:


--------------
DECLARE
NAME emp.ENAME%type;
EJOB EMP.JOB%TYPE:='&JOB';
BEGIN
select ENAME into NAME from emp WHERE JOB=EJOB;
dbms_output.put_line(NAME);
exception
when too_many_rows then
dbms_output.put_line('too many rows are found');
DECLARE
CURSOR C1 IS SELECT ENAME,JOB,SAL FROM EMP WHERE JOB=EJOB;
BEGIN
IF C1%ISOPEN THEN
DBMS_OUTPUT.PUT_LINE('CURSOR IS OPEN');
END IF;
FOR I IN C1 LOOP
DBMS_OUTPUT.PUT_LINE(I.ENAME||' '||I.JOB||' '||I.SAL);
END LOOP;
END;
END;

NO_DATA_FOUND
-------------
DECLARE
NO EMP.EMPNO%TYPE;
NAME EMP.ENAME%TYPE;
SALARY EMP.SAL%TYPE;
DESIG EMP.JOB%TYPE;
BEGIN
SELECT EMPNO,ENAME,SAL,JOB INTO NO,NAME,SALARY,DESIG
FROM EMP WHERE EMPNO=&EMPNO;
IF SQL%FOUND THEN
116

DBMS_OUTPUT.PUT_LINE(NO||' '||NAME||' '||SALARY||' '||DESIG);


END IF;
EXCEPTION
WHEN NO_DATA_FOUND THEN
DBMS_OUTPUT.PUT_LINE('NO DATA FOUND');
DECLARE
NEWNO EMP.EMPNO%TYPE;
NAME EMP.ENAME%TYPE;
DESIG EMP.JOB%TYPE;
BEGIN
SELECT ENAME,JOB INTO NAME,DESIG FROM EMP WHERE EMPNO=&NEWNO;
DBMS_OUTPUT.PUT_LINE(NAME||' '||dESIG);
END;
END;

INVALID CURSOR(OPENING IN LOOP)


--------------
DECLARE
CURSOR C1 IS SELECT * FROM EMP;
A EMP%ROWTYPE;
BEGIN
LOOP
FETCH C1 INTO A;
OPEN C1;
EXIT WHEN C1%NOTFOUND;
DBMS_OUTPUT.PUT_LINE(A.ENAME||' '||A.JOB||' '||A.SAL);
END LOOP;
CLOSE C1;
EXCEPTION
WHEN INVALID_CURSOR THEN
DBMS_OUTPUT.PUT_LINE('INVALID CURSOR');
END;

CURSOR_ALREADY_OPEN
--------------------
DECLARE
CURSOR C1 IS SELECT * FROM EMP ;
A C1%ROWTYPE;
BEGIN
open c1;
LOOP
OPEN C1;
FETCH C1 INTO A;
EXIT WHEN C1%NOtFOUND;
DBMS_OUTPUT.PUT_LINE(a.sal||' '||a.ename);
END LOOP;
CLOSE C1;
exception
when cursor_already_open then
dbms_output.put_line('cursor already openED');
END;

WHEN OTHERS
117

------------
DESC TEMP
A VARCHAR2(10)
B VARCHAR2(25)
C VARCHAR2(25)

DECLARE
ENO NUMBER(4);
NAME VARCHAR2(10);
DEPNO NUMBER(3);
ACODE NUMBER(4);
BMSG VARCHAR2(40);
EMPNO NUMBER(4);
BEGIN
SELECT EMPNO,ENAME,DEPTNO INTO ENO,NAME,DEPNO FROM EMP
WHERE empno=&empno;
DBMS_OUTPUT.PUT_LINE(ENO||' '||NAME||' '||DEPNO);
EXCEPTION
WHEN OTHERS THEN
ACODE:=SQLCODE;
BMSG:=SQLERRM;
DBMS_OUTPUT.PUT_LINE('ACODE:'||' '||ACODE||' '||BMSG);
--INSERT INTO temp VALUES(ACODE,BMSG ,'asds');
END;

DUP_VAL_ON_INDEX
-----------------
create table temp(a number(3) primary key,
b varchar2(10),c varchar2(10));

declare
dno dept.deptno%type;
dname dept.dname%type;
loc dept.loc%type;
begin
insert into DEPT values(&deptno,'&dname','&loc');
exception
when dup_val_on_index then
dbms_output.put_line('DUP_VALUES_ON_INDEX');
end;

USER_DEFINED_EXCEPTION
----------------------

DECLARE
SALARY EMP.SAL%TYPE;
COM EMP.COMM %TYPE;
MIS_COMM EXCEPTION;
NETSAL NUMBER(7);
BEGIN
SELECT SAL,COMM INTO SALARY,COM FROM EMP WHERE EMPNO=&N;
DBMS_OUTPUT.PUT_LINE(SALARY||' '||COM);
IF COM IS NULL THEN
118

RAISE MIS_COMM;
ELSE
NETSAL:=SALARY+COM;
DBMS_OUTPUT.PUT_LINE(SALARY||' '||COM||' '||NETSAL);
END IF;
EXCEPTION
WHEN MIS_COMM THEN
DBMS_OUTPUT.PUT_lINE('ORA421'||' '||'MISS_COMM EXCEPTION');
END;

PARAMETER(ERROR)
----------
DECLARE
I EMP%ROWTYPE;
CURSOR C1(TEMPENO NUMBER) IS
SELECT * FROM EMP WHERE EMPNO=TEMPENO;
BEGIN
OPEN C1(7499);
FETCH C1 INTO I ;
INSERT INTO EMP(EMPNO,ENAME,DEPTNO) VALUES(I.EMPNO,I.ENAME,I.DEPTNO);
--EXIT WHEN C1%NOT FOUND;
--END LOOP;
END;

WEAK CURSOR(NO RETURN TYPE DECLARATION)


---------------------------------------
DECLARE
TYPE T1 IS REF CURSOR;
T2 T1;
A EMP%ROWTYPE;
BEGIN
OPEN T2 FOR SELECT * FROM EMP;
LOOP
FETCH T2 INTO A;
EXIT WHEN T2%NOTFOUND;
DBMS_OUTPUT.PUT_LINE(A.EMPNO);
119

END LOOP;
CLOSE T2;
END;

DATA BASE TRIGGER:


------------------
BEFORE/AFTER INSERT OR UPDATE OR DELETE ON TABLENAME FOR EACH ROW

(ERROR)
CREATE OR REPLACE TRIGGER T1 BEFORE INSERT ON EMP
DECLARE
A VARCHAR2(10);
BEGIN
SELECT TO_CHAR(SYSDATE,'DAY') INTO A FROM DUAL;
IF A ='TUESDAY' THEN
RAISE_APPLICATION_ERROR(-20909,'INSERTION NOT POSSIBLE');
END IF;
END;

ERROR NO: -20000 TO -20999

(FIND T1 OR T2 )(OK)
CREATE OR REPLACE TRIGGER T2 BEFORE INSERT ON EMP FOR EACH ROW
DECLARE
A NUMBER;
BEGIN
SELECT COUNT(*) INTO A FROM EMP WHERE DEPTNO=:NEW.DEPTNO;
IF A>=1 THEN
RAISE_APPLICATION_ERROR(-20101,'PRIMARY KEY VIOLATION');
END IF;
END;

CREATE OR REPLACE TRIGGER DELDEPT


AFTER DELETE ON DEPT
FOR EACH ROW
BEGIN
DELETE EMP WHERE DEPTNO=:OLD.DEPTNO;
DBMS_OUTPUT.PUT_LINE('PARENT CHILD DELETED');
END;

CREATE OR REPLACE TRIGGER CHECK_SAL


BEFORE update ON emp
FOR EACH ROW
BEGIN
IF :NEW.SAL<1000 OR :NEW.SAL>5000 THEN
RAISE_APPLICATION_ERROR(-20001,'CHECK SAL ');
END IF;
END;

CREATE OR REPLACE TRIGGER T1 BEFORE INSERT ON DEPT FOR EACH ROW


DECLARE
A DEPT.DEPTNO%TYPE;
120

BEGIN
SELECT COUNT(DEPTNO) INTO A FROM DEPT
WHERE DEPTNO=:NEW.DEPTNO;
IF A>=1 THEN
RAISE_APPLICATION_ERROR(-20001,'MASTER EXIST');
END IF;
EXCEPTION
WHEN NO_DATA_FOUND THEN
DBMS_OUTPUT.PUT_LINE('-20001 NO MASTER RECORD');
END;

(MUTATING ERROR)
CREATE OR REPLACE TRIGGER T3 AFTER UPDATE ON EMP FOR EACH ROW
DECLARE
A NUMBER(1);
BEGIN
SELECT COUNT(*) INTO A FROM EMP WHERE DEPTNO=:old.DEPTNO;
dbms_output.put_line('new.depttno'||' '||:old.deptno);
IF A>1 THEN
RAISE_APPLICATION_ERROR(-20001,'UPDATED');
END IF;
END ;

VARRAY SELECT STATEMENT


-----------------------
/*DECLARE
CURSOR C1 IS SELECT * FROM TABLENAME;
A CI%ROWTYPE;
BEGIN
FOR I IN C1
LOOP
DBMS_OUTPUT.PUT_LINE('SDFS :'|| );
FOR I IN C1.COUNT
LOOP
DBMS_OUTPUT.PUT_LINE(SDA);
END LOOP;
END LOOP */
END;

NESTED TABLES:
--------------

SELECT X.NAME FROM THE (SELECT EMPL FROM DEPTNEST WHERE DNO=10) X
WHERE X.NAME='YYYY';

SUBPROGRAMS

1. PROCEDURE Syntax:

CREATE OR REPLACE PROCEDURE <PROCNAME> (PARAMETERLIST) IS


<DECLARATION>
BEGIN
121

EXECUTABLE STATEMENTS
EXCEPTION HANDLERS
END;

Eg.:

CREATE OR REPLACE PROCEDURE P1 (A NUMBER,B NUMBER) IS


COMMISSION NUMBER;
NULL_COMM EXCEPTION;
BEGIN
SELECT COMM INTO COMMISSION FROM EMP WHERE EMPNO=A;
IF COMMISSION IS NULL THEN
RAISE NULL_COMM;
ELSE
UPDATE EMP SET COMM=SAL+B WHERE EMPNO=A;
END IF;
EXCEPTION WHEN NULL_COMM THEN
DBMS_OUTPUT.PUT_LINE('THE VALUE COMM IS NULL');
END;

EXEC P1(7499,1000);

1.1 IN PARAMETER

CREATE OR REPLACE PROCEDURE P2 (NO IN NUMBER) IS PRICE NUMBER;


BEGIN
SELECT ACTUALPRICE INTO PRICE FROM ITEM WHERE ITEMID=NO;
DBMS_OUTPUT.PUT_LINE('ORIGINAL PRICE IS'||'
'||TO_CHAR(PRICE));
IF PRICE IS NULL THEN
DBMS_OUTPUT.PUT_LINE('PRICE IS NULL');
END IF;
END;

EXEC P2(10);

1.2 IN OUT PARAMETER

CREATE OR REPLACE PROCEDURE P3 (INNER IN NUMBER, A OUT NUMBER)


IS ID NUMBER;
BEGIN
SELECT DEPTNO INTO ID FROM EMP WHERE EMPNO=INNER;
IF ID<40 THEN
A:=50;
END IF;
END;

DECLARE
INNER NUMBER;
A NUMBER;
BEGIN
P3 (7499,A);
122

DBMS_OUTPUT.PUT_LINE('THE OUT VALUE IS '||' '||TO_CHAR(A));


END;

CREATE OR REPLACE PROCEDURE SAMPLE (A IN NUMBER,B IN OUT NUMBER)


IS ID NUMBER;
BEGIN
SELECT ORDID,PRODID INTO ID ,B FROM ITEM WHERE ITEMID=A;
IF B<500 THEN
B:=B+100;
END IF;
END;

DECLARE
A NUMBER;
B NUMBER;
BEGIN
SAMPLE(10,B);
DBMS_OUTPUT.PUT_LINE('B VALUE IS'||' '||B);
END;

FUNCTIONS
---------
<CREATE OR REPLACE FUNCTION NAME> {(ARGUMENT) - IN ,OUT ,IN OUT}
RETURN DATATYPE IS >
DECLARATION
BEGIN
EXECUTABLE STATEMENTS
EXCEPTION
EXCEPTION HANDLERS
END;

create or replace function f1 return number is


a emp.sal%type;
begin
SELECT SAL INTO A FROM EMP WHERE ENAME='ALLEN';
RETURN A;
END;

DECLARE
B NUMBER;
BEGIN
B:=F1;
DBMS_OUTPUT.PUT_LINE(B);
END;

CREATE OR REPLACE FUNCTION FUN(ID NUMBER,AMOUNT NUMBER)


RETURN BOOLEAN IS
MINI NUMBER;
MAXI NUMBER;
BEGIN
SELECT MINPRICE,STDPRICE INTO MINI,MAXI FROM PRICE WHERE PRODID=ID;
RETURN (MINI>=AMOUNT) OR (MAXI>=AMOUNT);
END;
123

TO EXECUTE IT:

DECLARE
ID NUMBER;
AMOUNT NUMBER;
REMARK BOOLEAN;
BEGIN
ID:=&A;
AMOUNT:=&B;
REMARK:=FUN(ID,AMOUNT);
IF REMARK=TRUE THEN
DBMS_OUTPUT.PUT_LINE('TRUE');
ELSE
DBMS_OUTPUT.PUT_LINE('FALSE');
END IF;
END;

CREATE OR REPLACE FUNCTION FUN(N VARCHAR2)


RETURN VARCHAR2 IS
J VARCHAR2(10);
BEGIN
SELECT JOB INTO J FROM EMP WHERE ENAME=N;
RETURN J;
END;

SELECT FUN('BLAKE') FROM DUAL;

IN PARAMETER
-------------
CREATE OR REPLACE FUNCTION F1(NAME IN VARCHAR2) RETURN NUMBER IS
A EMP.SAL%TYPE;
BEGIN
SELECT SAL INTO A FROM EMP WHERE ENAME=NAME;
RETURN A;
END;

DECLARE
B NUMBER;
BEGIN
B:=F1('&A');
DBMS_OUTPUT.PUT_LINE(B);
END;

IN AND OUT
----------
CREATE OR REPLACE FUNCTION F1(NAME IN VARCHAR2,B OUT VARCHAR2) RETURN
NUMBER IS
A EMP.SAL%TYPE;
BEGIN
SELECT SAL,JOB INTO A,B FROM EMP WHERE ENAME=NAME;
RETURN A;
END;

DECLARE
124

A NUMBER;
JOB VARCHAR2(20);
BEGIN
A:=F1('&c',JOB);
DBMS_OUTPUT.PUT_LINE(A||' '||JOB);
END;

IN OUT
------
CREATE OR REPLACE function F1(A IN number,c OUT NUMBER) RETURN NUMBER
IS
B EMP.COMM%TYPE;
BEGIN
SELECT SAL,COMM INTO sal1,comm1 FROM EMP WHERE EMPNO=A;
RETURN sal1;
END;

/* ERROR */
DECLARE
M2 NUMBER(5);
M3 NUMBER;
M1 NUMBER;
SALARY NUMBER;
BEGIN
M1:=F1(&M2,M3);
DBMS_OUTPUT.PUT_LINE(M2||' '||SALARY);
END;

PACKAGE SPECIATION
-------------------
CREATE OR REPLACE PACKAGE PACK1 IS
PROCEDURE P1;
FUNCTION F1 RETURN NUMBER;
A NUMBER;
END PACK1;

CREATE OR REPLACE PACKAGE BODY PACK1 IS


PROCEDURE P1 IS
BEGIN
DBMS_OUTPUT.PUT_LINE('P1 PACKAGE');
END P1;
FUNCTION F1 RETURN NUMBER IS
BEGIN
A:=1000;
RETURN A;
END F1;
END PACK1;

DECLARE
N NUMBER;
BEGIN
N:=PACK1.F1;
DBMS_OUTPUT.PUT_LINE(N);
PACK1.P1;
125

END;

/*
CREATE OR REPLACE PACKAGE PACK2 IS
PROCEDURE DDEP;
FUNCTION BALANCE RETURN NUMBER;
NAME VARCHAR2(15);
END PACK2;

CREATE PACKAGE BODY PACK2 IS


FUNCTION BALANCE (NAME IN VARCHAR2)
RETURN NUMBER AS
BALANCE NUMBER(10,2);
BEGIN
SELECT SAL INTO BALANCE FROM EMP WHERE ENAME=NAME;
RETURN(BALANCE);
EXCEPTIONS
WHEN NO_DATA_FOUND THEN
RAISE_APPLICATION_ERROR(-20101,'NO WORKER ON THAT NAME');
END PACK2;
PROCEDURE DDEP(NAME IN VARCHAR2) IS
BEGIN
INSERT INTO DEPT(DEPTNO,DNAME,LOC) VALUES(10,NAME,NULL);
END DDEP;
END PACK2; */

PL/SQL COMPOSITE DATA TYPE


--------------------------

DECLARE
TYPE T1 IS TABLE OF EMP.sal %TYPE
INDEX BY BINARY_INTEGER;
M BINARY_INTEGER :=1;
T2 T1;
BEGIN
FOR I IN 1..20
LOOP
T2(M) :=I*10;
DBMS_OUTPUT.PUT_LINE(T2(M)||' '||m);
M:=M+1;
END LOOP;
END;

DECLARE
TYPE T1 IS TABLE OF EMP.ENAME%TYPE
INDEX BY BINARY_INTEGER;
M BINARY_INTEGER:=0;
T2 T1;
BEGIN
FOR I IN (SELECT ENAME FROM EMP )
LOOP
T2(M):=I.ENAME;
--INSERT INTO DEPT1(DNAME) VALUES(T2(M));
dbms_output.put_line(t2(m)||' '||m);
126

M:=M+1;
END LOOP;
END;

DECLARE
TYPE T1 IS TABLE OF EMP.ENAME%TYPE
INDEX BY BINARY_INTEGER;
M BINARY_INTEGER :=1;
T2 T1;
T3 T1;
BEGIN
FOR I IN(SELECT ENAME FROM EMP)
LOOP
T2(M) :=I.ENAME;
T3(M):=T2;
DELETE FROM EMP WHERE ENAME=T2(M);
DBMS_OUTPUT.PUT_LINE(T3(M));
M:=M+1;
END LOOP;
END;

DECLARE
TYPE T1 IS TABLE OF DEPT%ROWTYPE
INDEX BY BINARY_INTEGER;
T2 T1;
M BINARY_INTEGER :=1;
BEGIN
FOR I IN (SELECT * FROM DEPT)
LOOP
T2(M).DEPTNO :=I.DEPTNO;
T2(M).DNAME :=I.DNAME;
T2(M).LOC :=I.LOC;
DBMS_OUTPUT.PUT_LINE(T2(M).DEPTNO||' '||T2(M).DNAME||' '||T2(M).LOC);
M :=M+1;
END LOOP;
END;

--RECORD(ONE ROW)

DECLARE
TYPE T1 IS RECORD
(A NUMBER(3),B VARCHAR2(30),C VARCHAR2(30));
T2 T1;
BEGIN
SELECT * INTO T2 FROM DEPT WHERE DEPTNO=10;
DBMS_OUTPUT.PUT_LINE(T2.A||T2.B||T2.C);
END;

BEGIN
SELECT * FROM EMP;
END;

-----------------------------------------

BEGIN
UPDATE EMP SET SAL=SAL+2000;
127

END;

-----------------------------------------

DECLARE
I NUMBER :=7788;
J NUMBER :=10000;
BEGIN
UPDATE EMP SET SAL=J WHERE EMPNO=I;
END;

-----------------------------------------

DECLARE
I NUMBER:=&I;
J NUMBER:=&J;
BEGIN
UPDATE EMP SET SAL=J WHERE EMPNO=I;

------------------------------------------

DECLARE
I NUMBER;
J NUMBER;
BEGIN
UPDATE EMP SET SAL=&J WHERE EMPNO=&I;
END;

------------------------------------------

FOR LOOP
--------

FOR <VAR> IN <MIN>..<MAXVALUE>


LOOP
-
-
-
END LOOP;

-------------------------------------------
declare
begin
FOR I IN 1..5
LOOP
INSERT INTO TEMP VALUES (I);
END LOOP;
end;

-------------------------------------------

WHILE LOOP
----------

WHILE <CONDITION>
LOOP
-
128

-
-
END LOOP;

-------------------------------------------

DECLARE
A NUMBER(2);
BEGIN
A:=&A;
FOR COUNT IN 1..A
LOOP
INSERT INTO TEMP VALUES (COUNT);
END LOOP;
END;

-------------------------------------------

DECLARE
I NUMBER:=10;
BEGIN
WHILE I <=15
LOOP
INSERT INTO TEMP VALUES (I);
I:=I+1;
END LOOP;
END;
-------------------------------------------

DECLARE
I NUMBER:=1;
BEGIN
WHILE I<=10
LOOP
INSERT INTO TEMP VALUES(I,'XXXX');
IF I>5 THEN
EXIT;
END IF;
I:=I+1;
END LOOP;
INSERT INTO TEMP VALUES(I,'YYYY');
END;

-------------------------------------------

GO TO STATEMENT
---------------

DECLARE
I NUMBER:=1;
BEGIN
WHILE I<=10
LOOP
INSERT INTO TEMP VALUES(I,'XXXX');
IF I=5 THEN
GOTO PROC;
END IF;
129

I:=I+1;
END LOOP;
<<PROC>>
INSERT INTO TEMP VALUES(I,'PROC');
END;

------------------------------------------------------------

USING INTO CLASS


----

DECLARE
TEMP NUMBER: = &TEMPNO;
TEMPSAL NUMBER;
BEGIN
SELECT SAL INTO TEMPSAL FROM EMP WHERE EMPNO=TEMP;
DBMS_OUTPUT.PUT_LINE(TEMPSAL);
END;

SET SERVEROUT ON;


------------------------------------------------------------
////////////////(UPDATE ERROR)
DECLARE
TNO NUMBER:=&TEMPNO;
TEMPSAL NUMBER;
TEMPCOMM NUMBER;
BEGIN
SELECT SAL,COMM INTO TEMPSAL,TEMPCOMM FROM EMP WHERE
EMPNO=TNO;
IF TEMPCOMM >1000 AND TEMPSAL <=5000 THEN
UPDATE EMP SET SAL=SAL+2000 WHERE EMPNO=TNO;
ELSIF TEMPSAL >2000 THEN
UPDATE EMP SET SAL=SAL+1000 WHERE EMPNO=TNO;
END IF;
END;

-------------------------------------------------------------------

DECLARE
TEMPEMPNO NUMBER:=&TEMPEMPNO;
TEMPHIREDATE DATE;
TEMPNAME VARCHAR2(20);
BEGIN
SELECT HIREDATE,ENAME INTO TEMPHIREDATE,TEMPNAME FROM EMP
WHERE EMPNO=TEMPEMPNO;
IF TEMPHIREDATE >='01-JAN-80' AND TEMPHIREDATE <='30-JAN-85'
THEN
UPDATE EMP SET COMM=COMM+COMM*0.1 WHERE EMPNO=TEMPEMPNO;
END IF;
END;

-------------------------------------------------------------------

DECLARE
TEMPEMPNO NUMBER:=&TEMPEMPNO;
TEMPDEPTNO NUMBER;
BEGIN
130

SELECT DEPTNO INTO TEMPDEPTNO WHERE EMPNO=TEMPEMPNO;


IF TEMPDEPTNO=10 THEN
UPDATE EMP SET SAL=SAL+1000 WHERE EMPNO=TEMPEMPNO;
ELSIF TEMPDEPTNO=20 THEN
UPDATE EMP SET SAL=SAL+2000 WHERE EMPNO=TEMPEMPNO;
ELSIF TEMPDEPTNO=30 THEN
UPDATE EMP SET SAL=SAL+3000 WHERE EMPNO=TEMPEMPNO;
ELSE
UPDATE EMP SET SAL=SAL+4000 WHERE EMPNO=TEMPEMPNO;
END IF;
END;

-------------------------------------------------------------------

DECLARE
A NUMBER;
B NUMBER;
C NUMBER;
BEGIN
A:=&A;
B:=&B;
C:=A+B;
DBMS_OUTPUT.PUT_LINE(C);
END;
------------------------------------------------------------------------
-
%TYPE
--------

DECLARE
SALARY EMP.SAL%TYPE;
DOJ EMP.HIREDATE%TYPE;
BEGIN
SELECT SAL,HIREDATE INTO SALARY,DOJ FROM EMP WHERE EMPNO=7900;
DBMS_OUTPUT.PUT_LINE(SALARY||' '||DOJ);
END;
------------------------------------------------------------------------

You might also like