DBMS Practical Example For Students
DBMS Practical Example For Students
Department of Computer
Engineering
SE/COMP/SEMIV
For Functions :
https://www.plsqltutorial.com/plsql-function/
For Procedure:
https://www.plsqltutorial.com/plsql-procedure/
In this example, we create a table called "employees" with the following columns:
employee_id: a numeric column with a maximum of 5 digits, set as the primary key of the table.
first_name and last_name: string columns that cannot be null.
email: a string column with a maximum length of 100 characters, with a unique constraint applied to
ensure no duplicate emails are stored.
hire_date: a date column that defaults to the current system date when a new row is inserted.
salary: a numeric column that must have a value greater than 0.
department_id: a numeric column that references the department_id column in another table called
"departments", with the constraint that if a department is deleted, the corresponding department_id
value in the "employees" table should be set to NULL.
Date constraints: Date constraints can be used to restrict the values that can be entered into a date column.
For example, the following statement creates a table with a hire_date column that must be between January
1, 2000 and December 31, 2022
Page 2
CREATE TABLE employees (
employee_id NUMBER(5) PRIMARY KEY,
first_name VARCHAR2(50) NOT NULL,
last_name VARCHAR2(50) NOT NULL,
salary NUMBER(10,2) CHECK (salary BETWEEN 1000 AND 100000)
);
Range constraints: Range constraints can be used to restrict the values that can be entered into a numeric
column to a specific range. For example, the following statement creates a table with a salary column that
must be between 1000 and 100000
Unique constraint: A unique constraint can be used to ensure that no duplicate values are entered into a
column. For example, the following statement creates a table with an email column that must be unique
Not null constraint: A NOT NULL constraint can be used to ensure that a column must have a value
entered into it when a row is inserted or updated. For example, the following statement creates a table with
a phone_number column that cannot be null
creating a table with a constraint that requires a specific column value to start with a certain number
Example of creating a table with a constraint that requires a specific column value to start with a
certain string (An)
Page 3
creating a table with a check constraint for city value to be one of Pune or Mumbai and Cname must
be in capital letters
Inserting Date
INSERT INTO employees (employee_id, first_name, last_name, email, phone_number, hire_date, job_id,
salary, commission_pct, manager_id, department_id)
VALUES (100, 'Steven', 'King', '[email protected]', '515.123.4567', TO_DATE('17-JUN-1987',
'DD-MON-YYYY'), 'AD_PRES', 24000, NULL, NULL, 90);
Page 4
Triggers Queries
1. BEFORE INSERT trigger to automatically set a new employee's hire date to the current date:
2. Create a trigger that will prevent a record from being inserted into the employees table if the salary
is less than 1000.
Page 5
3. Create a trigger that outputs a message to the console, indicating the old and new salaries for the
employee.
Page 6
Functions
1. Create a function that will calculate the age of a person based on their date of birth.
DECLARE
emp_age NUMBER;
BEGIN
emp_age := calculate_age(TO_DATE('01-JAN-1980', 'DD-MON-YYYY'));
DBMS_OUTPUT.PUT_LINE('Employee Age: ' || emp_age);
END;
/
2. Create a function that will return the total number of employees in a department based on the
department ID.
DECLARE
dept_size NUMBER;
BEGIN
dept_size := get_department_size(60);
DBMS_OUTPUT.PUT_LINE('Department Size: ' || dept_size);
END;
/
Page 7
Procedure
1. Create a procedure that will insert a new record into the employees table.
BEGIN
add_employee(1,'John', 'Doe', '[email protected]', SYSDATE, 'IT_PROG', 5000, 100, 60);
END;
/
2. Create a procedure that will update the salary of an employee based on their employee ID.
BEGIN
update_employee_salary(100, 6000);
END;
/
Page 8
For Practical
SOLUTION:
1. Creating a Database
CREATE DATABASE Company;
Page 9
CREATE TABLE EMPLOYEE
(SSN VARCHAR2 (20) PRIMARY KEY,
FNAME VARCHAR2 (20),
LNAME VARCHAR2 (20),
ADDRESS VARCHAR2 (20),
SEX CHAR (1),
SALARY INTEGER,
SUPERSSN REFERENCES EMPLOYEE (SSN),
DNO REFERENCES DEPARTMENT (DNO));
NOTE: Once DEPARTMENT and EMPLOYEE tables are created we must alter department
table to add foreign constraint MGRSSN using sql command
Page 10
INSERT INTO DEPARTMENT VALUES (‗3‘,‘ECE‘,‘01-JUN-08‘,‘RNSECE01‘);
INSERT INTO DEPARTMENT VALUES (‗4‘,‘ISE‘,‘01-AUG-15‘,‘RNSISE01‘);
INSERT INTO DEPARTMENT VALUES (‗5‘,‘CSE‘,‘01-JUN-02‘,‘RNSCSE05‘);
Update
COMMIT;
On execution of this command all changes to the database made by you are made
permanent and cannot be undone.
A COMMIT is automatically executed when you exit normally from SQL*Plus.
However, it does no harm to occasionally issue a COMMIT command.
A COMMIT does not apply to any SELECT commands as there is nothing to
commit.
A COMMIT does not apply to any DDL commands (eg CREATE TABLE,
CREATE INDEX, etc). These are automatically committed and cannot be rolled
back.
If you wished to rollback (ie undo) any changes made to the database since the
last commit, you can issue the command:
ROLLBACK;
A group of related SQL commands that all have to complete successfully or otherwise be
rolled back, is called a transaction. Part of your research for Outcome 3 includes
investigating transaction processing and the implications of rollback and commit.
Page 11
For Practical
SOLUTION:
Create Table
2. Add a new column PINCODE with not null constraints to the existing table DEPT
Table altered.
Page 12
3. All constraints and views that reference the column are dropped automatically, along
with the column.
Table altered.
Table altered.
SQL> DESC DEPARTMENT;
Name Null? Type
6. Delete table
SQL> DROP TABLE DEPARTMENT;
Table dropped.
Page 13
For Practical
Consider Employee table
E101 45000
E102 70000
E103 12000
0
E105 67000
Page 14
E106 14500
0
3. Retrieve average salary of all employee
SQL> select avg(salary) from
employee; AVG(SALARY)
89400
employee; COUNT(*)
6. Retrieve total salary of employee group by employee name and count similar names
SUM(SALARY)>120000;
EMP_NAME
SUM(SALA
RY)
mahesh 145000
sunita 187000
Page 15
8. Display name of employee in descending order
EMP_NAME
sunita
sunita
mahes
h Amit
Amit
9. Display details of employee whose name is AMIT and salary greater than 50000;
Page 16
For Practical
For a given tables
Page 17
SOLUTION
Table altered.
Page 18
MGRSTARTDATE DATE
MGRSSN VARCHAR2(20)
Note: update entries of employee table to fill missing fields SUPERSSN and DNO
UPDATE EMPLOYEE SET SUPERSSN=NULL, DNO=‘3‘ WHERE
SSN=‘RNSECE01‘;
UPDATE EMPLOYEE SET SUPERSSN=‘RNSCSE02‘, DNO=‘5‘ WHERE
SSN=‘RNSCSE01‘;
UPDATE EMPLOYEE SET SUPERSSN=‘RNSCSE03‘, DNO=‘5‘ WHERE
SSN=‘RNSCSE02‘;
UPDATE EMPLOYEE SET SUPERSSN=‘RNSCSE04‘, DNO=‘5‘ WHERE
SSN=‘RNSCSE03‘;
Page 19
UPDATE EMPLOYEE SET DNO=‘5‘, SUPERSSN=‘RNSCSE05‘ WHERE
SSN=‘RNSCSE04‘; UPDATE EMPLOYEE SET DNO=‘5‘, SUPERSSN=‘RNSCSE06‘
WHERE SSN=‘RNSCSE05‘;
UPDATE EMPLOYEE SET DNO=‘5‘, SUPERSSN=NULL WHERE
SSN=‘RNSCSE06‘;
UPDATE EMPLOYEE SET DNO=‘1‘, SUPERSSN=‘RNSACC02‘ WHERE
SSN=‘RNSACC01‘;
UPDATE EMPLOYEE SET DNO=‘1‘, SUPERSSN=NULL WHERE
SSN=‘RNSACC02‘;
UPDATE EMPLOYEE SET DNO=‘4‘, SUPERSSN=NULL WHERE
SSN=‘RNSISE01‘;
UPDATE EMPLOYEE SET DNO=‘2‘, SUPERSSN=NULL WHERE
SSN=‘RNSIT01‘;
2. Find the sum of the salaries of all employees of the ‘Accounts’ department, as well
as the maximum salary, the minimum salary, and the average salary in this
department
SQL> SELECT SUM(E.SALARY),MAX(E.SALARY),MIN(E.SALARY),
AVG(E.SALARY)FROM EMPLOYEE1 E,DEPARTMENT D WHERE
E.DNO=D.DNUMBER AND D.DNAME='RESEARCH';
E.FNAME,E.LNAME 2
FROM EMPLOYEE1 E
Page 20
3 WHERE EXISTS(SELECT DNO FROM EMPLOYEE1 WHERE E.DNO=5);
4. Retrieve the name of each dept and number of employees working in each
department which has at least 2 employees
SELECT DNAME, COUNT(*)
FROM EMPLOYEE E, DEPARTMENT D
WHERE D.DNO=E.DNO
AND D.DNO IN (SELECT E1.DNO
FROM EMPLOYEE E1
GROUP BY E1.DNO
having count(*)>2 )
ORDER BY DNO;
6. Retrieve the name of employees and their dept name (using JOIN)
Page 21
For Practical View
For a given EMPLOYEE tables
SOLUTION:
Page 22
INSERT INTO EMPLOYEE (SSN, FNAME, LNAME, ADDRESS, SEX, SALARY)
VALUES (‘RNSCSE02‘,‘HEARN‘,‘BAKER‘,‘BANGALORE‘,‘M‘, 700000);
INSERT INTO EMPLOYEE (SSN, FNAME, LNAME, ADDRESS, SEX, SALARY)
VALUES (‘RNSCSE03‘,‘EDWARD‘,‘SCOTT‘,‘MYSORE‘,‘M‘, 500000);
INSERT INTO EMPLOYEE (SSN, FNAME, LNAME, ADDRESS, SEX, SALARY)
VALUES (‘RNSCSE04‘,‘PAVAN‘,‘HEGDE‘,‘MANGALORE‘,‘M‘, 650000);
INSERT INTO EMPLOYEE (SSN, FNAME, LNAME, ADDRESS, SEX, SALARY)
VALUES (‘RNSCSE05‘,‘GIRISH‘,‘MALYA‘,‘MYSORE‘,‘M‘, 450000);
INSERT INTO EMPLOYEE (SSN, FNAME, LNAME, ADDRESS, SEX, SALARY)
VALUES (‘RNSCSE06‘,‘NEHA‘,‘SN‘,‘BANGALORE‘,‘F‘, 800000);
INSERT INTO EMPLOYEE (SSN, FNAME, LNAME, ADDRESS, SEX, SALARY)
VALUES (‘RNSACC01‘,‘AHANA‘,‘K‘,‘MANGALORE‘,‘F‘, 350000);
INSERT INTO EMPLOYEE (SSN, FNAME, LNAME, ADDRESS, SEX, SALARY)
VALUES (‘RNSACC02‘,‘SANTHOSH‘,‘KUMAR‘,‘MANGALORE‘,‘M‘, 300000);
INSERT INTO EMPLOYEE (SSN, FNAME, LNAME, ADDRESS, SEX, SALARY)
VALUES (‘RNSISE01‘,‘VEENA‘,‘M‘,‘MYSORE‘,‘M‘, 600000);
INSERT INTO EMPLOYEE (SSN, FNAME, LNAME, ADDRESS, SEX, SALARY)
VALUES (‘RNSIT01‘,‘NAGESH‘,‘HR‘,‘BANGALORE‘,‘M‘, 500000);
Creating View
The query that defines the sales_staffview references only rows in department 5.
Furthermore, the CHECK OPTION creates the view with the constraint (named
sales_staff_cnst) that INSERT and UPDATE statements issued against the view cannot
result in rows that the view cannot select.
View created.
3. Drop View
Page 23
For Practical Procedure
Given an integer i, write a PL/SQL procedure to insert the tuple (i, 'xxx') into a given relation.
SOLUTION:
CREATE TABLE T2 (
a INTEGER,
b CHAR(10));
Page 24
Study For Theory Only Not in Practical Exam
Page 25
SOLUTION:
Operation Purpose
Select(σ) The SELECT operation is used for selecting a subset of the tuples
according to a given selection condition
Projection(π) The projection eliminates all attributes of the input relation but those
mentioned in the projection list.
Set Difference(-) - Symbol denotes it. The result of A - B, is a relation which includes
all tuples that are in A but not in B.
Intersection(∩) Intersection defines a relation consisting of a set of all tuple that are
in both A and B.
Inner Join Inner join, includes only those tuples that satisfy the matching
criteria.
Theta Join(θ) The general case of JOIN operation is called a Theta join. It is
denoted by symbol θ.
EQUI Join When a theta join uses only equivalence condition, it becomes a equi
join.
Natural Join(⋈) Natural join can only be performed if there is a common attribute
(column) between the relations.
Outer Join In an outer join, along with tuples that satisfy the matching criteria.
Left Outer Join( In the left outer join, operation allows keeping all tuple in the left
) relation.
Page 26
Right Outer join( In the right outer join, operation allows keeping all tuple in the right
) relation.
Full Outer Join( ) In a full outer join, all tuples from both relations are included in the
result irrespective of the matching condition.
Page 27
4. Find all movies and their ratings
πtitle, rating(Movies)
Page 28
6. Find Coen’s movies with McDormand
e1 = πtitle(σactor=‘McDormand_ (Acts))
e2 = πtitle(σdirector=‘Coen_ (Movies))
result = e1 ∩ e2
Consider following databases and draw ER diagram and convert entities and relationships
to relation table for a given scenario.
1. COLLEGE DATABASE:
STUDENT (USN, SName, Address, Phone, Gender)
SEMSEC (SSID, Sem, Sec)
CLASS (USN, SSID)
SUBJECT (Subcode, Title, Sem, Credits)
IAMARKS (USN, Subcode, SSID, Test1, Test2, Test3, FinalIA)
2. COMPANY DATABASE:
EMPLOYEE (SSN, Name, Address, Sex, Salary, SuperSSN, DNo)
DEPARTMENT (DNo, DName, MgrSSN, MgrStartDate)
DLOCATION (DNo,DLoc)
PROJECT (PNo, PName, PLocation, DNo)
WORKS_ON (SSN, PNo, Hours)
Page 29
SOLUTION:
Mapping
entities and
relationships
to relation
table
(Schema
Diagram)
Page 30
COMPANY DATABASE:
E-R Diagram
Schema Diagram
Page 31
Page 32
Page 33