0% found this document useful (0 votes)
3 views

DBMS_LAB

The document outlines various SQL commands categorized into DDL, DML, and DCL, along with their usage and examples. It explains commands such as CREATE, DROP, INSERT, UPDATE, and GRANT, detailing their syntax and function in database management. Additionally, it covers operators and built-in functions in SQL, providing examples for arithmetic, relational, and character functions.

Uploaded by

shaikshahena04
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

DBMS_LAB

The document outlines various SQL commands categorized into DDL, DML, and DCL, along with their usage and examples. It explains commands such as CREATE, DROP, INSERT, UPDATE, and GRANT, detailing their syntax and function in database management. Additionally, it covers operators and built-in functions in SQL, providing examples for arithmetic, relational, and character functions.

Uploaded by

shaikshahena04
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 50

NRI IT, Department of MCA DBMS LAB

Experiment - 1
Aim : Execute all DDL, DML and DCL commands on sample Tables
DDL Commands :
 CREATE Command  TRUNCATE Command
 DROP Command  RENAME Command
 ALTER Command  DESCRIBE Command
CREATE Command : This command can be used to create a table.
CREATE Table Student(SNO Number(3), SNAME Varchar2(20),
MARK1 Number(3), MARK2 Number(3));
DROP Command : This command can be used to drop the table from the database i.e., this command can be
used to delete the table structure as well as the data itself from the database permanently. Once we drop the
table, it can‟t be get back. So use this command carefully.
DROP Table Student;
ALTER Command : This command can be used to modify or change the structure of a table.
ALTER table Student ADD (QUAL Varchar2(10));
ALTER table Student Modify(SNAME Varchar2(25));
RENAME Command : This command can be used to rename the table. So once we change the table name
then the old name doesn‟t exists.
RENAME Student TO Stu;
DESCRIBE Command : This command can be used to view the table structure. The syntax is
Syntax : DESC <table_name>;
Ex : DESC Stu;
TRUNCATE Command : This command can be used to truncate the table i.e., it deletes all the records in a
table but retains the table structure for future usage.
TRUNCATE Table Stu;

DML Commands :
 INSERT  DELETE
 UPDATE  SELECT
INSERT Command : This command can be used to insert data or to add data into the table, one row or
record at a time. This command can also be used to add new data to a table that already contains data.
INSERT INTO Stu (SNO, SNAME) values (1, „A‟);

T.V.N. HANUMANTHA RAO Page 1


NRI IT, Department of MCA DBMS LAB

UPDATE Command : This command can be used to update the content of the table. When we made mistakes
while entering the data into the table, this command can be used to make data entry corrections. Unlike
INSERT command this UPDATE command can correct more than one row at a time.
UPDATE Stu set SNAME = „B‟ WHERE SNO = 1;

DELETE Command : This command can be used to delete a single row or a set of rows from the table.
DELETE FROM stu WHERE sno = 1;
If we not mention the condition part of WHERE clause then all the rows are deleted from the table.

SELECT Command : Actually SELECT command is a query command rather than a DML command. The
reason for including it in DML commands is that it can also be used to check whether the data is inserted into
a table or not. Therefore to check the table contents, this command can be used. Generally it can be used to
retrieve the data from the table.
SELECT sno FROM Stu;
If we want to list all the columns from a table then we can use a wild card character „*‟ instead of all
column names in the table.
SELECT * FROM <table_name>;

DCL Commands : These commands are used to control the privileges in the database. Privileges are of two
types like
 System Privileges : Creating Sessions, Tables, etc are the types of System Privileges.
 Object Privileges : Any command or query to work on tables comes under the category of Object
Privileges.
DCL defines two commands.
GRANT Command - This command can be used to give privileges to the users. The syntax is
GRANT <Object_privileges> ON <Object> TO <User> [With Grant Option];
The object privileges that can be granted to the users are
 Alter  Index
 Delete  Select
 Insert  Update
To grant all the privileges, we specify ALL.
Ex : GRANT ALL ON emp TO Hindu;
To grant particular privileges to other users, we use

T.V.N. HANUMANTHA RAO Page 2


NRI IT, Department of MCA DBMS LAB

Ex : GRANT Select, Insert, Delete ON emp to Hindu;


To grant privilege on a particular column for Insert and Update, we use
Ex : GRANT Insert (Eno, Ena) on emp to Hindu;
The With Grant Option allows the grantee to grant object privileges to the other users.
Ex : GRANT ALL ON emp TO Hindu With Grant Option;
To grant the object to all the users, use Public.
Ex : GRANT ALL ON emp to Public.
REVOKE Command - This command can be used to bring back the privileges given to the users. The
syntax is
REVOKE <Privileges> ON <Object> FROM <User>;
To withdraw Select, Insert and Delete privileges on the object “Emp” from a user, we use
Ex : REVOKE Select, Insert, Delete FROM Hindu;

Queries :
1. Insert the data into employee table.
Insert into emp values(1,‟a‟,101,‟Clerk‟,‟10-oct-10‟,10000,400,10);
2. Insert the data into department table.
Insert into dept values(10,‟MCA‟,‟Guntur‟);
3. Display the employee information from the employee table.
Select * from emp;
EMPNO ENAME JOB MGR HIREDATE SAL COMM DNO
---------- --------------- ---------- ------- --------- -------- ---------- --------
7369 SMITH CLERK 7902 17-DEC-80 920 20
7499 ALLEN SALESMAN 7698 20-FEB-81 1600 300 30
7521 WARD SALESMAN 7698 22-FEB-81 1250 500 30
4. Display the department information from the department table.
Select * from dept;
DNO DNAME LOC
---------- -------------------- ---------------
10 accounting guntur
20 hr hyderabad
5. Display the Generalized Insert Statement for the employee table.
Insert into emp values(&empno,‟&ename‟,&mgr,‟&job‟,‟&hiredate‟,&sal,&comm.,&deptno);

T.V.N. HANUMANTHA RAO Page 3


NRI IT, Department of MCA DBMS LAB

6. Display the Name and Job of all employees.


Select ename, job from emp;
ENAME JOB
-------------------- ----------
SMITH CLERK
ALLEN SALESMAN
7. Display the Employee Number, Name & Salary of all the Employees.
Select empno, ename, sal from emp;
EMPNO ENAME SAL
---------- -------------------- ----------
7369 SMITH 920
7499 ALLEN 1600
8. Write a Query to Insert Null values into the table.
Insert into student values(101,‟xyz‟,NULL,60,70);

T.V.N. HANUMANTHA RAO Page 4


NRI IT, Department of MCA DBMS LAB

Experiment - 2
Aim : Implementation of different types of Operators and Built-in Functions with suitable
examples.
OPERATORS IN SQL : Operators in SQL are given below
 Arithmetic Operators  Relational Operators
 String Operators  Special Operators
 Logical Operators  Character Operators
1. Arithmetic Operators : These are the operators used to perform arithmetic operations and any
calculations in SQL Command. The Arithmetic Operators are + (Addition), - (Subtraction), *
(Multiplication), / (Division). Usually these can be applied to the numerical data.
Ex : Select ENO, SAL, COMM, SAL + COMM from Emp where DEPNO = 10;
2. Character Operators : These operators are used to manipulate character strings. The best character
operator is Concatenation Operator i.e., ||.
3. Logical Operators : These are the operators used to combine results of two conditions to produce a
single result. The Logical Operators are AND, OR, NOT.
Ex: Select * from Emp where SAL = 3500 AND DEPNO = 10;
The above command will display all the rows with their columns which has DEPNO as 10
and also SAL as 3500.
Ex : Select * from Emp where NOT SAL = 5000;
The above command will display all the rows and columns which is not having SAL as
5000.
4. Relational Operators : These are used to compare one expression with another. The Relational
Operators are >, >=, <, <=, =(Equal to), < > / ! = (Not Equal to).
5. Special Operators : In SQL the Special Operator is IS NULL. It is used to check whether it is
NULL.
6. String Operators : The String Operators in SQL are
BETWEEN – To check for a range of values
IN – To check whether the value is present in a set of values or not.
LIKE – To match with the parameter.
EXISTS - To check whether a column has a value or not.
Ex : Select * from Emp where SAL BETWEEN 3000 and 5000;
The above command will display the records which has SAL in the range from 3000 to
5000.
Ex : Select * from Emp where ENO IN (7839, 101, 110);

T.V.N. HANUMANTHA RAO Page 5


NRI IT, Department of MCA DBMS LAB

The above command will display the rows which are having ENO as 7839 or 101 or 110.
Ex : Select ENA, SAL from Emp where ENA LIKE „A%‟;
The above command will display columns ENA, SAL whose ENA begins with „A‟.
Ex : Select * from Emp where ENA LIKE „A___S‟;
The above command will display all the columns whose ENA is five characters long
beginning with „A‟ and ending with „S‟.
SQL Functions : A function is defined as a sub program that returns a value. There are different types of
functions. They are
 Number Functions  Conversion Functions
 Character Functions  Group Functions
 Date Functions  Special Functions
Number Functions :
 GREATEST( ) – Returns the greatest of the list of the expressions. The syntax is
GREATEST(expr1, expr2, -----)
Ex : Select GREATEST(3, 20, 70) “Greatest” from Dual;
 LEAST( ) – Returns the Least of the list of the expressions. The syntax is
LEAST(expr1, expr2, ------)
 SIN( ) – Returns the Sine of n (an angle expressed in Radians). The syntax is
SIN(n)
Ex : Select SIN(30 * 3.14 / 180) “Sine” from Dual;
 COS( ) – Returns the Cosine of n. The syntax is
COS(n)
 TAN( ) – Returns the Tangent of n. The syntax is
TAN(n)
 POWER( ) – The syntax is
POWER(m, n)
It returns m raised to the nth power.
Ex : Select POWER(3, 2) “Raised” from Dual;
 FLOOR( ) – Returns the largest integer equal to or less than n. The syntax is
FLOOR(n)
Ex : Select FLOOR(15.7) “Floor” from Dual;
 CEIL( ) – Returns the smallest integer greater than or equal to n. The syntax is
CEIL(n)
Ex : Select CEIL(15.7) “Ceiling” from Dual;

T.V.N. HANUMANTHA RAO Page 6


NRI IT, Department of MCA DBMS LAB

 SQRT( ) – Returns the Square Root of n. The value n cannot be negative. The syntax is
SQRT(n)
Ex : Select SQRT(25) “Sqrt” from Dual;
 ABS( ) – Returns the Absolute value of n. The syntax is
ABS(n)
Ex : Select ABS(-15) “Absolute” from Dual;
 MOD( ) – The syntax is
MOD(m, n)
Returns the remainder of m divided by n and returns m if n is 0.
Ex : Select MOD(11, 4) “Modulus” from Dual;
 EXP( ) – The syntax is
EXP(n)
Returns e raised to the nth power.
Ex : Select EXP(4) “E to the Power” from Dual;
 LN( ) – The syntax is
LN(n)
Returns the Natural Logarithm of n.
Ex : Select LN(95) “Natural Log” from Dual;
 ROUND( ) – The syntax is
ROUND(n, [m])
Returns n rounded m places right of the decimal point.
Ex : Select ROUND(15.193, 1) “Round” from Dual;
 TRUNC( ) – The syntax is
TRUNC(n, [m])
Returns n truncated to m decimal places.
Ex : Select TRUNC(15.79, 1) “Truncate” from Dual;
 CHR( ) – Returns the character having the binary equivalent to n in the database character set. The
syntax is
CHR(n)
Ex : Select CHR(75) “Character” from Dual;
 ASCII( ) – Returns the ASCII value of n. The syntax is
ASCII(n)
Ex : Select ASCII(„k‟) “ASCII” from Dual;

T.V.N. HANUMANTHA RAO Page 7


NRI IT, Department of MCA DBMS LAB

Character Functions :
 GREATEST( ) – The syntax is
GREATEST(expr1, expr2, ………)
Returns the Greatest of the list of expressions.
Ex : Select GREATEST(„Harry‟, „Harriot‟, „Harold‟) “Greatest” from Dual;
 LEAST( ) – The syntax is
LEAST(expr1, expr2, ………)
Returns the Least of the list of the expressions.
 LENGTH( ) – Returns the Length of the Characters in a string. The syntax is
LENGTH(Char)
Ex : Select LENGTH(„Candid‟) “Length” from Dual;
 INITCAP( ) – Returns Char, with the first letter of each word in Uppercase, all other letters in
Lowercase. The syntax is
INITCAP(Char)
Ex : Select INITCAP(„the soap‟) “Capitalised” from Dual;
 SUBSTR( ) – The syntax is
SUBSTR(Char, m, [n])
Returns a portion of Char, beginning at Char m, n characters long.
Ex : Select SUBSTR(„ABCDEFG‟, 3, 2) “Substring” from Dual;
Select SUBSTR(„ABCDEFG‟, -3, 2) “Substring” from Dual;
 INSTR( ) – The syntax is
INSTR(Char1, Char2, n, [m])
Searches Char2 beginning with its nth Character for mth occurance of Char2 and returns the position
of the Character in Char1.
Ex : Select INSTR(„CORPORATE FLOOR‟, „OR‟, 3, 2) “Instring” from Dual;
Select INSTR(„CORPORATE FLOOR‟, „OR‟, -3, 2) “Instring” from Dual;
 LPAD( ) – The syntax is
LPAD(Char1, n, [Char2])
Returns Char1 left padded to length n with the sequence of characters in Char2.
Ex : Select LPAD(„Page1‟, 10, „*‟) “Lpad” from Dual;
 RPAD( ) – The syntax is
RPAD(Char1, n, [Char2])
Returns Char1 right padded to length n with Char2.

T.V.N. HANUMANTHA RAO Page 8


NRI IT, Department of MCA DBMS LAB

 LTRIM( ) – The syntax is


LTRIM(Char, [Set])
Removes characters from the left of Char with initial characters removed upto the first character not
in the set.
Ex : Select LTRIM(„xyxXxyHindu‟, „xy‟) “Ltrim” from Dual;
 RTRIM( ) – The syntax is
RTRIM(Char, [Set])
Removes characters from the right of Char with initial characters removed upto the first character
not in the set.
 REPLACE( ) – The syntax is
REPLACE(Char, Search_String, [Replacement_String])
Returns Char with every occurance of Search_String replaced with Replacement_String.
Ex : Select REPLACE(„Jack and Jue‟, „J‟, „BL‟) “Replace” from Dual;
 TRANSLATE( ) – The syntax is
TRANSLATE(Char, From, To)
Returns Char with all occurances of each character in From replaced by its corresponding character
in To.
Ex : Select TRANSLATE(„MALAYALAM‟, „AL‟, „T‟) “Translate” from Dual;
In the above example, „A‟ is replaced by „T‟ and since „L‟ does not have replacement
character it is left blank.
Ex : Select TRANSLATE(„MALAYALAM‟, „A‟, „TV‟) “Translate” from Dual;
Date Functions :
 SYSDATE – Returns the current system date.
Ex : Select SYSDATE from Dual;
 ADD_MONTHS( ) – The syntax is
ADD_MONTHS(d, n)
Returns the date d plus n months.
Ex : Select ADD_MONTHS(Sysdate, 3) from Dual;
 MONTHS_BETWEEN( ) – The syntax is
MONTHS_BETWEEN(d1, d2)
Returns the number of months between the dates d1 and d2.
Ex : Select MONTHS_BETWEEN(Sysdate, ‟10-JUN-15‟) from Dual;
 NEXT_DAY( ) – The syntax is
NEXT_DAY(d, Char)

T.V.N. HANUMANTHA RAO Page 9


NRI IT, Department of MCA DBMS LAB

Returns the date of the first weekday named by Char that is later than the date d.
Ex : Select NEXT_DAY(Sysdate, „Sunday‟) from Dual;
 LAST_DAY( ) – The syntax is
LAST_DAY(d)
Returns the date of the last day of the month that contains d.
Ex : Select LAST_DAY(Sysdate) from Dual;
Conversion Functions :
 TO_CHAR( ) – The syntax is
TO_CHAR(d, [fmt, [‘nlsparams’]])
It converts d of Date datatype to a value of Varchar2 datatype in the format specified by the
date format fmt. The „nlsparams‟ specifies the language in which month and day names are returned.
Ex : Select Sysdate, TO_CHAR(Sysdate, „dayYYYYmonth‟) from Dual;
Select TO_CHAR(Sysdate, „HH-MM-SS‟) from Dual;
 TO_DATE( ) – The syntax is
TO_DATE(Char, [fmt, [‘nlsparams’]])
Converts Char of Char or Varchar2 datatype to a value of Date datatype. The fmt is a date
format specifying the format of char.
Ex : Create table Dates(SDATE Date, EDATE date);
Insert into Dates Values (TO_DATE(„2001-JAN-01‟,‟YYYY-Mon-DD‟),
TO_DATE(„JUNE-2002-10‟,‟Month-YYYY-DD‟));
Group Functions :
 MAX( ) – This will display the highest value of particular column. The syntax is
MAX(Column_Name)
 MIN( ) – This will display the minimum value for the particular column specified. The syntax is
MIN(Column_Name)
 AVG( ) – This function will return the average value for a column specified. This can be used with
one Number Datatype. The syntax is
AVG(Column_Name)
 SUM( ) – This function will return the sum of Column Values. This can be used with only the
Number Datatype. The syntax is
SUM(Column_Name)
 COUNT( ) – This function returns where expression is Not Null.
Ex : Select COUNT(*) from Emp;
The above will display all the rows which counts all rows belonging to Emp Table.

T.V.N. HANUMANTHA RAO Page 10


NRI IT, Department of MCA DBMS LAB

Ex : Select COUNT(Comm) from Emp;


The above will display the number of values present in the particular column.
Ex : Select COUNT(Distinct(Sal)) from Emp;
The above will count values of a particular column, but eliminates duplicate values while
counting.
Special Functions :
 NVL( ) – It is used to handle Null Values. The syntax is
NVL(expr1, expr2)
If expr1 is Null, returns expr2; If expr1 is Not Null returns expr1.
Ex : Select NVL(Comm, 0) from Emp;
The above is used to replace Null Values with zero.
 VSIZE( ) – It returns the number of bytes in the internal representation of expr. If expr is Null, the
function returns Null. The syntax is
VSIZE(Expr)
Ex : Select Ename, VSIZE(Ename) “Bytes” from Emp;
 UID( ) – It returns an integer that uniquely identifies the current user. The syntax is
UID
Ex : Select UID from Dual;

Queries :
1. Write a Query to display empno & total salary of all the employees.
Select empno, sal + comm “Total Salary” from emp;
EMPNO Total Salary
---------- ------------
7369
7499 1900
7521 1750
2. Display the employee name, annual salary for all the employees.
Select ename, 12 * sal “Annual Salary” from emp;
ENAME Annual Salary
-------------------- -------------
SMITH 11040
ALLEN 19200
WARD 15000

T.V.N. HANUMANTHA RAO Page 11


NRI IT, Department of MCA DBMS LAB

3. Display the name & hiredate of every employee who was hired in the year 1982.
Select ename, hiredate from emp where hiredate like „%82‟);
ENAME HIREDATE
-------------------- ---------
MILLER 23-JAN-82
4. Display the names of all the employees who are working as Clerks and drawing the salary
more than 3000.
Select ename, job from emp where job = „Clerk‟ and sal > 3000;
No Rows Selected
5. Display the empno & names for all the employees who are earning Commission.
Select empno, ename from emp where comm is NOT NULL;
EMPNO ENAME
---------- --------------------
7499 ALLEN
7521 WARD
7654 MARTIN
7844 TURNER
6. Display the names of employees who are working as Clerks, Salesman or Analyst and drawing
salary more than 4000.
Select ename, job from emp where job in („CLERK‟,‟SALESMAN‟,‟ANALYST‟) and sal > 4000;
ENAME JOB
-------------------- ----------
ADAMS CLERK
7. Display the names of employees who are working for the past 5 years.
Select ename, hiredate from emp where months_between(sysdate,hiredate) > 60;
ENAME HIREDATE
-------------------- ---------
SMITH 17-DEC-80
ALLEN 20-FEB-81
WARD 22-FEB-81
8. Display the list of employees who have joined the company before 30th june 1990 or after 31st
dec 1990.
Select * from emp where hiredate < ‟30-jun-1990‟ and hiredate > ‟31-dec-1990‟;
No Rows Seleted

T.V.N. HANUMANTHA RAO Page 12


NRI IT, Department of MCA DBMS LAB

9. Display the total number of employees working in the Company.


Select count(*) from emp;
COUNT(*)
----------
14
10. Display the total salary being paid to all the employees.
Select sum(sal) from emp;
SUM(SAL)
----------
39045
11. Display the total salary drawn by analyst working in department number 40.
Select empno, ename, sal from emp where deptno = 40 and job = „ANALYST;
No Rows Selected
12. Display the name of the employee along with their annual salary.
Select empno, ename, sal, sal * 12 “Annual Salary” from emp;
EMPNO ENAME SAL Annual Salary
---------- -------------------- ---------- -------------
7369 SMITH 920 11040
7499 ALLEN 1600 19200
7521 WARD 1250 15000
13. Display the maximum salary being paid in department number 20.
Select max(sal) from emp where deptno = 20;
MAX(SAL)
----------
11000
14. Display the average salary drawn by managers.
Select avg(sal) from emp where job = „MANAGER‟;
AVG(SAL)
----------
2758.33333
15. Display the names of employees in the order of salary i.e., the name of the employee earning
lowest salary should appear first.
Select empno, ename, sal from emp order by sal;

T.V.N. HANUMANTHA RAO Page 13


NRI IT, Department of MCA DBMS LAB

EMPNO ENAME SAL


---------- -------------------- ----------
7369 SMITH 920
7900 JAMES 950
7521 WARD 1250
16. Display the names of employee in descending order of salary.
Select empno, ename, sal from emp order by sal desc;
EMPNO ENAME SAL
---------- -------------------- ----------
7876 ADAMS 11000
7839 KING 5000
7902 FORD 3000
17. Display employee number, ename, deptno and salary. Sort the output first based on name and
within the name by deptno and within the deptno by salary.
Select empno, ename, deptno, sal from emp order by ename, deptno, sal;

EMPNO ENAME DNO SAL


---------- -------------------- ---------- ----------
7876 ADAMS 20 11000
7499 ALLEN 30 1600
7698 BLAKE 30 2850
7782 CLARK 10 2450
7902 FORD 20 3000
18. Display the deptno and total number of employees within each department.
Select deptno, count(*) from emp group by deptno;
DNO COUNT(*)
---------- ----------
30 6
20 5
10 3
19. Display the various jobs and total number of employees with each job group.
Select job, count(*) from emp group by job;

T.V.N. HANUMANTHA RAO Page 14


NRI IT, Department of MCA DBMS LAB

JOB COUNT(*)
---------- ----------
CLERK 4
SALESMAN 3
PRESIDENT 1
20. Display the department numbers and maximum salary for each department.
Select deptno, max(sal) from emp group by deptno;
DNO MAX(SAL)
---------- ----------
30 2850
20 11000
10 5000
21. Display the department numbers with more than 3 employees in each department.
Select deptno, count(*) from emp group by deptno having count(*) > 3;
DNO COUNT(*)
---------- ----------
30 6
20 5

T.V.N. HANUMANTHA RAO Page 15


NRI IT, Department of MCA DBMS LAB

Experiment - 3
Aim : Implementation of different types of Joins with suitable Examples
JOINS IN SQL :
In SQL, Join technique is used to define relationship among multiple tables. The syntax for Join is
Select Columns From Table1, Table2 where <Join_Condition>;
There are different types of Joins in SQL. They are
 Simple Join
 Self Join / Inner Join
 Outer Join
Simple Join : It retrieves rows from two tables having common columns. It is the most common type of
joins used in the SQL and it is classified into two types like
a. Equi Join
b. Non-Equi Join
a. Equi Join : It is the join which is based on the equality condition in the WHERE clause. This is
obtained by basing on the common columns existing in both the tables. The WHERE clause uses “=
“ operator to perform an Equi Join operation.
Ex : List the Employee Number, Names along with their Department Numbers and Department
Names.
Query : Select e.Empno, e.Ename, d.Deptno, d.Dname FROM Emp e, Dept d
WHERE e.Deptno = d.Deptno;
b. Non-Equi Join: It is the join which is based on non equality condition in the WHERE clause of the
query i.e., WHERE clause uses other than “=“ operator to perform this join operation.
Ex : List Employee Numbers, Names and their Salaries along with Salary Grades from Salgrade
Table.
Query : Select e.Empno, e.Ename, e.Sal, s.Grade FROM Emp e, Salgrade s
WHERE e.Sal BETWEEN s.Losal AND s.Hisal;

Self Join : A table can join by itself which is known as Self Join. In this Join, the row of a table can join
with another row of the same table.
Ex : Suppose we want to know the names and jobs of those employees who are paid same or more than the
employee “RAMAN”.
Query : Select x.Ename, x.Job FROM Emp x, Emp y
WHERE x.Sal >= y.Sal AND y.Ename=‟RAMAN‟;

T.V.N. HANUMANTHA RAO Page 16


NRI IT, Department of MCA DBMS LAB

Outer Join : This is the join which returns all the rows returned by a simple join as well as those rows from
one table that don‟t match any row from the other table. The symbol (+) is used in this join.
Ex : List the department wise employees even though department may not have employees.
Query : Select e.Ename, d.Deptno, d.Dname FROM Emp e, Dept d
WHERE e.Deptno (+)= d.Deptno;

T.V.N. HANUMANTHA RAO Page 17


NRI IT, Department of MCA DBMS LAB

Experiment - 4
Aim : Create Views, Sequence and Indexes for a particular Database.
VIEWS in SQL : A View is a logical or virtual table. We can create a view by using CREATE command.
CREATE VIEW emp_salaries AS SELECT empno, ename, sal FROM emp;
We can also drop the view with the command DROP command.
DROP VIEW emp_salaries;
TYPES OF VIEWS : There are different types of views in SQL. Important views of them are given below.
 Simple View : This is the view which is based on a single table.
 Complex View : This is the view which is based on more than one table i.e., this view is created
based on the joining of tables.
Apart from these types, the views can also be subdivided into the following types :
1. Read only View : This is the view that can‟t be modified. So this view can only be used to see the
view content. Therefore when we attempt to modify it then it leads to an error. This view is created
as follows :
Syntax : CREATE VIEW <view_name> AS <Select statement> WITH READ ONLY
CONSTRAINT <constraint_name>;
2. Updatable View : This is the view that allows an updations in the base tables. So we can modify
the data in base tables through this view.
Sequences : A Sequence is a database object which can generate unique, sequential integer values. It can be
used to automatically generate primary key or unique key values. A sequence can be either in an ascending
or a descending order.
Create Sequence seq_sam increment by 1 start with 1 maxvalue 10 minvalue 1;

After creating a sequence, we can access its values with the help of pseudo columns like currval and nextval.
A pseudo column behaves like a table column, but it is not actually stored in the table.
Nextval : It returns initial value of the sequence, when refereed to, for the first time. Later references to
nextval will increment the sequence using the INCREMENT BY clause and return the new value.
Currval : It returns the current value of the sequence which is the value returned by the last reference to
nextval.
Ex : Insert into <table_name> values(seq_name.nextval,col_name1,col_name2,……..);
Indexes : Indexes are optional structures associated with tables. We can create indexes explicitly to speed up
SQL Statement execution on a table. Similar to the indexes in books that helps us to locate information
faster, an Oracle index provides a faster access path to table data. The index points directly to the location of

T.V.N. HANUMANTHA RAO Page 18


NRI IT, Department of MCA DBMS LAB

the rows containing the value. We can create an index on a column or combinations of column using
CREATE INDEX command as follows :
Syntax : Create Index <index_name> on <table_name>(col_name);

T.V.N. HANUMANTHA RAO Page 19


NRI IT, Department of MCA DBMS LAB

Experiment - 5
Aim : Implement different types of Constraints on Relations
Integrity Constraints : It is a rule that restricts the values for one or more columns in a table. In SQL both
CREATE TABLE and ALTER TABLE commands are used to specify these constraints.
Types of Constraints : There are four types of Integrity Constraints. They are

 Domain Integrity Constraints  Referential Integrity Constraints


 Entity Integrity Constraints  Self Referential Integrity Constraints
Domain Integrity Constraints : These are two types. They are
 NOT NULL  CHECK
1. NOT NULL – There may be records in a table that do not have values for every field because the
information may not be available at the time of data entry. When a column is defined as NOT NULL,
then that column becomes a mandatory column i.e., a value must be entered into the column if the record
is to be accepted. A table may have many NOT NULL columns. The NOT NULL constraint can only be
applied at a Column Level.
Ex : Create table Dept (DEPNO Number(4), DNAME Varchar2(20) NOT NULL,
LOC Varchar2(20) NOT NULL);
2. CHECK - This constraint explicitly defines a condition. It must be specified as a logical expression that
evaluates either true or false. Only those rows that satisfy the condition are to be inserted into a table.
The Check Constraint defined at Column Level is
Create table Emp (ENO Number(6), ENAME Varchar2(15),
SAL Number(8,2) CHECK (SAL > 5000), DEPNO Number(3));

The Check Constraint defined at Table Level is


Create table Emp (ENO Number(6), ENAME Varchar2(15),
SAL Number(8,2), DEPNO Number(3), CHECK (SAL > 5000));
Entity Integrity Constraints : An entity is a data recorded in a database. To identify each row uniquely we
need to use these type of constraints. There are two types. They are
 UNIQUE  PRIMARY KEY
UNIQUE – This is used to avoid duplication of values within the rows of a specified column. These
columns allow single NULL Value. If a UNIQUE Key is defined for more than one column then it is called
Composite UNIQUE Key. The UNIQUE Constraint defined at Column Level is
Create table Dept (DEPNO Number(3) UNIQUE, DNAME Varchar2(15),
LOC Varchar2(20));

T.V.N. HANUMANTHA RAO Page 20


NRI IT, Department of MCA DBMS LAB

The UNIQUE Constraint defined at Table Level is


Create table Dept (DEPNO Number(3), DNAME Varchar2(15),
LOC Varchar2(20), UNIQUE(DEPNO));
The example of Composite UNIQUE Constraint is defined as follows :
Create table Student (SNO Number(6), NAME Varchar2(20), SUB_ID Number(5),
MARKS Number(4,1), UNIQUE(SNO, SUB_ID));
PRIMARY KEY - A Primary key is used to uniquely identify each row in the table. A primary key column
in a table has two special attributes.
1. The column cannot be left blank.
2. The data held across the column must be unique.
A single column PRIMARY KEY is called a simple KEY. A multi-column PRIMARY KEY is
called a Composite PRIMARY KEY. The PRIMARY KEY Constraint defined at Column Level is
Create table Emp (ENO Number(4) PRIMARY KEY, ENA Varchar2(20),
SAL Number(10,2), JOB Varchar2(15), DEPNO Number(4));
The PRIMARY KEY Constraint defined at the Table Level is
Create table Emp (ENO Number(4), ENA Varchar2(20), SAL Number(10,2),
JOB Varchar2(15), DEPNO Number(4), PRIMARY KEY(ENO));
Alter Table Command cannot be used when the column contains rows with duplicate values or
NULL Values for that column.
The PRIMARY KEY Constraint defined using Alter Command is
Alter table Emp add constraint pk_emp primary key(eno);
Alter Table Command cannot be used when the column contains rows with duplicate values or
NULL Values for that column.
Referential Integrity Constraint : It is nothing but a FOREIGN KEY. This represents a relationship
between the tables. The syntax is
Col_Name Datatype(Size) REFERENCES Table_Name(Col_Name) [On Delete Cascade]
The FOREIGN KEY defined at the Column Level is
Create table Emp (ENO Number(4), ENA Varchar2(20), SAL Number(6,2),
JOB Varchar2(15), DEPNO Number(4) REFERENCES Dept(DEPNO));
The FOREIGN KEY defined at the Table Level is
Create table Emp (ENO Number(4), ENA Varchar2(20), SAL Number(6,2),
JOB Varchar2(15), DEPNO Number(4),
FOREIGN KEY(DEPNO) REFERENCES Dept(DEPNO) On Delete Cascade);

T.V.N. HANUMANTHA RAO Page 21


NRI IT, Department of MCA DBMS LAB

When FOREIGN KEY is given with On Delete Cascade option, when we delete DEPNO value from
the Dept table then the corresponding rows in the Emp table will also be deleted.
The FOREIGN KEY Constraint defined using Alter Command is
Alter table Emp add constraint fk_dno Foreign key(dno) references dept(dno);
Alter Table Command cannot be used when the column contains rows with duplicate values or
NULL Values for that column.
Self Referential Integrity Constraint : A column in a table if referencing to another column in the same
table then it is called Self Referential Integrity Constraint. It is given as follows :
Create table Emp (ENO Number(4) PRIMARY KEY, ENAME Varchar2(20),
JOB Varchar2(15), MGR Number(4), SAL Number(10,2),
DEPNO Number(4), FOREIGN KEY(MGR) REFERENCES Emp(ENO));

T.V.N. HANUMANTHA RAO Page 22


NRI IT, Department of MCA DBMS LAB

Experiment - 6
Aim : Implementation of Sub Queries and Nested Queries
SUB-QUERIES : In Oracle a sub-query will provide an alternative approach to a Join technique. The sub-
query means the query within a query. A Sub-query is also referred to as Inner Query or Nested Query which
is embedded within the WHERE clause. A sub-query is used to return the data that will be used in the main
query as a condition to further restrict the data to be retrieved.
Sub-queries with the SELECT Statement :
 Subqueries are most frequently used with the SELECT statement.
SQL > Select * FROM Customers WHERE Id IN (Select Id FROM Customers
WHERE Salary > 4500);
Sub-queries with the INSERT Statement :
Sub-queries can also be used with INSERT statement. The INSERT statement uses the data returned
from the sub-query to insert into another table. The selected data in the sub-query can be modified with any
of the character, date or number functions.
SQL > Insert INTO Customers_Bkp AS Select * FROM Customers
WHERE Id IN (Select Id FROM Customers);
Sub-queries with the UPDATE Statement :
The sub-query can be used in conjunction with the UPDATE statement. Either single or multiple
columns in a table can be updated when using a sub-query with the UPDATE statement.
SQL > Update Customers SET Salary = Salary * 0.25
WHERE Age IN (Select Age FROM Customers_Bkp WHERE AGE >= 27 );
Sub-queries with the DELETE Statement :
The sub-query can be used in conjunction with the DELETE statement like with any other
statements mentioned above.
SQL > Delete FROM Customers WHERE Age IN (Select Age FROM Customers_Bkp
WHERE Age > 27);

T.V.N. HANUMANTHA RAO Page 23


NRI IT, Department of MCA DBMS LAB

Queries :
1. Display the names of employees who are not working as Managers
Select * from emp where empno not in (Select mgr from emp where mgr is NOT NULL);
EMPNO ENAME JOB MGR HIREDATE SAL COMM DNO
---------- -------------- ---------- ------- --------- ---------- ---------- ----------
7844 TURNER SALESMAN 7698 08-SEP-81 1500 0 30
7521 WARD SALESMAN 7698 22-FEB-81 1250 500 30
7654 MARTIN SALESMAN 7698 28-SEP-81 1250 1400 30
2. Display the name of the salesman who earns a salary more than the highest salary of any Clerk
Select empno, ename from emp where job= „SALESMAN‟ and sal > (Select max(sal) from emp
where job = „CLERK‟);
No Rows Selected

3. Display the name of the employees who earn the highest salary in their respective
departments.
Select * from emp e where sal = (Select max(sal) from emp where deptno = e.deptno);
EMPNO ENAME JOB MGR HIREDATE SAL COMM DNO
---------- --------------- ---------- ------- --------- -------- ---------- ----------
7698 BLAKE MANAGER 7839 01-MAY-81 2850 30
7839 KING PRESIDENT 17-NOV-81 5000 10
7876 ADAMS CLERK 7788 23-MAY-87 11000 20
4. Display the employee details who are working in Accounting Department
Select ename from emp where deptno = (Select deptno from dept where dname =
„ACCOUNTING‟);
No Rows Selected
5. Display the employees from department number 10 with salary greater than that are of all
employees working in other departments.
Select ename, sal, deptno from emp e where deptno = 10 and sal > any (Select sal from emp where
e.deptno != deptno);
ENAME SAL DNO
-------------- ---------- ----------
CLARK 2450 10
KING 5000 10
MILLER 1300 10

T.V.N. HANUMANTHA RAO Page 24


NRI IT, Department of MCA DBMS LAB

6. Update the salary of each employee by 10% those who are not eligible for commission.
Update emp set sal = sal + (sal * 10/100) where comm Is Null;
7. Display the managers whose salary is more than an average salary of these employees.
Select ename, sal from emp e where empno in (Select mgr from emp) and e.sal > (select avg(sal)
from emp where mgr = e.empno);
ENAME SAL
-------------------- ----------
FORD 3000
BLAKE 2850
KING 5000
CLARK 2450
8. Find out the least 5 earners of the company.
Select * from emp e where 5 > (Select count(*) from emp where sal < e.sal) order by sal;
EMPNO ENAME JOB MGR HIREDATE SAL COMM DNO
---------- --------------- ---------- -------- --------- ---------- ---------- ----------
7369 SMITH CLERK 7902 17-DEC-80 920 20
7900 JAMES CLERK 7698 03-DEC-81 950 30
7521 WARD SALESMAN 7698 22-FEB-81 1250 500 30
st
9. Display the employees who are going to retire on 31 dec 1999 or if the maximum period is 18
years.
Select * from emp where (to_date(‟31-dec-99‟)-hiredate)/365 > 18;
EMPNO ENAME JOB MGR HIREDATE SAL COMM DNO
---------- ------------- ---------- ------- --------- -------- ---------- ---------
7369 SMITH CLERK 7902 17-DEC-80 920 20
7499 ALLEN SALESMAN 7698 20-FEB-81 1600 300 30
7521 WARD SALESMAN 7698 22-FEB-81 1250 500 30
10. Display the employees whose salary is odd value.
Select * from emp where mod(sal,2) = 1;
EMPNO ENAME JOB MGR HIREDATE SAL COMM DNO
---------- ------------ ---------- -------- --------- ---------- ---------- ----------
7566 JONES MANAGER 7839 02-APR-81 2975 20
11. Delete the records where the number of employees in a particular department is less than 3.
Delete from emp where deptno in (Select deptno from emp group by deptno having count(*) > 3);
11 Rows Deleted

T.V.N. HANUMANTHA RAO Page 25


NRI IT, Department of MCA DBMS LAB

12. List all the employees with hiredate in the format ‘Mar 3 2024’.
Select to_char(hiredate,‟month dd yyyy‟) Format from emp;
FORMAT
-----------------
december 17 1980
february 20 1981
february 22 1981
april 02 1981
september 28 1981
may 01 1981

T.V.N. HANUMANTHA RAO Page 26


NRI IT, Department of MCA DBMS LAB

Experiment - 7
Aim : Implement Queries on Group by & Having Clauses, Alias, Sequence by, Order by
Basic form of SQL Query
SQL > Select [DISTINCT] list of columns
From list of tables
[WHERE condition
ORDER BY column[s] [DESC]
GROUP BY column[s]
HAVING condition];
SELECT : This clause consists of the columns that we want to retrieve from the tables given in the FROM
clause.
FROM : This clause consists of the tables from which the data has to be retrieved.
DISTINCT : This clause can be used to retrieve only those values that are different from one another.
WHERE : This is an optional clause which can be used to mention a condition and based on that the data
will be retrieved.
Ex: Select Empno, Ename, Sal From Emp WHERE Deptno = 10;
The above query lists the employee details who work in the department number 10.
ORDER BY : This is also an important optional clause which helps to list the values in a particular order.
Ex : Select Empno, Ename, Sal From Emp ORDER BY Sal DESC;
The above query lists the employee details in the order of their salary in descending order.
GROUP BY : This is another optional clause that can be used to group the rows with the same values of one
or more specified column values.
Ex : Select Deptno, SUM(Sal), AVG(Sal) From Emp GROUP BY Dept;
The above query gives the information about sum and average of salaries of department wise.
HAVING : This clause is very much similar to WHERE clause except that it can be used only with the
combination of GROUP BY clause.
SQL > Select Deptno From Emp GROUP BY Deptno HAVING COUNT(Empno) = 1;
The above query gives the departments in which only one employee is working.

T.V.N. HANUMANTHA RAO Page 27


NRI IT, Department of MCA DBMS LAB

Experiment – 8
a) Write a PL/SQL Block for Addition of two Numbers.
declare
x number(5);
y number(5);
z number(7);
begin
x:=10;
y:=20;
z:=x+y;
dbms_output.put_line('Sum is '||z);
end;
/

Output :
Sum is 30

T.V.N. HANUMANTHA RAO Page 28


NRI IT, Department of MCA DBMS LAB

b) Write a PL/SQL Block for If, If and Else Condition.


declare
a number:=&a;
begin
if a mod 2=0 then
dbms_output.put_line('Given Number is Even‟);
else
dbms_output.put_line('Given Number is Odd‟);
end if;
end;
/

Output :
Enter value for a : 4
Given Number is Even

Enter value for a : 3


Given Number is Odd

T.V.N. HANUMANTHA RAO Page 29


NRI IT, Department of MCA DBMS LAB

c) Write a PL/SQL Block for implementation of Loops.


declare
r number;
n number:=&n;
s number:=0;
i number;
f number;
t number;
begin
t:=n;
while t>0
loop
r:=t mod 10;
f:=1;
for i in 1..r
loop
f:=f*i;
end loop;
s:=s+f;
t:=trunc(t/10);
end loop;
if s=n then
dbms_output.put_line('Given number is Strong Number');
else
dbms_output.put_line('Given Number is not Strong Number');
end if;
end;
/
Output :
Enter value for n : 145
old 3: n number:=&n;
new 3: n number:=145;
Given number is Strong Number
PL/SQL procedure successfully completed.

T.V.N. HANUMANTHA RAO Page 30


NRI IT, Department of MCA DBMS LAB

d) Write a PL/SQL Block for Greatest of 3 Numbers using If and Else If


DECLARE
a NUMBER := 46;
b NUMBER := 67;
c NUMBER := 21;
BEGIN
IF a > b AND a > c THEN
dbms_output.Put_line('Greatest number is ' ||a);
ELSIF b > a AND b > c THEN
dbms_output.Put_line('Greatest number is „||b);
ELSE
dbms_output.Put_line('Greatest number is '||c);
END IF;
END;

Output :
Greatest Number is 67

T.V.N. HANUMANTHA RAO Page 31


NRI IT, Department of MCA DBMS LAB

Experiment - 9
Aim : Exception Handling – Implement the following with respect to Exception Handling
Raising Exceptions, User Defined Exceptions, Pre-defined Exceptions.
Create or Replace Procedure pemp(eno number) is t_sal number(7,2);
sal_excp exception;
v_error number;
v_message varchar2(50);
begin
select sal into t_sal from emp where empno=eno;
if t_sal is NULL then
raise sal_excp;
end if;
update emp set sal=sal+t_sal*0.15 where empno=eno;
exception
when NO_DATA_FOUND then
dbms_output.put_line('NO SUCH EMPLOYEE WITH EMPNO'||eno);
when sal_excp then
dbms_output.put_line('SALARY IS NULL');
when others then
v_error:=sqlcode;
v_message:=sqlerrm;
dbms_output.put_line(v_error||' : '||v_message);
end;
/

Output :
SQL > Select * emp;
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

T.V.N. HANUMANTHA RAO Page 32


NRI IT, Department of MCA DBMS LAB

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

SQL> exec pemp(7369);


PL/SQL procedure successfully completed.

SQL > Select * emp;


EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO
----------- ----------- ------ -------- ----------------- ------ ----------- -------------
7369 SMITH CLERK 7902 17-DEC-80 920 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

T.V.N. HANUMANTHA RAO Page 33


NRI IT, Department of MCA DBMS LAB

Experiment - 10
a) Write a PL/SQL Procedure using Positional Parameters.
create or replace function bonus_emp(eno number) return number is tsal emp.sal%type;
bonus number(7,2);
begin
select sal into tsal from emp where empno=eno;
if tsal > 10000 then
bonus:=800;
elsif tsal > 5000 then
bonus:=500;
else
bonus:=300;
end if;
return bonus;
end;
/

Function created.

SQL> select empno ,sal, bonus_emp(empno) Bonus from emp;


EMPNO SAL Bonus
----------- ----------- ------
7369 920 300
7499 1600 300
7521 1250 300
7566 2975 300
7654 1250 300
7698 2850 300
7782 2450 300
7788 3000 300
7839 5000 300
7844 1500 300
7876 1100 300
7900 950 300

T.V.N. HANUMANTHA RAO Page 34


NRI IT, Department of MCA DBMS LAB

b) Write a PL/SQL Procedure for GCD of two Numbers.


declare
num1 number;
num2 number;
t number;
m number;
n number;
begin
num1:= 8;
num2:= 48;
m:=num1;
n:=num2;
while mod(num2, num1)!= 0
loop
t:=mod(num2, num1);
num2:=num1;
num1:=t;
end loop;
dbms_output.Put_line('GCD of '||m||' and '||n||' is '||num1);
end;
/

Output :
GCD of 8 and 48 is 8
PL/SQL Procedure Successfully Completed

T.V.N. HANUMANTHA RAO Page 35


NRI IT, Department of MCA DBMS LAB

c) Write a PL/SQL Procedure for Cursor implementation (Implicit and Explicit)


declare
cursor c1(dnum number) is select sal,comm from emp where deptno=dnum;
tot_wages number(10,2):=0;
hpaid number(3):=0;
hcomm number(3):=0;
begin
for emp_rec in c1(&dnum)
loop
tot_wages:=tot_wages + emp_rec.sal + nvl(emp_rec.comm,0);
if emp_rec.sal > 2000 then
hpaid:=hpaid + 1;
end if;
if emp_rec.comm > emp_rec.sal then
hcomm:=hcomm + 1;
end if;
end loop;
dbms_output.put_line ('TOTAL WAGES : '||tot_wages);
dbms_output.put_line ('EMPLOYEES EARNING MORE THAN 2000 SALARY :
'||hpaid);
dbms_output.put_line ('EMPLOYEES EARNING COMMISSION MORE THAN
THEIR SALARY : '||hcomm);
end;
/

Output :
Enter value for dnum : 20
old 7 : for emp_rec in c1(&dnum)
new 7 : for emp_rec in c1(20)
TOTAL WAGES : 10875
EMPLOYEES EARNING MORE THAN 2000 SALARY : 3
EMPLOYEES EARNING COMMISSION MORE THAN THEIR SALARY : 0

PL/SQL procedure successfully completed

T.V.N. HANUMANTHA RAO Page 36


NRI IT, Department of MCA DBMS LAB

Explicit Cursor
SQL > create table stu(sno number, sna varchar2(15), m1 number, m2 number, m3 number,
grade varchar2(10));
SQL > insert into stu(sno,sna,m1,m2,m3) values (&sno,'&sna',&m2,&m2,&m3);
SQL > Select * from stu;
SQL > Select * from stu;
SNO SNA M1 M2 M3 GRADE
---------- --------------- -------- ------- -------- ----------
1 Anil 65 89 64
2 Ajay 75 85 87
3 Madhu 64 74 89
4 Murali 44 48 42
5 Bhargav 56 86 65
6 Rahul 82 68 54
7 Ravi 35 45 55
8 Chandu 55 47 61
9 Kishore 45 46 47
10 Syam 55 56 53

SQL >
declare
cursor st_grade is select sno,m1,m2,m3 from stu;
no stu.sno%type;
ma1 stu.m1%type;
ma2 stu.m2%type;
ma3 stu.m3%type;
avg1 number(5,2);
grd varchar2(10);
begin
open st_grade;
loop
fetch st_grade into no,ma1,ma2,ma3;
exit when st_grade%notfound;
avg1:=(ma1+ma2+ma3)/3;

T.V.N. HANUMANTHA RAO Page 37


NRI IT, Department of MCA DBMS LAB

if (ma1>=40 and ma2>=40 and ma3>=40) then


if avg1>=60 then
grd:='First';
elsif avg1>50 then
grd:='Second';
else
grd:='Third';
end if;
else
grd:='Fail';
end if;
update stu set grade=grd where sno=no;
end loop;
commit;
close st_grade;
end;
/

Output :
SQL > Select * from stu;
SNO SNA M1 M2 M3 GRADE
---------- --------------- -------- ------- -------- ----------
1 Anil 65 89 64 First
2 Ajay 75 85 87 First
3 Madhu 64 74 89 First
4 Murali 44 48 42 Third
5 Bhargav 56 86 65 First
6 Rahul 82 68 54 First
7 Ravi 35 45 55 Fail
8 Chandu 55 47 61 Second
9 Kishore 45 46 47 Third
10 Syam 55 56 53 Second

T.V.N. HANUMANTHA RAO Page 38


NRI IT, Department of MCA DBMS LAB

Experiment - 11
a) Write a PL/SQL Block to implement Factorial using Functions

Program :
create or replace function fact(n number) return number is
begin
if n=1 then
return 1;
else
return n*fact(n-1);
end if;
end fact;
/

Function created.

Main Program :
declare
n number(4):=&n;
n1 number(8);
begin
n1:=fact(n);
dbms_output.put_line('Factorial of '||n||‟ is '||n1);
end;
/

Output :
Enter value for n : 5
Factorial of 5 is 120
PL/SQL Procedure Successfully Completed

T.V.N. HANUMANTHA RAO Page 39


NRI IT, Department of MCA DBMS LAB

b) Write a PL/SQL Function to search an address from the given Database

SQL> create table emp1(empid number,address varchar2(30));


Table created.

SQL> insert into emp1 values(&empid,'&address');

SQL > select * from emp1;


EMPID ADDRESS
---------- ---------------------
1 guntur
2 vijayawada
3 hyderabad
4 narasaraopet

SQL >
create or replace function get_address(v_empid emp1.empid%type) return emp1.address%type is
v_address emp1.address%type;
begin
select address into v_address from emp1 where empid=v_empid;
return v_address;
end get_address;
/

SQL >
declare
v_address emp1.address%type;
v_empid emp1.empid%type:=&v_empid;
begin
v_address:=get_address(v_empid);
dbms_output.put_line('Address is : '||v_address);
end;
/

T.V.N. HANUMANTHA RAO Page 40


NRI IT, Department of MCA DBMS LAB

Enter value for v_empid: 2


old 3: v_empid emp1.empid%type:=&v_empid;
new 3: v_empid emp1.empid%type:=2;
Address is : vijayawada

PL/SQL procedure successfully completed.

T.V.N. HANUMANTHA RAO Page 41


NRI IT, Department of MCA DBMS LAB

Experiment - 12
Aim : Write a DBMS Program to prepare PL/SQL Reports for an Application using
Functions.
SQL > Select * from emp;
SQL > Select * from dept;
SQL > Set Pagesize 10
SQL > Set Linesize 150
SQL > Set Pause on
SQL > Set Pause „Press any Key…..‟
SQL > Ttitle center „Employee Report‟
SQL > Btitle center „End of Report‟
SQL > Column sal format 99999.99
SQL > Column ename format A5 trunc
SQL > Spool c:\Hanu\emp_report.txt
SQL > Select e.empno, e.ename, e.sal, d.dname, d.dno from emp e, dept d where e.dno = d.dno;
SQL > Clear column
SQL > Btitle off
SQL > Ttitle off
SQL > Set Linesize 80
SQL > Set Pagesize 24
SQL > Spool off

T.V.N. HANUMANTHA RAO Page 42


NRI IT, Department of MCA DBMS LAB

Experiment - 13
a) Write a Trigger to pop-up the DML Operations

SQL>
Create or replace trigger emp_trigger before insert or update or delete on emp
declare
cday varchar2(15);
chours number;
begin
cday:=to_char(sysdate,'day');
chours:=to_number(to_char(sysdate,'hh24'));
if inserting or updating or deleting then
if (ltrim(rtrim(cday))='sunday') then
raise_application_error(-20100,'Today is Sunday, No Operation');
end if;
if chours > 17 or chours < 8 then
raise_application_error(-20100,'Office Hours Over, No Transactions');
end if;
end if;
end;
/

Trigger created.

T.V.N. HANUMANTHA RAO Page 43


NRI IT, Department of MCA DBMS LAB

b) Write a Trigger to check the Age valid or not using Message Alert

SQL > Create table stu1(sno number, sna varchar2(20), dob date);
SQL >
create or replace trigger check_age_validity before insert or update on stu1
for each row
declare
v_age number;
begin
v_age:=trunc(months_between(sysdate,:NEW.dob)/12);
if v_age<18 then
dbms_output.put_line('Age is not Valid. Must be 18 years or Older.');
raise_application_error(-20001,‟Age is not Valid. Must be 18 years‟);
end if;
end;
/

Trigger Created

SQL > insert into stu1 values(3,'b','10-oct-10');


Age is not Valid. Must be 18 years or Older.
insert into stu1 values(3,'b','10-oct-10')
*
ERROR at line 1:
ORA-20001: Age is not Valid. Must be 18 years
ORA-06512: at "SYSTEM.CHECK_AGE_VALIDITY", line 7
ORA-04088: error during execution of trigger 'SYSTEM.CHECK_AGE_VALIDITY'

T.V.N. HANUMANTHA RAO Page 44


NRI IT, Department of MCA DBMS LAB

c) Create a Trigger to raise appropriate Error Code and Error Message

SQL >
create or replace trigger check_salary before insert or update of sal on emp for each row
declare
v_error_code number;
v_error_message varchar2(100);
begin
if :NEW.sal<0 then
v_error_code:=-20001;
v_error_message:='Salary cannot be Negative';
raise_application_error(v_error_code,v_error_message);
elsif :NEW.sal>10000 then
v_error_code:=-20002;
v_error_message:='Salary cannot exceed 10000';
raise_application_error(v_error_code,v_error_message);
end if;
end;
/

Trigger created.

SQL > insert into emp(empno,ename,sal) values(1234,'ABC',11000);


insert into emp(empno,ename,sal) values(1234,'ABC',11000)
*
ERROR at line 1 :
ORA-20002: Salary cannot exceed 10000
ORA-06512: at "SYSTEM.CHECK_SALARY", line 12
ORA-04088: error during execution of trigger 'SYSTEM.CHECK_SALARY'

T.V.N. HANUMANTHA RAO Page 45


NRI IT, Department of MCA DBMS LAB

d) Create a Trigger on a Table so that it will update another table while inserting values.

SQL > Create table stu_audit as select * from student;


SQL > Truncate table stu_audit;
SQL >
create or replace trigger update_trigger after insert on student
for each row
begin
insert into stu_audit(sno,sna,age) values (:NEW.sno,:NEW.sna,:NEW.age);
end;
/

Trigger created.

SQL > Insert into student(sno, sna, age) values (5, „E‟, 20);

SQL > Select * from stu_audit;


SNO SNA AGE
---------- -------------------- ----------
5 E 20

T.V.N. HANUMANTHA RAO Page 46


NRI IT, Department of MCA DBMS LAB

Experiment - 14
Aim : Write a PL/SQL Block for an Application using Cursors and all types of Triggers.

SQL > create table employees(emp_id number,ename varchar2(20),sal number);


Table created.
SQL > insert into employees values(1001,'ABC',4000);
1 row created.
SQL >
declare
cursor employee_cursor is
select emp_id,ename,sal from employees;
v_emp_id employees.emp_id%type;
v_emp_name employees.ename%type;
v_salary employees.sal%type;
v_trigger_demo number;
begin
open employee_cursor;
loop
fetch employee_cursor into v_emp_id,v_emp_name,v_salary;
exit when employee_cursor%NOTFOUND;
dbms_output.put_line('Employee Id : '||v_emp_id||', Name : '||v_emp_name||', Salary :
'||v_salary);
end loop;
close employee_cursor;
insert into employees(emp_id,ename,sal) values(101,'Ram',5000);
update employees set sal=sal*1.1 where emp_id=1001;
delete from employees where emp_id=101;
select count(*) into v_trigger_demo from employees;
dbms_output.put_line('Number of Employees after Delete : '||v_trigger_demo);
exception
when others then
dbms_output.put_line('Error : '||sqlerrm);
end;
/

T.V.N. HANUMANTHA RAO Page 47


NRI IT, Department of MCA DBMS LAB

Employee Id : 1001, Name : ABC, Salary : 4000


Number of Employees after Delete : 1

PL/SQL procedure successfully completed.

SQL > select * from employees;

EMP_ID ENAME SAL


---------- -------------------- ----------
1001 ABC 4400

T.V.N. HANUMANTHA RAO Page 48


NRI IT, Department of MCA DBMS LAB

Experiment - 15
Aim : Write a PL/SQL Block for Transaction Operations of a typical Application using
Package.

SQL>
create or replace package ins_del as
procedure ins_emp(eno number,name varchar2,job varchar2,
mgr number,hdate date,sal number,comm number,deptno number);
procedure del_emp(eno number);
end ins_del;
/
Package created.

SQL>
create or replace package body ins_del as
procedure ins_emp(eno number,name varchar2,job varchar2,
mgr number,hdate date,sal number,comm number,deptno number) is
begin
insert into emp values(eno,name,job,mgr,hdate,sal,comm,deptno);
end ins_emp;
procedure del_emp(eno number) is
enum number;
begin
select empno into enum from emp where empno=eno;
delete from emp where empno=eno;
exception
when NO_DATA_FOUND then
dbms_output.put_line('NO SUCH EMPLOYEE WITH empno
EXISTS '||eno);
end del_emp;
end ins_del;
/
Package body created.

T.V.N. HANUMANTHA RAO Page 49


NRI IT, Department of MCA DBMS LAB

SQL> exec ins_del.ins_emp(1234, 'xxxx', 'PROGRAM', 2345, to_date('25-MAR-2006', 'dd-mon-yyyy'),


4000, 0, 20);

PL/SQL procedure successfully completed.

SQL> exec ins_del.del_emp(1234);

PL/SQL procedure successfully completed.

T.V.N. HANUMANTHA RAO Page 50

You might also like