Download as doc, pdf, or txt
Download as doc, pdf, or txt
You are on page 1of 18

SQL Assignments

EMP Table Structure:

Name Null? Type


------------------------------- -------- ----------------------
EMPNO NOT NULL NUMBER(4), Primary Key
ENAME VARCHAR2(10)
JOB VARCHAR2(9)
MGR NUMBER(4), may/may not any EMPNO
HIREDATE DATE
SAL NUMBER(7,2)
COMM NUMBER(7,2)
DEPTNO NUMBER(2) foreign key of DEPT table

Records in EMP Table

EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO


--------- ---------- --------- --------- --------- --------- --------- --------- ------------ --------------
7369 SMITH CLERK 7902 17-DEC-80 800 20
7499 ALLEN SALESMAN 7698 20-FEB-81 1600 300 30
7521 WARD SALESMAN 7698 22-FEB-81 1250 500 30
7566 JONES MANAGER 7839 02-APR-81 2975 20
7654 MARTIN SALESMAN 7698 28-SEP-81 1250 1400 30
7698 BLAKE MANAGER 7839 01-MAY-81 2850 30
7782 CLARK MANAGER 7839 09-JUN-81 2450 10
7788 SCOTT ANALYST 7566 19-APR-87 3000 20
7839 KING PRESIDENT 17-NOV-81 5000 10
7844 TURNER SALESMAN 7698 08-SEP-81 1500 0 30
7876 ADAMS CLERK 7788 23-MAY-87 1100 20
7900 JAMES CLERK 7698 03-DEC-81 950 30
7902 FORD ANALYST 7566 03-DEC-81 3000 20
7934 MILLER CLERK 7782 23-JAN-82 1300 10

DEPT Table Structure:

Name Null? Type


------------------------------- -------- ----
DEPTNO NOT NULL NUMBER(2), Primary key
DNAME VARCHAR2(14)
LOC VARCHAR2(13)

Records in DEPT Table:

DEPTNO DNAME LOC


--------- -------------- -------------
10 ACCOUNTING NEW YORK
20 RESEARCH DALLAS
30 SALES CHICAGO
40 OPERATIONS BOSTON
Assignment # 01

1. Display the name, deptno, dname for all employees.


2. Create a unique listing of all jobs that are in deptno 30. Include the location of dept 30 in the output.
3. Display the employee name, dept name and the location of all employees who earn a commission.
4. Display the employee name, dept name for all employees who have an ‘A’ in their name.
5. Display the employee name, job, deptno, dept name for all employees who work in DALLAS.
6. Display the employee name, empno along with their manager’s name and manager no.
7. Modify query 6 to display all employees including king, who has no manager.
8. Display the employee name of all the employees that work in the same deptno as a given
employee.
9. Display the employee name, job, dept name, salary and grade for all employees.
10. Display the employee name, and hire date of any employee hired after BLAKE.
11. Display the employee name, and hire date along with their manager’s name and hire date of all
employees hired before their manager.
12. Find the second highest salary from emp table.

Assignment #02

1. List the names of analysts and salesmen.


2. List details of employees who have joined before 30 Sep 81.
3. List names of employees who are not managers.
4. List the names of employees whose employee numbers are 7369, 7521, 7839,
7934, 7788.
5. List employees not belonging to department 30, 40, or 10.
6. List employee names for those who have joined between 30 June and 31 Dec. ‘81.
7. List the different designations in the company.
8. List the names of employees who are not eligible for commission.
9. List the name and designation of the employee who does not report to anybody.
10. List the employees not assigned to any department.
11. List the employees who are eligible for commission.
12. List employees whose names either start or end with “S”.
13. List names of employees whose names have “i” as the second character.
14. List the number of employees working with the company.
15. List the number of designations available in the EMP table.
16. List the total salaries paid to the employees.
17. List the maximum, minimum and average salary in the company.
18. List the maximum salary paid to a salesman.

Assignment #03

1) List the number of employees and average salary for employees in department 20.
2) List name, salary and PF amount of all employees. (PF is calculated as 10% of
basic salary)
3) List names of employees who are more than 2 years old in the company.
4) List the employee details in the ascending order of their basic salary.
5) List the employee name and hire date in the descending order of the hire date.
6) List employee name, salary, PF, HRA, DA and gross; order the results in the
ascending order of gross. HRA is 50% of the salary and DA is 30% of the salary.
7) List the department numbers and number of employees in each department.
8) List the department number and total salary payable in each department.
9) List the jobs and number of employees in each job. The result should be in the
descending order of the number of employees.
10) List the total salary, maximum and minimum salary and average salary of the
employees jobwise.
11) List the total salary, maximum and minimum salary and average salary of the
employees, for department 20.
12) List the total salary, maximum and minimum salary and average salary of the
employees jobwise, for department 20 and display only those rows having an
average salary > 1000

Solutions Assignment # 01:


1. SELECT ename,emp.deptno,dname
FROM emp,dept
WHERE emp.deptno=dept.deptno;
2. SELECT distinct job, loc
FROM emp,dept
WHERE emp.deptno=dept.deptno
and emp.deptno=30;
3. SELECT emp.ename,dept.dname,dept.loc
FROM emp,dept
WHERE emp.deptno=dept.deptno
and emp.comm>0
4. SELECT emp.ename,dept.dname
FROM emp,dept
WHERE emp.deptno=dept.deptno
and emp.ename like '%A%'
5. SELECT emp.ename,emp.job,dept.deptno,dept.dname
FROM emp,dept
WHERE emp.deptno=dept.deptno
and dept.loc='DALLAS'
6. SELECT emp1.ename "EMPLOYEE",emp1.empno "Employee No",emp2.ename
"MANAGR", emp2.empno "Manager no”
FROM emp emp1,emp emp2
WHERE emp1.mgr=emp2.empno
7. SELECT emp1.ename "EMPLOYEE", emp1.empno "Employee No", emp2.ename
"MANAGR", emp2.empno "Manager no”
FROM emp emp1, emp emp2
WHERE emp1.mgr=emp2.empno(+)
8. SELECT ENAME, DEPTNO FROM EMP WHERE
DEPTNO IN(select deptno from emp where ename='&ename')
9.

10. SELECT ENAME,HIREDATE


FROM EMP
WHERE HIREDATE>
(SELECT HIREDATE
FROM EMP
WHERE ENAME='BLAKE')
11. SELECT EMP1.ENAME, EMP1.HIREDATE, EMP2.ENAME, EMP2.HIREDATE
FROM EMP EMP1, EMP EMP2
WHERE EMP1.MGR=EMP2.EMPNO
AND EMP1.HIREDATE<EMP2.HIREDATE
12 SELECT MAX(sal) “2nd Highest Salary”
FROM emp
WHERE sal NOT IN (SELECT MAX (sal) FROM emp);

Assignment #02

1. List the names of analysts and salesmen.


2. List details of employees who have joined before 30 Sep 81.
3. List names of employees who are not managers.
4. List the names of employees whose employee numbers are 7369, 7521, 7839,
7934, 7788.
5. List employees not belonging to department 30, 40, or 10.
6. List employee names for those who have joined between 30 June and 31 Dec. ‘81.
7. List the different designations in the company.
8. List the names of employees who are not eligible for commission.
9. List the name and designation of the employee who does not report to anybody.
10. List the employees not assigned to any department.
11. List the employees who are eligible for commission.
12. List employees whose names either start or end with “S”.
13. List names of employees whose names have “i” as the second character.
14. List the number of employees working with the company.
15. List the number of designations available in the EMP table.
16. List the total salaries paid to the employees.
17. List the maximum, minimum and average salary in the company.
18. List the maximum salary paid to a salesman.

Solution Assignment #02:

1. SELECT ename FROM emp


WHERE job IN('ANALYST','SALESMAN');
2. SELECT * FROM Emp
WHERE HIREDATE < '30-SEP-1981';
3. SELECT ename FROM emp
MINUS
SELECT ename FROM emp
WHERE empno IN (SELECT mgr FROM emp);
OR SELECT ename FROM emp WHERE empno NOT IN (SELECT mgr FROM EMP);

4. SELECT ename FROM emp


WHERE empno IN (7369, 7521, 7839,7934, 7788)
5. SELECT ENAME FROM EMP
WHERE DEPTNO NOT IN(30,10,40)
6. SELECT ENAME FROM EMP
WHERE HIREDATE BETWEEN '30-JUN-1981' AND '31-DEC-1981';
7. SELECT DISTINCT JOB FROM EMP;

8. SELECT ENAME FROM EMP


WHERE COMM<=0;
9.
10. SELECT ENAME FROM EMP
WHERE DEPTNO not IN(SELECT DEPTNO FROM EMP);
11. SELECT ENAME FROM EMP
WHERE COMM>0;
12 SELECT ENAME FROM EMP WHERE ENAME LIKE 'S%' OR ENAME LIKE '%S'

13. SELECT ENAME FROM EMP


WHERE ENAME LIKE '_I%'

14. SELECT COUNT(EMPNO) FROM EMP;


15. SELECT COUNT(DISTINCT JOB) FROM EMP;
16. SELECT SUM(SAL) FROM EMP;
17. SELECT MAX(SAL), MIN(SAL), AVG(SAL) FROM EMP;
18. SELECT MAX(SAL) FROM EMP
WHERE JOB='SALESMAN';

Assignment #03

1) List the number of employees and average salary for employees in department 20.
2) List name, salary and PF amount of all employees. (PF is calculated as 10% of
basic salary)
3) List names of employees who are more than 2 years old in the company.
4) List the employee details in the ascending order of their basic salary.
5) List the employee name and hire date in the descending order of the hire date.
6) List employee name, salary, PF, HRA, DA and gross; order the results in the
ascending order of gross. HRA is 50% of the salary and DA is 30% of the salary.
7) List the department numbers and number of employees in each department.
8) List the department number and total salary payable in each department.
9) List the jobs and number of employees in each job. The result should be in the
descending order of the number of employees.
10) List the total salary, maximum and minimum salary and average salary of the
employees jobwise.
11) List the total salary, maximum and minimum salary and average salary of the
employees, for department 20.
12) List the total salary, maximum and minimum salary and average salary of the
employees jobwise, for department 20 and display only those rows having an
average salary > 1000

Solution Assignment #03:

1) SELECT COUNT(empno),AVG(sal)
FROM emp WHERE deptno=20;
2) SELECT ENAME,SAL "SALARY",SAL*.1 "PF"
FROM EMP;
3) SELECT ENAME FROM EMP
WHERE ROUND(SYSDATE-HIREDATE)>720
4) SELECT * FROM EMP
ORDER BY SAL;
5) SELECT ENAME,HIREDATE FROM EMP
ORDER BY HIREDATE DESC;
6) SELECT ENAME,SAL,SAL*.1 "PF",SAL*.5 "HRA", SAL*.3 "DA",
SAL+SAL*.1+SAL*.5+SAL*.3 "GROSS"
FROM EMP
ORDER BY SAL+SAL*.1+SAL*.5+SAL*.3;
7) SELECT DEPTNO,COUNT(EMPNO)
FROM EMP
GROUP BY DEPTNO;
8) SELECT DEPTNO,SUM(SAL)
FROM EMP
GROUP BY DEPTNO;
9) SELECT JOB, COUNT(EMPNO)
FROM EMP
GROUP BY JOB
ORDER BY COUNT(EMPNO);
10) SELECT JOB,SUM(SAL),MAX(SAL),MIN(SAL),AVG(SAL)
FROM EMP
GROUP BY JOB;
11) SELECT DEPTNO,SUM(SAL),MAX(SAL),MIN(SAL),AVG(SAL)
FROM EMP
GROUP BY DEPTNO
HAVING DEPTNO=20;
12) SELECT JOB,SUM(SAL),MAX(SAL),MIN(SAL),AVG(SAL)
FROM EMP
GROUP BY JOB,DEPTNO
HAVING DEPTNO=20 AND AVG(SAL)>1000;

JOIN :

-- Cross Join or Cartesian product of two tables


/*

SELECT emp.empno "Employee No.",dept.deptno "Department No."


FROM emp,dept;

-- The above query display all tuples(specific attributes) with the relation that one tuple(record) of 1st table
is associated with all the tuples of other table and similerly all the tuples of 1st table are associated with
other table.

*/

/*
-- Inner(Equi) join between two table

SELECT emp.empno "Employee No.",dept.dname "Department Name"


FROM emp,dept
WHERE emp.deptno=dept.deptno;

-- The above query is To display all employee no. and the corresponding department name.

*/

-- SelfJoin .....

-- Find all the employee name and their corresponding manager name.

SELECT E.ename "Employee", M.ename "Manager"


FROM emp E, emp M
WHERE E.mgr=M.empno and E.ename<>M.ename;

-- Outer join(LEFT) between two table


/*

SELECT emp.empno "Employee No.",dept.dname "Department Name"


FROM emp,dept
WHERE emp.deptno=dept.deptno(+);
*/

-- Outer join(Right) between two table

/*
SELECT emp.empno "Employee No.",dept.dname "Department Name"
FROM dept,emp
WHERE emp.deptno(+)=dept.deptno;

*/

PL/SQL Block:

CURSOR:

/* Write a cursor to find first 5 employee getting highest salary */

declare
cursor cur_emp_ord is select empno,sal from emp order by sal desc;
meno emp.empno%type;
msal emp.sal%type;
begin
open cur_emp_ord;
dbms_output.put_line('Employee No. Salary');
dbms_output.put_line('------------ ------- ');
loop
fetch cur_emp_ord into meno,msal;
exit when (cur_emp_ord%rowcount-1)=5;
dbms_output.put_line(' '||meno||' '||msal);
end loop;
close cur_emp_ord;
end;
/

/* Write a cursor to Calculate DA and store in the DA feild. */

declare
cursor cur_emp_da is select empno,sal from emp;
meno emp.empno%type;
msal emp.sal%type;
mda emp.da%type;
begin
open cur_emp_da;
loop
fetch cur_emp_da into meno,msal;
exit when cur_emp_da%notfound;
update emp set da=msal*.74 where empno=meno;
end loop;
close cur_emp_da;
end;
/

PL/SQL Assignment:
Write a PL/SQL Block
1) To find the largest from the three numbers.
2) To find the factorial value of any number.
3) To print the Fibonacii Series of n numbers.
4) To compute the area of the circle with radius 2,4,6………40. and store the data into a table ‘circle’
containing attributes ‘radius’ and ‘area’.
5) To accept the marks for three subjects from a student, calculate its average. If average <50 then print
FAIL, average is between 50 to 60 then Second Division, average is between 60 to 75 then First
Division, average is in between 75 and above then print Distinction.
6) To accept the empno from EMP table and calculate the tax on salary based on the following –
Basic Salary Tax
Less than 1500 5% of Salary
1500.2500 7% of Salary
2501.3500 9% of Salary
3501 and above 10%of Salary.
7) To calculate Gross Salary on the basis of basic salary if DA is 40% of basic, HRA is 20% of basic
and PF deduction is 12% of basic salary, update all the records in emp table.
8) To display all Clerks from emp table using CURSOR.
9) To insert the records of all managers from emp table to newemp and also display on the screen using
CURSOR.
10) To delete all employees belonging to department 50 and check if at least one row has been processed
using SQL%FOUND attribute. Insert the value into a table del_history and see the result.
11) To delete all employees whose job = CLERK and update the emp table with jb = CAPTAIN and sal
= 8000. Check if any row have been processed using SQL%NOTFOUND attribute. If it is true then
ROLLBACK and if it is false then COMMIT.
12) To declare a cursor that selects all employees in a given department and raise the salary by 0.05%
and updates the table and also update another table which keeps track of raised amount.
13) To display the five lowest paid employees.
14) Create a TRIGGER for does not permit deletion of any row from emp table on Sunday.
15) Create a table dupemp with the records those are inserted, updated or deleted from emp table using
TRIGGER.
16) Create a function to calculate factorial of any number.
17) Create a procedure for hike the salary by 10% of all employees.
18) Create a function to calculate simple interest.
19) Create a package for displaying the emp_name, in ascending order of their hiredate, highest salary
and rank.
Solution:
/* 1) To find the largest from the three numbers */

declare
no1 number;
no2 number;
no3 number;

begin
no1:=&no1;
no2:=&no2;
no3:=&no3;
if no1>no2 then
if no1>no3 then
dbms_output.put_line('Largest is '||no1);
else
dbms_output.put_line('Largest is '||no3);
end if;
else
if no2>no3 then
dbms_output.put_line('Largest is '||no2);
else
dbms_output.put_line('Largest is '||no3);
end if;
end if;

end;
/

/* 2) To find the factorial value of any number. */

DECLARE
no number;
fact number:=1;
i number;
BEGIN
no:=&no;
FOR i IN 2..no
LOOP
fact:=fact*i;
end loop;
DBMS_OUTPUT.PUT_LINE('fACTORIAL OF '||no||' IS '||fact);
END;
/

/* 3) To print the Fibonacii Series of n numbers. */

DECLARE
no NUMBER;
fn NUMBER:=0;
sn NUMBER:=1;
nn NUMBER;
cn NUMBER:=2;
BEGIN
no:=&no;
if no=1 then
dbms_output.put_line(fn);
end if;
if no>=2 then
dbms_output.put_line(fn||' , '||sn);
end if;
if no>2 then
loop
nn:=fn+sn;
dbms_output.put_line(nn);
fn:=sn;
sn:=nn;
cn:=cn+1;
exit when cn=no;
end loop;
else
dbms_output.put_line('Wrong entry ');
end if;
end;
/

/* 4) To compute the area of the circle with radius 2,4,6………40. and


store the data into a table ‘circle’ containing attributes ‘radius’ and
‘area’. */

DECLARE
rd circle.radius%type:=2;
ar circle.area%type;
pi constant number:=3.14;
BEGIN
while rd<=40
loop
ar:=pi*rd*rd;
insert into circle values(rd,ar);
rd:=rd+2;
end loop;
end;
/

/* 5) To accept the marks for three subjects from a student,


calculate its average. If average <50 then print FAIL,
average is between 50 to 60 then Second Division,
average is between 60 to 75 then First Division,
average is in between 75 and above then print Distinction.

*/

DECLARE
marks1 number;
marks2 number;
marks3 number;
average number ;
BEGIN
marks1:=&marks1;
marks2:=&marks2;
marks3:=&marks3;
average:=(marks1 + marks2 + marks3)/3;
if average>=75 then
dbms_output.put_line('Distincion');
elsif average>=60 then
dbms_output.put_line('First Division');
elsif average>=50 then
dbms_output.put_line('Second Division');
else
dbms_output.put_line('FAIL');
end if;
end;
/

/*
6) To accept the empno from EMP table and calculate the tax on salary
based on the following –
Basic Salary Tax
Less than 1500 5% of Salary
1500-2500 7% of Salary
2501-3500 9% of Salary
3501 and above 10%of Salary.

*/

DECLARE
eno emp.empno%type;
msal emp.sal%type;
tax number;
BEGIN
eno:=&eno;
select sal into msal from emp where empno=eno;
if msal>3500 then
tax:=msal*0.1;

elsif msal>2500 then


tax:=msal*0.09;

elsif msal>1500 then


tax:=msal*0.07;

else
tax:=msal*0.05;

end if;
dbms_output.put_line('Tax = '||tax);

end;
/

/* 7) To calculate Gross Salary on the basis of basic salary if DA is 40% of basic, HRA is 20% of basic
and PF deduction is 12% of basic salary.

*/

DECLARE
basic number;
da number;
hra number;
pf number;
gross number;
BEGIN
basic:=&Basic;
da:=basic*0.4;
hra:=basic*0.2;
pf:=basic*0.12;
gross:=basic+da+hra-pf;
dbms_output.put_line('Gross Salary '||gross);
END;
/

/* 8) To display all Clerks from emp table using CURSOR. */

DECLARE
cursor clerk_emp is select ename from emp where job like 'CLERK';
name emp.ename%type;
BEGIN
open clerk_emp;
loop
fetch clerk_emp into name;
exit when clerk_emp%notfound;
dbms_output.put_line(name);
end loop;
end;
/

/* 9) To insert the records of all managers from emp table to newemp and also display on the screen using
CURSOR.

*/

DECLARE
cursor manager_emp is select empno,ename,hiredate,sal from emp where job like 'MANAGER';

eno emp.empno%type;
name emp.ename%type;
hdt emp.hiredate%type;
basic emp.sal%type;
BEGIN
open manager_emp;
dbms_output.put_line('eno Name Date Basic');
loop
fetch manager_emp into eno,name,hdt,basic;
exit when manager_emp%notfound;
insert into newemp values(eno,name,hdt,basic);
dbms_output.put_line(eno||' '||name||' '||hdt||' '||basic);
end loop;
close manager_emp;
end;
/

/* 10) To delete all employees belonging to department 50 and check if at least one row has been processed
using SQL%FOUND attribute. Insert the value into a table del_history and see the result.

*/

BEGIN

delete from emp where deptno=50;


if SQL%FOUND then
dbms_output.put_line(SQL%ROWCOUNT||'rows have been deleted');
else
dbms_output.put_line('Not Found ');
end if;
end;
/

/* 12) To declare a cursor that selects all employees in a given department and raise the salary by 0.05%
and updates the table and also update another table which keeps track of raised amount.

*/

declare
cursor cur12 is select empno,ename,sal,deptno from emp where deptno=&deptno;
eno emp.empno%type;
name emp.ename%type;
salary emp.sal%type;
sal1 emp.sal%type;
dn emp.deptno%type;
begin
open cur12;
loop
fetch cur12 into eno,name,salary,dn;
exit when cur12%notfound;
sal1:=salary;
insert into sal_incr values(eno,name,salary);
salary:=salary+salary*0.05;
update emp set sal=salary where deptno=dn and sal=sal1;
end loop;
close cur12;
end;
/

/* 16) Create a function to calculate factorial of any number. */

CREATE OR REPLACE FUNCTION factorial(n IN NUMBER) RETURN NUMBER IS


i number;
fact number:=1;
BEGIN
for i IN 2..n
loop
fact:=fact*i;
end loop;
return fact;
END;
/

/* Creating a Procedure with IN and OUT variable….. */

CREATE OR REPLACE PROCEDURE fact_pro(n IN NUMBER, r OUT NUMBER) IS


i number;
fact number:=1;
BEGIN
for i IN 2..n
loop
fact:=fact*i;
end loop;
r:=fact;
END;
/

/* Calling function and procedure in the following PL/SQL Block…………… */


DECLARE

num number;
result number;

BEGIN
num:=&num;
result:=factorial(num);
dbms_output.put_line('Factorial of '||num||' is '||result);
fact_pro(num,result);
dbms_output.put_line('Factorial of '||num||' is '||result);

end;
/

/* 16. Create a function to calculate simple interest. */

CREATE OR REPLACE FUNCTION simple_int(p IN number,i IN number, t IN number) RETURN


number IS
interest number;
BEGIN
interest:=p*t*i*0.01;
RETURN interest;
END;
/

/* Corresponding PL/SQL Block………………… */

declare
pr number;
i number;
y number;
begin
pr:=&Principal;
i:=&Interest;
y:=&Year;
dbms_output.put_line('Simple Interest = '||simple_int(pr,i,y));
end;
/

TRIGGER
Triggers are stored programs, which are automatically executed or fired when some events occur.
Triggers are in fact, written to be executed in response to any of the following events:

 A database manipulation (DML) statement (DELETE, INSERT, or UPDATE).

 A database definition (DDL) statement (CREATE, ALTER, or DROP).

 A database operation (SERVERERROR, LOGON, LOGOFF, STARTUP, or SHUTDOWN).


Triggers could be defined on the table, view, schema, or database with which the event is associated.

Benefits of Triggers
Triggers can be written for the following purposes:

 Generating some derived column values automatically

 Enforcing referential integrity

 Event logging and storing information on table access

 Auditing

 Synchronous replication of tables

 Imposing security authorizations

 Preventing invalid transactions

Creating Triggers
The Syntax for creating a trigger is:

CREATE [OR REPLACE ] TRIGGER trigger_name


{BEFORE | AFTER | INSTEAD OF }
{INSERT [OR] | UPDATE [OR] | DELETE}
[OF col_name]
ON table_name
[REFERENCING OLD AS o NEW AS n]
[FOR EACH ROW]
WHEN (condition)
DECLARE
Declaration-statements
BEGIN
Executable-statements
EXCEPTION
Exception-handling-statements
END;

Where,

 CREATE [OR REPLACE] TRIGGER trigger_name : Creates or replace an existing trigger with
thetrigger_name.

 {BEFORE | AFTER | INSTEAD OF} : This specifies when the trigger would be executed. The INSTEAD
OF clause is used for creating trigger on a view.

 {INSERT [OR] | UPDATE [OR] | DELETE}: This specifies the DML operation.

 [OF col_name]: This specifies the column name that would be updated.

 [ON table_name]: This specifies the name of the table associated with the trigger.

 [REFERENCING OLD AS o NEW AS n]: This allows you to refer new and old values for various DML
statements, like INSERT, UPDATE, and DELETE.

 [FOR EACH ROW]: This specifies a row level trigger, i.e., the trigger would be executed for each
row being affected. Otherwise the trigger will execute just once when the SQL statement is executed,
which is called a table level trigger.
 WHEN (condition): This provides a condition for rows for which the trigger would fire. This clause
is valid only for row level triggers.

Example:
To start with, we will be using the CUSTOMERS table we had created and used in the previous chapters:

Select * from customers;

+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
+----+----------+-----+-----------+----------+
The following program creates a row level trigger for the customers table that would fire for INSERT or
UPDATE or DELETE operations performed on the CUSTOMERS table. This trigger will display the salary
difference between the old values and new values:
CREATE OR REPLACE TRIGGER display_salary_changes
BEFORE DELETE OR INSERT OR UPDATE ON customers
FOR EACH ROW
WHEN (NEW.ID > 0)
DECLARE
sal_diff number;
BEGIN
sal_diff := :NEW.salary - :OLD.salary;
dbms_output.put_line('Old salary: ' || :OLD.salary);
dbms_output.put_line('New salary: ' || :NEW.salary);
dbms_output.put_line('Salary difference: ' || sal_diff);
END;
/

When the above code is executed at SQL prompt, it produces the following result:

Trigger created.

Here following two points are important and should be noted carefully:

 OLD and NEW references are not available for table level triggers, rather you can use them for
record level triggers.

 If you want to query the table in the same trigger, then you should use the AFTER keyword,
because triggers can query the table or change it again only after the initial changes are applied and the
table is back in a consistent state.

 Above trigger has been written in such a way that it will fire before any DELETE or INSERT or
UPDATE operation on the table, but you can write your trigger on a single or multiple operations, for
example BEFORE DELETE, which will fire whenever a record will be deleted using DELETE operation on
the table.

Triggering a Trigger
Let us perform some DML operations on the CUSTOMERS table. Here is one INSERT statement which will
create a new record in the table:

INSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY)


VALUES (7, 'Kriti', 22, 'HP', 7500.00 );
When a record is created in CUSTOMERS table, above create trigger display_salary_changes will be fired
and it will display following result:
Old salary:
New salary: 7500
Salary difference:

Because this is a new record so old salary is not available and above result is coming as null. Now, let us
perform one more DML operation on the CUSTOMERS table. Here is one UPDATE statement which will
update an existing record in the table:

UPDATE customers
SET salary = salary + 500
WHERE id = 2;
When a record is updated in CUSTOMERS table, above create trigger display_salary_changes will be fired
and it will display following result:
Old salary: 1500
New salary: 2000
Salary difference: 500

You might also like