Unit Iii Normalization

Download as pdf or txt
Download as pdf or txt
You are on page 1of 38

Dept.

of Computer Science & Engineering


(Artificial Intelligence)

B. Tech II Year I Semester

23CAI202 DATABASE MANAGEMENT SYSTEMS


LABORATORY
List of Experiments:

1. Design Conceptual database schema using ER Modelling Software Tools.


2. Development of Relational Database Schemas for Deposit/Customer/ borrow/ branch using
DDL Constructs of SQL.
3. To perform various data manipulation commands such as select, insert, update etc. of SQL
on Relational Database.
4. To perform various DCL and TCL construct of SQL on Relational Database.
5. Implement different types of referential and integrity constraints on Relation Database.
6. To apply the concept of Aggregating Data using Group functions.
7. To retrieve the queries using Group by, Having and Order by clauses of SQL.
8. Design and development of Banking database and perform various type of JOIN operations.
9. Insert the Data into table and use COMMIT, ROLLBACK and SAVEPOINT in PL/SQL
10. Write a trigger that automatically deletes students when they graduate
11. Develop programs using features parameters in a CURSOR for UPDATE
12. a) Create a cursor to update the salary of employees in EMP table.
b) Write a PL/SQL program to raise an Exception when the bonus exceeds salary.
13. Design and implementation real time project with database connection.
1. Design Conceptual
database schema using
ER Modelling Software
Tools.
What is an ER Model?
An Entity-Relationship Model represents the structure of the database with the help of a diagram.
ER Modelling is a systematic process to design a database as it would require you to analyze all data
requirements before implementing your database.

History of ER models
Peter Chen proposed ER Diagrams in 1971 to create a uniform convention used as a conceptual modeling tool.

Why Use ER Diagrams in DBMS?


 ER Diagram helps you conceptualize the database and lets you know which fields need to be embedded for a
particular entity
 ER Diagram gives a better understanding of the information to be stored in a database
 It reduces complexity and allows database designers to build databases quickly
 It helps to describe elements using Entity-Relationship
models
 It allows users to get a preview of the logical structure
of the database

Symbols Used in ER Diagrams


 Rectangles: This Entity Relationship Diagram symbol
represents entity types
 Ellipses: This symbol represents attributes
 Diamonds: This symbol represents relationship types
 Lines: It links attributes to entity types and entity types
with other relationship types
 Primary key: Here, it underlines the attributes
 Double Ellipses: Represents multi-valued attributes

Components of ER Diagram
Entities
An entity can be either a living or non-living component.
It showcases an entity as a rectangle in an ER diagram.

Weak Entity
An entity that makes reliance over another entity is called a weak entity
You showcase the weak entity as a double rectangle in ER Diagram.
In the example below, school is a strong entity because it has a primary key attribute - school number.
Unlike school, the classroom is a weak entity because it does not have any primary key and the room number
here acts only as a discriminator.

Attribute
An attribute exhibits the properties of an entity.
You can illustrate an attribute with an oval shape in an ER diagram.

Key Attribute
Key attribute uniquely identifies an entity from an entity set.
It underlines the text of a key attribute.
For example: For a student entity, the roll number can uniquely identify a student from a set of students.
Composite Attribute
An attribute that is composed of several other attributes is known as a composite attribute.
An oval showcases the composite attribute, and the composite attribute oval is further connected with other
ovals.

Multivalued Attribute
Some attributes can possess over one value, those attributes are called multivalued attributes.
The double oval shape is used to represent a multivalued attribute.

Derived Attribute
An attribute that can be derived from other attributes of the entity is known as a derived attribute.
In the ER diagram, the dashed oval represents the derived attribute.
Relationship
The diamond shape showcases a relationship in the ER diagram.
It depicts the relationship between two entities.
In the example below, both the student and the course are entities, and study is the relationship between them.

One-to-One Relationship
When a single element of an entity is associated with a single element of another entity, it is called a one-to-one
relationship.
For example, a student has only one identification card and an identification card is given to one person.

One-to-Many Relationship
When a single element of an entity is associated with more than one element of another entity, it is called a one-
to-many relationship
For example, a customer can place many orders, but an order cannot be placed by many customers.

Many-to-One Relationship
When more than one element of an entity is related to a single element of another entity, then it is called a
many-to-one relationship.
For example, students have to opt for a single course, but a course can have many students.

Many-to-Many Relationship
When more than one element of an entity is associated with more than one element of another entity, this is
called a many-to-many relationship.
For example, you can assign an employee to many projects and a project can have many employees.
Hospital ER Model

 Patients - ID(primary key), name, age,visit_date


 Tests- Name(primary key), date, result
 Doctor- ID(primary key), name, specialization

Company ER Model

 Employee - ENO(Primary Key) , Name, Salary


 Department - DNO(Primary key), Name, Locations
 Project - PNO(Primary key), Name
The Flight Database
The University Database
The Music Database
The BANK database
ER diagram of Library Management System
2. Development of
Relational Database
Schemas for
Deposit/Customer/
borrow/ branch
using
DDL Constructs of SQL.
DDL (Data Definition Language):
CREATE: Creates a new table or database.
ALTER: Modifies an existing database object.
DROP: Deletes an entire table, database, or other objects.
TRUNCATE: Removes all records from a table
Consider following database schema, Write the queries using SQL
branch (branch_name, branch_city, assets)
customer (customer_name, customer_street, customer_city)
loan (loan_number, branch_name, amount)
borrower (customer_name, loan_number)
account (account_number, branch_name, balance)
depositor (customer_name, account_number)

createtable BRANCH (
branch_name varchar(20) primary key, branch_city varchar(20), assets int );

createtable CUSTOMER (
customer_name varchar(20) primary key, customer_street varchar(20), customer_city
varchar(20) );

create table ACCOUNT (


account_number int primary key, branch_name varchar(20), amount int,
foreign key (branch_name) references branch(branch_name) );

create table LOAN (


loan_number int primary key, branch_name varchar(20), amount int,
foreign key (branch_name) references branch(branch_name) );

create table DEPOSITOR (


customer_name varchar(20), account_number int, primary key(customer_name,
account_number), foreign key (customer_name) references customer(customer_name),
foreign key (account_number) references account(account_number) );

create table BORROWER (


customer_name varchar(20), loan_number int, primary key(customer_name,
loan_number), foreign key (customer_name) references customer(customer_name),
foreign key (loan_number) references loan(loan_number) );

create table EMPLOYEE (


employee_name varchar(20), branch_name varchar(20), salary int,
primary key(employee_name, branch_name),
foreign key (branch_name) references branch(branch_name) );
3. To perform various
data manipulation
commands such as select,
insert, update etc. of SQL
on Relational Database.
DML (Data Manipulation Language):
 SELECT: Retrieves data from the database.
 INSERT: Adds new data to a table.
 UPDATE: Modifies existing data within a table.
 DELETE: Removes data from a table.
INSERT BRANCH  (‘JP Nagar’,’Bangalore’,1000), (‘Charchgate’,
’Mumbai’,1500), (‘Red Hill’,’Hyderabad’,2000), (‘Jaya Nagar’,
’Bangalore’, 5000);

INSERT CUSTOMER  (‘c1’,’s1’,’Bangalore’), (‘c2’,’s2’,’Hyderabad’),


(‘c3’,’s3’,’Mumbai’), (‘c4’,’s4’,’Kolkatta’);

INSERT ACCOUNT  (101,’JP Nagar’,5000), (102,’Red Hill’,3000),


(103,’Charchgate’,2000);

INSERT LOAN  (1,’JP Nagar’,3000), (2,’Charchgate’,1000), (3,’Red


Hill’,5000), (4,’Jaya Nagar’,6000);

INSERT DEPOSITOR  (‘c1’,101), (‘c3’,103);

INSERT BORROWER  (‘c1’,1), (‘c4’,4);


-- a) Find all customers who have both a loan and an account (eliminate duplicates if
exists)

SELECT distinct customer_name from borrower WHERE


customer_name IN (SELECT customer_name FROM depositor );

-- b) Find all customers who have a loan or an account or both (eliminate duplicates if
exists)

SELECT customer_name FROM borrower


UNION
SELECT customer_name FROM depositor;

-- c) Find all customers who have a loan but not an account (eliminate duplicates if exists)

SELECT DISTINCT customer_name FROM borrower WHERE


customer_name NOT IN (SELECT customer_name FROM depositor );

-- d) Find all customers who have a loan or an account or both

SELECT customer_name FROM borrower


UNION ALL
SELECT customer_name FROM depositor;

-- e) Find all customers who have both a loan and an account

SELECT customer_name FROM borrower WHERE customer_name IN


(SELECT customer_name FROM depositor );
4. To perform various
DCL and TCL construct
of SQL on Relational
Database.
DCL (Data Control Language):
 GRANT: Gives users access privileges to the database.
 REVOKE: Removes access privileges given with the GRANT command.

TCL (Transaction Control Language):


 COMMIT: Saves all changes made in the current transaction.
 ROLLBACK: Restores the database to the last committed state.
 SAVEPOINT: Sets a savepoint within a transaction.
 SET TRANSACTION: Places a name on a transaction.
CREATE TABLE TEACHERS ( CODE INT NOT NULL, SUBJECT VARCHAR (15) NOT NULL, NAME
VARCHAR (15) NOT NULL, PRIMARY KEY (CODE));

===============================================================================
INSERT INTO TEACHERS VALUES (1, 'SELENIUM', 'TOM');
ROLLBACK;
INSERT INTO TEACHERS VALUES (2, 'UFT', 'SAM');
INSERT INTO TEACHERS VALUES (3, 'JMETERE', 'TONK');
COMMIT;
===============================================================================

SELECT * FROM TEACHERS;


===============================================================================

DELETE FROM TEACHERS WHERE CODE= 3;


ROLLBACK;

SELECT * FROM TEACHERS;


===============================================================================

INSERT INTO TEACHERS VALUES (4, 'CYPRESS', 'MICHEAL');


SAVEPOINT s;
INSERT INTO TEACHERS VALUES (5, 'PYTHON', 'STEVE');
INSERT INTO TEACHERS VALUES (6, 'PYTEST', 'ARNOLD');
ROLLBACK TO s;
INSERT INTO TEACHERS VALUES (7, 'PROTRACTOR', 'FANNY');
COMMIT;

===============================================================================

Automatic Transaction Control In PL/SQL

We can do configuration such that a COMMIT statement gets executed by default whenever an INSERT or
DELETE statement is run. This is done by making the AUTOCOMMIT environment variable to ON.
Syntax:
SET AUTOCOMMIT ON;
Again, this can be turned off by making the AUTOCOMMIT environment variable to OFF.
Syntax:
SET AUTOCOMMIT OFF;

===============================================================================
5. Implement different
types of referential and
integrity constraints on
Relation Database.
Types of Integrity Constraints

Domain integrity constraint contains a certain set of rules or conditions to restrict the kind of
attributes or values a column can hold in the database table. The data type of a domain can be string,
integer, character, DateTime, currency, etc.

Entity Integrity Constraint is used to ensure that the primary key cannot be null.

Referential Integrity Constraint ensures that there must always exist a valid relationship between
two relational database tables.

Key Constraints are the set of entities that are used to identify an entity within its entity set uniquely.

When no value is defined for a column, the DEFAULT Constraint provides a default value.

Check constraint check the value as its mentioned.


ON DELETE CASCADE Constraint

CREATE TABLE Student ( sno INT PRIMARY KEY, sname


VARCHAR(20), age INT );

INSERT Student (1,'Ankit',17), (2,'Ramya',18), (3,'Ram',16);

CREATE TABLE Course ( cno INT PRIMARY KEY, cname


VARCHAR(20));

INSERT Course  (101,'c'), (102,'c++'), (103,'DBMS');

CREATE TABLE Enroll ( sno INT, cno INT, jdate date,


PRIMARY KEY(sno,cno),
FOREIGN KEY(sno) REFERENCES Student(sno) ON DELETE CASCADE,
FOREIGN KEY(cno) REFERENCES Course (cno) ON DELETE CASCADE );

INSERT Enroll  (1, 101, '5-jun-2021'), (1, 102, '5-jun-2021'),


(2, 103, '6-jun-2021');

DELETE FROM Student WHERE sname=’Ramya’;

Check the difference  ON DELETE SET NULL


6. To apply the concept
of Aggregating Data
using Group functions.
SQL Aggregate Functions

o SQL aggregation function is used to perform the calculations on


multiple rows of a single column of a table. It returns a single value.
o It is also used to summarize the data.

Types of SQL Aggregation Function

SELECT AVG(Salary) FROM Employee;

SELECT E_NAME,MAX(SALARY) FROM Employee;

SELECT COUNT(*) FROM EMPLOYEE ;

SELECT COUNT(DEPARTMENT) FROM EMPLOYEE WHERE


SALARY>30000;
7. To retrieve the queries
using Group by, Having
and Order by clauses of
SQL.
The SQL GROUP BY Statement
The GROUP BY statement groups rows that have the same values into
summary rows, like "find the number of customers in each country".

The GROUP BY statement is often used with aggregate functions


(COUNT(), MAX(), MIN(), SUM(), AVG()) to group the result-set
by one or more columns.

 SELECT DEPARTMENT, SUM(SALARY) FROM EMPLOYEE


GROUP BY DEPARTMENT ORDER BY DEPARTMENT;

 SELECT DEPARTMENT, MAX(SALARY) FROM EMPLOYEE


GROUP BY DEPARTMENT ;

 SELECT E_NAME, Salary FROM EMPLOYEE GROUP BY


DEPARTMENT;

The SQL HAVING Clause


The HAVING clause was added to SQL because the WHERE keyword cannot be
used with aggregate functions.

 SELECT COUNT(CustomerID), Country FROM Customers


GROUP BY Country HAVING COUNT(CustomerID) > 5;

 SELECT COUNT(CustomerID), Country FROM Customers


GROUP BY Country HAVING COUNT(CustomerID) > 5
ORDER BY COUNT(CustomerID) DESC;
8. Design and
development of Banking
database and perform
various type of JOIN
operations.
Types of Joins in Oracle
 Inner Joins (also known as Simple Joins)
 Equi Joins
 Outer Joins
 Left Outer Joins (also called as Left Joins)
 Right Outer Joins (also called as Right Joins)
 Full Outer Joins (also called as Full Joins)
 Self Joins
 Cross Joins (also called as Cartesian Products)
 Anti Joins
 Semi Joins
SELECT b.branch_name, a.account_number
FROM branch b
JOIN account a ON b.branch_name = a.branch_name;

================================================================
SELECT b.branch_name, a.account_number
FROM branch b
INNER JOIN account a ON b.branch_name = a.branch_name;

================================================================

SELECT b.branch_name, a.account_number


FROM branch b
LEFT JOIN account a ON b.branch_name = a.branch_name;
================================================================

SELECT b.branch_name, a.account_number


FROM branch b
RIGHT JOIN account a ON b.branch_name = a.branch_name;
================================================================

SELECT * FROM branch NATURAL JOIN account ;

================================================================

SELECT b.branch_name, a.account_number


FROM branch b
FULL JOIN account a ON b.branch_name = a.branch_name;
================================================================

SELECT b.branch_name, a.account_number


FROM branch b
CROSS JOIN account a;
================================================================
9. Insert the Data into
table and use COMMIT,
ROLLBACK and
SAVEPOINT in PL/SQL
CREATE TABLE STUDENT (SNO INT, SNAME VARCHAR2(20), AGE INT);

Insert  (1, ‘rajesh’, 45) , ( 2, ‘anand’, 41), (3, ‘sathish’, 38), (4, ‘gopi’, 36)

Sqllab9.sql

DECLARE
rollno student.sno%type;
snm student.sname%type;
nage student.age%type;
BEGIN
rollno := &sno;
snm := '&sname';
nage := &age;

INSERT into student values (rollno, snm, nage);


dbms_output.put_line('commit and savepoint’);

COMMIT;

SAVEPOINT save1;

rollno := &sno;
snm := '&sname';
nage := &age;

INSERT into student values (rollno, snm, nage);


dbms_output.put_line('rollback success');

ROLLBACK TO save1;
END;

/
10. Write a trigger that
automatically deletes
students when they
graduate
Classes of Triggers in SQL Server
There are three types or classes of triggers in SQL Server, DML, DDL, and Logon triggers:

 DML (Data Manipulation Language) Triggers – Fire when an INSERT, UPDATE, or DELETE
event occurs on a table, view, etc.
 DDL (Data Definition Language) Triggers – Fire when a CREATE, ALTER, or DROP event
occurs on a database object.
 Logon Triggers – Fire when a user logs into a database i.e. logon event.

SQL Server supports three types of DML triggers:

 BEFORE Triggers – This type of trigger fires before the data has been committed into the
database.
 AFTER Triggers – This type of trigger fires after the event it is associated with completes and
can only be defined on permanent tables.
 INSTEAD OF Triggers – This type of trigger fires instead of the event it is associated with and
can be applied to tables or views.
CREATE TABLE ex10 (
id NUMBER PRIMARY KEY,
name VARCHAR2(10), status VARCHAR2(15));

INSERT INTO ex10 (id, name, status) VALUES (1, 'Alice', 'enrolled');
INSERT INTO ex10 (id, name, status) VALUES (2, 'Bob', 'graduated');
INSERT INTO ex10 (id, name, status) VALUES (3, 'Charlie', 'enrolled');

COMMIT;

-- Create the PL/SQL trigger


CREATE OR REPLACE TRIGGER trg
AFTER UPDATE OF status ON ex10
FOR EACH ROW
BEGIN
IF :NEW.status = 'graduated' THEN
DELETE FROM ex10 WHERE id = :NEW.id;
END IF;
END;
/

UPDATE ex10 SET status = 'graduated' WHERE id = 1;

SELECT * FROM ex10;

DROP TRIGGER trg


DROP TABLE ex10;
11. Develop programs
using features parameters
in a CURSOR for
UPDATE
CREATE TABLE employee1 ( employee_no NUMBER PRIMARY KEY, first_name
VARCHAR2(50), last_name VARCHAR2(50), schedule_code VARCHAR2(10) );

INSERT INTO employee1 VALUES (100, 'John', 'Doe', 'X');


INSERT INTO employee1 VALUES (200, 'Jane', 'Smith', 'Y');
INSERT INTO employee1 VALUES (300, 'Michael', 'Johnson', 'Z');
INSERT INTO employee1 VALUES (400, 'Emily', 'Brown', 'X');
INSERT INTO employee1 VALUES (500, 'David', 'Lee', 'Y');
INSERT INTO employee1 VALUES (600, 'Olivia', 'Davis', 'Z');

CREATE OR REPLACE PROCEDURE p_upd_schdcde IS


CURSOR c1(p_employee_no NUMBER) IS
SELECT employee_no, schedule_code FROM employee1 WHERE employee_no =
p_employee_no FOR UPDATE;
BEGIN
FOR rec IN c1(100) LOOP
UPDATE employee1 SET schedule_code = 'A' WHERE CURRENT OF c1;
END LOOP;

FOR rec IN c1(300) LOOP


UPDATE employee1 SET schedule_code = 'A' WHERE CURRENT OF c1;
END LOOP;

FOR rec IN c1(500) LOOP


UPDATE employee1 SET schedule_code = 'A' WHERE CURRENT OF c1;
END LOOP;

FOR rec IN c1(700) LOOP


UPDATE employee1 SET schedule_code = 'A' WHERE CURRENT OF c1;
END LOOP;

COMMIT;
END;
/

BEGIN
p_upd_schdcde;
END;
/
12. a) Create a cursor to
update the salary of
employees in EMP table.
12. b) Write a PL/SQL
program to raise an
Exception when the bonus
exceeds salary.
13. Design and
implementation real time
project with database
connection.

You might also like