DBMS_LAB
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‟);
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
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);
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);
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;
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;
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.
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.
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
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
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
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‟;
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;
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
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);
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
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));
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);
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
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
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
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.
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
Output :
Enter value for a : 4
Given Number is Even
Output :
Greatest Number is 67
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
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.
Output :
GCD of 8 and 48 is 8
PL/SQL Procedure Successfully Completed
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
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;
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
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
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;
/
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
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.
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 >
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.
d) Create a Trigger on a Table so that it will update another table while inserting values.
Trigger created.
SQL > Insert into student(sno, sna, age) values (5, „E‟, 20);
Experiment - 14
Aim : Write a PL/SQL Block for an Application using Cursors and all types of Triggers.
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.