Dbms Lab (R20) v1.0-FINAL
Dbms Lab (R20) v1.0-FINAL
INSTITUTE OF TECHNOLOGY
(Approved by AICTE New Delhi & Affiliated to JNTUK, Kakinada)
NH- 5, Chowdavaram, Guntur-522 019
An ISO 9001:2015 Certified Institution, Accredited by NAAC & NBA
KHIT
PRACTICAL RECORD
Name:……………………………………………………………………..
Branch:…………………. Section:…………………………........
Lab:……………………………………………………………………..…
KALLAM HARANADHAREDDY
INSTITUTE OF TECHNOLOGY
(APPROVED BY AICTE NEW DELHI, AFFLIATED TO
JNTUK, KAKINADA) CHOWDAVARAM, GUNTUR-19
Roll No:
CERTIFICATE
This is to Certify that the Bonafide Record of the Laboratory Work done by
Mr/Ms…………………………………………………………………………………………..
experiments in ……………………………………………………….………………………..
.
EX. PAGE
NO DATE NAME OF THE EXPERIMENT FROM TO MARKS SIGNATURE
.
INTRODUCTION
Structured Query Language (SQL)
SQL is a database language designed for the retrieval and management of data in a relational
database. SQL stands for Structured Query Language.
SQL includes database creation, deletion, fetching rows, modifying rows, etc.
Applications of SQL
As mentioned before, SQL is one of the most widely used query language over the databases. Allows
users to access data in the relational database management systems.
• Allows users to describe the data.
• Allows users to define the data in a database and manipulate that data.
• Allows to embed within other languages using SQL modules, libraries & pre-compilers.
• Allows users to create and drop databases and tables.
• Allows users to create view, stored procedure, functions in a database.
• Allows users to set permissions on tables, procedures and views.
SQL databases:
• Microsoft SQL
• MySQL
• MariaDB
• Oracle
• PostgreSQL
• MSSQL
DATABASE SCHEMA:
A database schema is the skeleton structure of the database object that is a table, view or an index
DATA TYPES:
1. CHAR(Size): This data type is used to store character string values of fixed length. The
maximum number of character is 255 characters.
2. VARCHAR(Size) / VERCHAR2(Size): This data type is used to store variable length string
data. The maximum character can hold is 2000 character.
3. NUMBER(P, S): The NUMBER data type is used to store number (fixed or floating point).
P is precision and S is scale.
• The precision is the number of digits in a number. It ranges from 1 to 38.
• The scale is the number of digits to the right of the decimal point in a number. It ranges from
-84 to 127.
For example, the number 1234.56 has a precision of 6 and a scale of 2. So to store this number, you
need NUMBER(6,2).
P and S are optional.
4. INT(size) or INTEGER(size) , FLOAT, DOUBLE, DECIMAL are also used
5. DATE: This data type is used to represent date and time. The standard format is DD-MM-
YY as in 17-SEP-2009.
6. RAW: The RAW data type is used to store binary data, such as digitized picture or image.
7. BOOL or BOOLEAN : True or false
Example:
SQL> desc person;
Name Null? Type
----------------------------------- ------ ------------------
name varchar2(10)
city varchar2(10)
state varchar2(10)
Inserting Records into PERSON TABLE:
SQL> insert into person values(‘RAMU’, ‘GUNTUR’, ‘AP’);
Syntax:
SQL>desc student;
Altering Tables:-
To alter a table use the alter table command:
Syntax1: To add new columns
Alter table tablename add (column datatype(size), ...);
Syntax2: To modify size(increase only) or change data type
Alter table tablename modify (column datatype(size));
Task 1.2: Write a query to add new column ‘PINCODE’ to the STUDENT table
Task 1.3 : Write a query to modify size of the NAME attribute in the table ‘STUDENT’
SQL>ALTER TABLE STUDENT MODIFY (NAME VARCHAR2 (15));
Task 1.5 : Write a query to change attribute name from NAME to STNAME
SQL>ALTER TABLE STUDENT RENAME COLUMN NAME TO STNAME;
Here (Col1_name,Col2_name,...) is used to insert values to specific columns. It can be omitted if you
want insert values to all columns.
String and Date values should be enclosed in single quotes.
Task 1.6: Write a query to insert the values into the table ‘STUDENT’
SQL>INSERT INTO STUDENT VALUES (01,’ANIL’,’12-FEB-90’,’HYD’);
SQL> /
Task 1.8: Write a query to display only ROLLNO & STNAME columns of a table ‘STUDENT’
SQL> SELECT ROLLNO, STNAME FROM STUDENT;
Task 1.9: Write a query to display only ROLLNO & CITY columns of a table ‘STUDENT’
SQL> SELECT ROLLNO, CITY FROM STUDENT;
Dropping Tables:-
To delete a table use the following:
Syntax: DROP TABLE TABLENAME;
DUAL table: The DUAL is special one row, one column table present by default in all Oracle
databases. The owner of DUAL is SYS (SYS owns the data dictionary, therefore DUAL is part of the
data dictionary.) but DUAL can be accessed by every user.
Numberic Functions
String Functions
Task 2.7: Write a query to find the character of ASCII value 65 & 100
SQL> select CHR(65), CHR(100) from dual;
Task 2.8: Write a query to add two strings Tamota & Soup
SQL> select CONCAT('Tamotat','Soup') "Starter" from dual;
Task 2.9: Write a query to padding ‘$’ symbols to the name in student table
Assume ‘student’ existed in the data base
SQL> select RPAD(name,5,'$') from student;
Task 2.11: Write a query to replace ‘Th’ with ‘B’ in the string 'This and That'
SQL> select REPLACE('This and That','Th','B') from dual;
Task 2.12: Write a query to work with translate function
SQL> SELECT TRANSLATE('123', '321', '456') FROM DUAL;
Task 2.13: Write a query to find the length of names in student table
Assume ‘student’ existed in the data base
SQL> SELECT NAME,LENGTH(NAME) FROM STUDENT;
Task 2.16: Write a query to find the no.of months between two dates:
SQL> SELECT MONTHS_BETWEEN('05-JAN-99','05-JAN-98') FROM DUAL;
Task 2.17: Write a query to convert a string date ’2022/OCT/10’ as date type:
SQL> SELECT TO_DATE(’2022/OCT/10’, 'YYYY/MMM/DD') FROM DUAL;
Task 2.18: Write a query to convert a system date as string in 'MONTH DD, YYYY format:
SQL> SELECT TO_CHAR(SYSDATE, 'MONTH DD, YYYY') FROM DUAL;
Exercise - 3
EMP TABLE
Task 3.1: Create a table with the name DEPT(DEPTNO,DNAME,LOC) AND INSERT
RECORDS
SQL>CREATE TABLE DEPT
( DEPTNO NUMBER(2) PRIMARY KEY,
DNAME VARCHAR2(10) NOT NULL,
LOC VARCHAR2(8));
SQL> desc dept
Task 3.2: Create a table with the name EMP and set foreign key with DEPTNO which
references to DEPT table and insert rocords
SQL> CREATE TABLE EMP
(EMPNO NUMBER(5) PRIMARY KEY,
ENAME VARCHAR2(10) NOT NULL,
JOB VARCHAR2(10),
MGR NUMBER(4),
HIREDATE DATE,
SAL NUMBER(7,2) CHECK(SAL>=500 AND SAL<=10000),
COMM NUMBER(7,2),
DEPTNO NUMBER(2),
FOREIGN KEY(DEPTNO) REFERENCES DEPT);
SQL | GROUP BY
The GROUP BY Statement in SQL is used to arrange identical data into groups with the help of
some functions. i.e if a particular column has same values in different rows then it will arrange these
rows in a group.
Important Points:
• GROUP BY clause is used with the SELECT statement.
• In the query, GROUP BY clause is placed after the WHERE clause.
• In the query, GROUP BY clause is placed before ORDER BY clause if used any.
Syntax:
SELECT column1, function_name(column2)
FROM table_name WHERE condition
GROUP BY column1, column2
ORDER BY column1, column2;
function_name: Name of the function used for example, SUM() , AVG().
table_name: Name of the table.
condition: Condition used.
HAVING Clause
We can use HAVING clause to place conditions to decide which group will be the part of final
result-set. Also we can not use the aggregate functions like SUM(), COUNT() etc. with WHERE
clause. So we have to use HAVING clause if we want to use any of these functions in the conditions
Syntax:
SELECT column1, function_name(column2)
FROM table_name
WHERE condition
GROUP BY column1, column2
HAVING condition
ORDER BY column1, column2;
Task 3.3: Write a query to display count of different jobs in the table ‘EMP’:
SQL> SELECT COUNT(DISTINCT JOB) FROM EMP;
Task 3.4: Write a query to display TOTAL salary of all employees in the table ‘EMP’:
SQL> SELECT SUM(SAL) FROM EMP;
Task 3.5: Write a query to display maximum of salary in the table ‘EMP’:
SQL> SELECT MAX(SAL) FROM EMP;
Task 3.6: Write a query to display maximum of salary among job type ‘SALESMAN’ in the
table ‘EMP’:
SQL> SELECT MAX(SAL) FROM EMP WHERE JOB='SALESMAN';
Task 3.7: Write a query to display minimum of salary in the table ‘EMP’:
SQL> SELECT MIN(SAL) FROM EMP;
Task 3.8: Write a query to display average salary from DEPTNO is 20 in the table ‘EMP’
SQL> SELECT AVG(SAL) FROM EMP WHERE DEPTNO=20;
Task 3.9: Write a query to display departmentwise count of employees in the table ‘EMP’
SQL> SELECT DEPTNO,COUNT(*) FROM EMP GROUP BY DEPTNO;
Task 3.10: Write a query to display departmentwise total salary of employees in the table
‘EMP’
SQL> SELECT DEPTNO,SUM(SAL) FROM EMP GROUP BY DEPTNO;
Task 3.11: Write a query to display jobwise count of employees in descending order in the table
‘EMP’
SQL> SELECT JOB,COUNT(*) FROM EMP GROUP BY JOB ORDER BY COUNT(*) DESC;
Task 3.12: Write a query to display jobwise sum,average, maximum and minimum salaries of
employees in the table ‘EMP’
SQL> SELECT JOB,SUM(SAL),AVG(SAL),MAX(SAL),MIN(SAL) FROM EMP GROUP BY
JOB;
Task 3.12: Write a query to display jobwise average salary of employees in the table ‘EMP’
except job category Manager
SQL> SELECT JOB,AVG(SAL) FROM EMP WHERE JOB!='MANAGER' GROUP BY JOB;
Task 3.13: Write a query to display jobwise maximum salary of employees whose maximum
salary having greater than 500 in the table ‘EMP’
SQL> SELECT JOB,MAX(SAL) FROM EMP GROUP BY JOB HAVING MAX(SAL)>=500;
Task 3.14: Write a query to display jobwise sum,average, maximum and minimum salary of
employees working in department no 20 whose average salary having greater than 1000 in the
table ‘EMP’
SQL> select job,sum(sal),avg(sal),max(sal),min(sal) from emp where deptno=20 group by job
having avg(sal)>1000 order by sum(sal);
VIEWS
Views:A view is a logical table based on a table or another view. A view contains no data of its own
but is like a window through which data from tables can be viewed or changed.
Consider EMP table.
Consider Dept table
Task 3.15: Write a query to create a view from the table ‘emp’ to display only
empno,ename,sal
SQL> CREATE OR REPLACE VIEW EMP_VIEW1 AS SELECT EMPNO,ENAME,SAL FROM
EMP;
Task 3.16: Write a query to create a view from the table ‘emp’ to display only empno, ename,
salary, deptno of employees of department number 20
SQL> CREATE OR REPLACE VIEW EMP_VIEW2 AS SELECT EMPNO,ENAME,SAL,
DEPTNO FROM EMP WHERE DEPTNO=20;
Task 4.1: Write a query to display employees whose job is CLERK OR ANALYST from EMP
table:
SQL> SELECT * FROM EMP WHERE JOB IN ('CLERK','ANALYST');
NOT IN operator :
Task 4.2: Write a query to display employees whose job is NOT CLERK OR ANALYST from
EMP table:
SQL> SELECT *FROM EMP WHERE JOB NOT IN ('CLERK','ANALYST');
EXISTS operator : is used to test for the existence of any record in a subquery. The EXISTS
operator returns TRUE if the subquery returns one or more records.
Task 4.2: Write a query to display employees whose salary is greatherthan salary of other
employees:
SQL> SELECT EMPNO,ENAME, SAL FROM EMP E1 WHERE EXISTS(SELECT EMPNO
FROM EMP E2 WHERE E1.SAL >= E2.SAL);
Task 4.3: Write a query to display employees whose salary is not greatherthan salary of other
employees:
NOT EXISTS operator : is used to test for the existence of any record in a subquery
SQL> SELECT EMPNO,ENAME, SAL FROM EMP E1 WHERE NOT EXISTS(SELECT
EMPNO FROM EMP E2 WHERE E1.SAL >= E2.SAL);
ANY operator: It returns TRUE if ANY of the subquery values meet the condition. ANY means
that the condition will be true if the operation is true for any of the values in the range..
Task 4.4: Write a query to display employees whose salary is equal to the salaty of employees
working in department number 20 from EMP table:
SQL> SELECT ENAME FROM EMP WHERE SAL =ANY(SELECT SAL FROM EMP WHERE
DEPTNO=20);
ALL operator: It returns TRUE if ALL of the subquery values meet the condition
Task 4.5: Write a query to display employees whose salary is greater than the salaty of all
employees working as clerk from EMP table:
SQL> SELECT ENAME FROM EMP WHERE SAL > ALL (SELECT SAL FROM EMP WHERE
JOB=’CLERK’);
UNION operator: The UNION operator is used to combine the result-set of two or
more SELECT statements.
Task 4.6: Write a query to display employees who are working in DALLAS or NEWYORK
from EMP nad DEPT tables:
INTERSECT operator: The SQL INTERSECT clause/operator is used to combine two SELECT
statements, but returns rows only from the first SELECT
Task 4.7: Write a query to display employees from EMP table whose departments in DEPT
table.
SQL> SELECT E.DEPTNO FROM EMP E INTERSECT SELECT D.DEPTNO FROM DEPT D;
Constraints:
You can place constraints to limit the type of data that can go into a table.
Common types of constraints include the following:
• UNIQUE Constraint : Ensures that all values in a column are distinct.
• NOT NULL Constraint : Ensures that a column cannot have NULL value.
• CHECK Constraint : Makes sure that all values in a column satisfy certain criteria.
• PRIMARY KEY Constraint : Ensures that all values in a column are distinct and a Column
can’t have NULL value.
• FOREIGN KEY Constraint : Used to ensure referential integrity of the data.
UNIQUE Constraint:-
Task 4.7: Write a query to create a table with name ‘CUSTOMER’ in this add UNIQUE
constraint to SID column and insert the following rows and test UNIQUE CONSTRAINTS
SQL> CREATE TABLE CUSTOMER
(SID INTEGER UNIQUE,
FIRST_NAME VARCHAR2(20),
LAST_NAME VARCHAR2(20));
It will result in an error because '1201' already exists in the SID column, thus trying to insert another
row with that value violates the UNIQUE constraint.
TABLE CREATED.
SQL> SELECT B.COLOR FROM BOATS B WHERE B.BID IN (SELECT R.BID FROM
RESERVES R WHERE R.SID=(SELECT S.SID FROM SAILORS S WHERE S.SNAME
=’LUBBER’));
Task 5.3: Write a query to find the names of sailors who have reserved at least one boat.
Task 5.4: Write a query to find the names of sailors who have reserved a RED or
GREEN boat.
SQL> SELECT S.SID, S.SNAME FROM SAILORS S
WHERE S.SID IN (SELECT R.SID FROM RESERVES R
WHERE R.BID IN (SELECT B.BID FROM BOATS B
WHERE B.COLOR=’GREEN’ OR B.COLOR=’RED’));
or
Task 5.6: Write a query to find names of sailors who have reserved all boats.
SELECT S.SNAME FROM SAILORS S
WHERE NOT EXISTS
(( SELECT B.BID FROM BOATS B )
MINUS
( SELECT R.BID FROM RESERVES R WHERE R.SID=S.SID ));
Exercise - 6
DECLARE
X STUDENT%ROWTYPE;
BEGIN
SELECT RNO ,NAME ,AVG_MARKS ,RES INTO X.RNO, X.NAME,
X.AVG_MARKS, X.RES FROM STUDENT WHERE RNO=&RNO;
Insert data into student table and use COMMIT, ROLLBACK and
SAVEPOINT in PL/SQL block.
Program:
DECLARE
X STUDENT%ROWTYPE;
BEGIN
X.RNO:=&RNO;
X.AME:='&NAME';
X.AVG_MARKS:=&AVG_MARKS;
X.RES:=’&GRADE’;
INSERT INTO STUDENT VALUES
(X.RNO,X.NAME,X.AVG_MARKS,X.RESULT);
COMMIT;
X.RNO:=&RNO;
X.AME:='&NAME';
X.AVG_MARKS:=&AVG_MARKS;
X.RES:=’&GRADE’;
INSERT INTO STUDENT VALUES
(X.RNO,X.NAME,X.AVG_MARKS,X.RESULT);
SAVEPOINT A;
X.RNO:=&RNO;
X.AME:='&NAME';
X.AVG_MARKS:=&AVG_MARKS;
X.RES:=’&GRADE’;
INSERT INTO STUDENT VALUES
(X.RNO,X.NAME,X.AVG_MARKS,X.RESULT);
SAVEPOINT B;
X.RNO:=&RNO;
X.AME:='&NAME';
X.AVG_MARKS:=&AVG_MARKS;
X.RES:=’&GRADE’;
INSERT INTO STUDENT VALUES
(X.RNO,X.NAME,X.AVG_MARKS,X.RESULT);
ROLLBACK TO A;
COMMIT;
END;
/
OUTPUT:
OUTPUT:
CASE X
WHEN 1 THEN
DBMS_OUTPUT.PUT_LINE('MONDAY');
WHEN 2 THEN
DBMS_OUTPUT.PUT_LINE('TUESDAY');
WHEN 3 THEN
DBMS_OUTPUT.PUT_LINE('WEDNESDAY');
WHEN 4 THEN
DBMS_OUTPUT.PUT_LINE('THURSEDAY');
WHEN 5 THEN
DBMS_OUTPUT.PUT_LINE('FRIDAY');
WHEN 6 THEN
DBMS_OUTPUT.PUT_LINE('SATURDAY');
WHEN 7 THEN
DBMS_OUTPUT.PUT_LINE('SUNDAY');
ELSE
DBMS_OUTPUT.PUT_LINE('UNKNOWN DAY');
END CASE;
END;
/
OUTPUT:
NULLIF() Function
Definition and Usage
The NULLIF() function returns NULL if two expressions are equal, otherwise it returns the first
expression.
Syntax
NULLIF(expr1, expr2)
Example:
SELECT NULLIF(25, 25 from dual;
Ans: Null
SELECT NULLIF('Hello', 'Hello') from dual;
Ans: Null
SELECT NULLIF('Hello', 'world') from dual;
Ans: Hello
Exercise 8. C)PL/SQL program using NULLIF
Program:
DECLARE
X NUMBER(3);
Y VARCHAR2(10);
Z VARCHAR2(10);
BEGIN
SELECT NULLIF(25, 25) INTO X FROM DUAL;
DBMS_OUTPUT.PUT_LINE(' X IS '|| X);
SELECT NULLIF('HELLO', 'HELLO') INTO Y FROM DUAL;
DBMS_OUTPUT.PUT_LINE(' Y IS '|| Y);
SELECT NULLIF('HELLO', 'WORLD') INTO Z FROM DUAL;
DBMS_OUTPUT.PUT_LINE(' Z IS '|| Z);
END;
/
Exercise - 9
Program development using WHILE LOOPS, numeric FOR LOOPS,
nested loops using ERROR Handling, BUILT IN Exceptions, USE
defined Exceptions, RAISE- APPLICATION ERROR.
SIMPLE LOOP
Basic loop structure encloses sequence of statements in between the LOOP and END LOOP
statements. With each iteration, the sequence of statements is executed and then control resumes at
the top of the loop.
Syntax
LOOP
Statements;
EXIT;
{or EXIT WHEN condition;}
END LOOP;
Example
DECLARE
X NUMBER := 10;
BEGIN
LOOP
DBMS_OUTPUT.PUT_LINE(X);
X := X + 10;
EXIT WHEN X=50;
END IF;
END LOOP;
DBMS_OUTPUT.PUT_LINE('AFTER EXIT X IS: ' || X);
END;
/
WHILE LOOP
Example
DECLARE
a number(2) := 1;
BEGIN
WHILE a <= 15 LOOP
insert into seq values(a);
a := a + 1;
END LOOP;
END;
/
Program:
DECLARE
A NUMBER(2) := 1;
BEGIN
WHILE A <= 15 LOOP
INSERT INTO SEQ VALUES(A);
A := A + 1;
END LOOP;
END;
/
FOR LOOP
A FOR LOOP is a repetition control structure that allows you to efficiently write a loop that needs
to execute a specific number of times.
Syntax
FOR counter IN initial_value .. final_value LOOP
sequence_of_statements;
END LOOP;
• Counter is control variable
• Initial_value is stating value of counter
• Final_value is stating value of counter
• The initial_value need not be 1; however, the loop counter increment (or decrement) must be
1.
Example:
DECLARE
a number(2);
BEGIN
FOR a in 10 .. 15 LOOP
dbms_output.put_line('value of a: ' || a);
END LOOP;
END;
/
Program:
DECLARE
A number(2);
BEGIN
FOR A in REVERSE 1 .. 10 LOOP
INSERT INTO REV_SEQ VALUES(A);
END LOOP;
END;
/
NESTED LOOP:
EXCEPTIONS
An exception is an error condition during a program execution. PL/SQL supports programmers to
catch such conditions using EXCEPTION block in the program and an appropriate action is taken
against the error condition. There are two types of exceptions −
1. Built-in or System-defined exceptions
2. User-defined exceptions
Built-in or System-defined exceptions:
These are defined in SQL software. These exceptions will implicitly raised when evr occured.
Example: NO_DATA_FOUND
The general syntax for exception handling is as follows. Here you can list down as many exceptions
as you can handle. The default exception will be handled using WHEN others THEN −
Exercise 9E) userexcep: This program asks for a Student RNo, when
the user enters an invalid RNo, the exception invalid_id is raised.
DECLARE
s_rno student.RNo%type := &student_RNo;
s_name student.Name%type;
s_avg student.avg%type;
-- user defined exception
ex_invalid_id EXCEPTION;
BEGIN
IF s_rno <= 0 THEN
RAISE ex_invalid_id;
ELSE
SELECT name, avg INTO s_name, s_avg FROM student WHERE RNo =
s_RNo;
DBMS_OUTPUT.PUT_LINE ('Name: '|| s_name);
DBMS_OUTPUT.PUT_LINE ('Avg: ' || s_avg);
END IF;
EXCEPTION
WHEN ex_invalid_id THEN
dbms_output.put_line('RNo must be greater than zero!');
WHEN no_data_found THEN
dbms_output.put_line('No such student!');
WHEN others THEN
dbms_output.put_line('Error!');
END;
/
Exercise - 10
PL/SQL Procedures
PL/SQL subprograms are named PL/SQL blocks that can be invoked with a set of parameters.
PL/SQL provides two kinds of subprograms −
1. Functions − These subprograms return a single value; mainly used to compute and return a
value.
2. Procedures − These subprograms do not return a value directly; mainly used to perform an
action.
Creating a Procedure
A procedure is created with the CREATE OR REPLACE PROCEDURE statement.
Syntax:
CREATE [OR REPLACE] PROCEDURE procedure_name
[(parameter_name [IN | OUT | IN OUT] type [, ...])] {IS | AS}
BEGIN
< procedure_body >
END procedure_name;
Example
The following example creates a simple procedure that displays the string 'Hello World!' on the
screen when executed.
CREATE OR REPLACE PROCEDURE greetings AS
BEGIN
dbms_output.put_line('Hello World!');
END;
When the above code is executed using the SQL prompt, it will produce the following result −
Procedure created.
PL/SQL -Functions
Functions − These subprograms return a single value; mainly used to
compute and return a value.
Creating a Function
A standalone function is created using the CREATE FUNCTION statement:
Example
This function returns the total number of Empoyees in the EMP table.
We will use the EMP table
SQL>Select * from EMP;
SQL> @C:\USERS\SANJU\DESKTOP\DBMS\LAB\LAB9A_2.SQL
ENTER VALUE FOR N: 5
OLD 2: N NUMBER:=&N;
NEW 2: N NUMBER:=5;
FACTORIAL IS120
Pl/Sql Procedure Successfully Completed.
Exercise 11.B) Write a PL/SQL Code to increment sal using
Userdefined function
Program to create function:
CREATE OR REPLACE FUNCTION INCREMENT_SALARY(EID NUMBER) RETURN
NUMBER IS
INCR EMP999.SAL%TYPE;
VENO EMP999.ENO%TYPE;
VSAL EMP999.SAL%TYPE;
BEGIN
SELECT ENO,SAL INTO VENO,VSAL FROM EMP999 WHERE ENO=EID;
IF VSAL<=5000 THEN
INCR:=0.10*VSAL;
ELSIF VSAL>5000 AND VSAL<=10000 THEN
INCR:=0.20*VSAL;
ELSE
INCR:=0.30*VSAL;
END IF;
RETURN INCR;
END INCREMENT_SALARY;
/
Program to call Fact() function
DECLARE
INCR NUMBER;
VENO NUMBER:=&EMPLOY_NUMBER;
BEGIN
INCR := INCREMENT_SALARY(VENO);
UPDATE EMP999 SET SAL=INCR WHERE ENO=VENO;
DBMS_OUTPUT.PUT_LINE('THE EMPLOY SALARY AFTER INCREMNT IS ' || INCRE);
END;
/
Exercise - 12
Exercise 12.A) Program to fetch employ data from EMP whose salary
> 5000 using cursor
Program:
DECLARE
VENO EMP999.ENO%TYPE;
VSAL EMP999.SAL%TYPE;
CURSOR C1 IS SELECT ENO,SAL FROM EMP999 WHERE SAL>5000;
BEGIN
OPEN C1;
LOOP
FETCH C1 INTO VENO,VSAL;
IF C1%FOUND THEN
DBMS_OUTPUT.PUT_LINE(VENO||' '||VNAME||' '||VSAL);
ELSE
EXIT;
END IF;
END LOOP;
CLOSE C1;
END;
/
Output
SQL> SELECT * FROM EMP999;
SQL> @E:\samson\lab10a.sql;
Exercise 12.B) Program to fetch employ salaries and calculate total
salary from EMP table using cursor
Program:
DECLARE
SALARY EMP999.SAL%TYPE;
S NUMBER:=0;
CURSOR C1 IS SELECT SAL FROM EMP999;
BEGIN
OPEN C1;
LOOP
FETCH C1 INTO SALARY;
S:=S+SALARY;
EXIT WHEN C1%NOTFOUND;
END LOOP;
DBMS_OUTPUT.PUT_LINE('TOTAL IS: ');
DBMS_OUTPUT.PUT_LINE(TO_CHAR(S));
DBMS_OUTPUT.PUT_LINE('ROWS FETCHED'||C1%ROWCOUNT);
CLOSE C1;
END;
/
Output:
SQL> SELECT * FROM EMP;
SQL> @E:\samson\lab10b.sql;
Exercise - 13
▪ A trigger is a PL/SQL block structure which is fired when a DML statements like Insert,
Delete, Update is executed on a database table.
▪ A trigger is triggered automatically when an associated DML statement is executed.
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
Syntax of Triggers
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;
There are two types of triggers based on the which level it is triggered.
1) Row level trigger - An event is triggered for each row upated, inserted or deleted.
2) Statement level trigger - An event is triggered for each sql statement executed.
PL/SQL Trigger Execution Hierarchy
END;
/
SQL> create table deleted_emps as select * from emp;
Table created.
SQL> delete from deleted_emps;
SQL> @E:\samson\lab11b.sql
Trigger created.
SQL> delete from emp where eno=1;
1 row deleted.
SQL> select * from deleted_emps;
ENO NAME SAL
---------- ---------- ----------
1 TEJA 3000
SQL> select * from emp;
ENO NAME SAL
---------- ---------- ----------
2 HARI 3000
3 ANIL 10000
STATEMENT-LEVEL TRIGGERS
A statement-level trigger is fired whenever a trigger event occurs on a table regardless of how many
rows are affected. In other words, a statement-level trigger executes once for each transaction.
For example, if you update 1000 rows in a table, then a statement-level trigger on that table
would only be executed once.
Due to its features, a statement-level trigger is not often used for data-related activities like auditing
the changes of the data in the associated table. It’s typically used to enforce extra security measures
on the kind of transaction that may be performed on a table.
By default, the statement CREATE TRIGGER creates a statement-level trigger when you omit the
FOR EACH ROW clause.
Exercise 13.C) Program to create statement level trigger to raise an
application error when update credit_limit of Customer table between
28th to 31st of every month
SQL> create table customer
(id number(4),
name varchar2(20),
credit_limit number(10,2));
SQL> insert into customer values( 1, 'TEJA', 50000);
SQL> insert into customer values( 2, 'ANIL', 150000);
SQL> insert into customer values( 3, 'BHARAT', 250000);
Program to create trigger:
CREATE OR REPLACE TRIGGER customers_credit_trg
BEFORE UPDATE OF credit_limit
ON customer
DECLARE
day_of_month NUMBER;
BEGIN
-- determine the transaction type
day_of_month := EXTRACT(DAY FROM sysdate)
IF day_of_month BETWEEN 28 AND 31 THEN
raise_application_error(-20100,'Cannot update customer credit from 28th to 31st');
END IF;
END;
/
SQL> @E:\samson\lab11C.sql
Trigger created.
SQL> update customer set credit_limit=100000 where id=1;
1 row updated.
SQL> select sysdate from dual;
SYSDATE
---------
22-JUN-21