0% found this document useful (0 votes)
7 views37 pages

dbms5-6LAB

The document outlines Lab Session 5 for Database Management Systems, focusing on the concept and techniques of database normalization. It covers the identification of issues in unnormalized tables, the application of normalization techniques to achieve various normal forms (1NF, 2NF, 3NF, and BCNF), and the use of SQL queries for implementation. Additionally, it includes tasks for analyzing and normalizing given tables, emphasizing the importance of reducing redundancy and improving data integrity.

Uploaded by

labibbukhari2003
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views37 pages

dbms5-6LAB

The document outlines Lab Session 5 for Database Management Systems, focusing on the concept and techniques of database normalization. It covers the identification of issues in unnormalized tables, the application of normalization techniques to achieve various normal forms (1NF, 2NF, 3NF, and BCNF), and the use of SQL queries for implementation. Additionally, it includes tasks for analyzing and normalizing given tables, emphasizing the importance of reducing redundancy and improving data integrity.

Uploaded by

labibbukhari2003
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 37

Database Management System-L Lab Session 05

Iqra University Department of Software Engineering

Lab Session 5
Objective:
● Understand the concept and significance of database normalization.
● Analyze unnormalized tables to identify issues such as redundancy and anomalies.
● Apply normalization techniques to transform tables into 1NF and 2NF.
● To learn and apply normalization techniques to achieve Third Normal Form (3NF) by
eliminating transitive dependencies.
● Apply Boyce-Codd Normal Form (BCNF) by ensuring every determinant is a candidate
key.
● Use SQL queries in MS SQL Server to implement normalization and manage normalized
tables.

Required Equipment / tools:


1. Computer with a Database Management System (DBMS) (e.g., MySQL, PostgreSQL,
Microsoft SQL Server).
2. SQL editor (e.g., MySQL Workbench, pgAdmin, or SSMS).
3. Access to sample unnormalized datasets.

Introduction:
Database normalization is a systematic approach to organizing a relational database to reduce
redundancy and improve data integrity. It involves dividing large tables into smaller,
interconnected ones while adhering to specific design principles.

Functional Dependencies

Functional Dependency (FD) is a fundamental concept in normalization. It describes the


relationship between attributes in a table.

● Definition: Attribute B is functionally dependent on attribute A if, for every value of A,


there is exactly one corresponding value of B
. This is written as:

● Key Attribute: The attribute or a combination of attributes on the left-hand side of the
functional dependency is called the determinant.
Database Management System-L Lab Session 05
Iqra University Department of Software Engineering
Example:
Consider a table of employees:

Here:

1. Employee_ID Employee_Name : Each Employee_ID determines a unique


Employee_Name.
2. Department Department_Head : Each Department determines a unique
Department_Head.

Role in Normalization:

Functional dependencies help identify the relationships between attributes and serve as the basis
for decomposing tables during normalization. By eliminating unwanted dependencies,
normalization improves the structure and integrity of the database.

Why Normalize?

Normalization addresses problems such as:

1. Data Redundancy: Duplication of data across rows.


2. Update Anomalies: Inconsistencies during data updates.
3. Deletion Anomalies: Loss of useful data when certain information is deleted.
4. Insertion Anomalies: Difficulty in adding new records due to design constraints.

Normalization Forms:
Normalization progresses through stages, each addressing specific issues:

1. First Normal Form (1NF): Ensures that each field contains atomic (indivisible) values
and eliminates repeating groups.
2. Second Normal Form (2NF): Eliminates partial dependencies, where non-primary
attributes depend on part of a composite primary key.
Database Management System-L Lab Session 05
Iqra University Department of Software Engineering

3. 3NF and BCNF

Normalization to 3NF and BCNF is crucial for:

1. Eliminating redundant data.


2. Minimizing anomalies during insert, update, and delete operations.
3. Improving database design and query efficiency.

Third Normal Form (3NF)

A table is in 3NF if it is in 2NF and has no transitive dependencies.

● Transitive dependency: A non-prime attribute depends on another non-prime attribute.

Boyce-Codd Normal Form (BCNF)

A table is in BCNF if it is in 3NF and every determinant is a candidate key.

● Determinant: An attribute or set of attributes that uniquely determines another attribute.

Procedure:
Example Problem Scenario
Consider the following Unnormalized Table (UNF):

Examples with Explanation


Step 1: Analyze the UNF

The given table is unnormalized because:

1. Repeating groups: The same Order_ID appears multiple times with different products
(Product_ID).
2. Redundant data: Supplier details (Supplier_Name, Supplier_Contact) are repeated
for every product.
3. Anomalies:
○ Update Anomaly: Changing the supplier's contact information requires updates
in multiple rows.
Database Management System-L Lab Session 05
Iqra University Department of Software Engineering
○ Deletion Anomaly: Deleting all products from a supplier results in losing
supplier details.
○ Insertion Anomaly: Adding a new supplier without an order is impossible.

Query to create above unnormalized table:

CREATE TABLE UnnormalizedTable (

Order_ID INT,

Customer_Name VARCHAR(50),

Product_ID VARCHAR(10),

Product_Name VARCHAR(50),

Quantity INT,

Supplier_Name VARCHAR(50),

Supplier_Contact VARCHAR(15)

);

INSERT INTO UnnormalizedTable (Order_ID, Customer_Name, Product_ID, Product_Name,


Quantity, Supplier_Name, Supplier_Contact)

VALUES

(001, 'John Doe', 'P101', 'Laptop', 2, 'TechSupply', '1234567890'),

(001, 'John Doe', 'P102', 'Mouse', 1, 'TechSupply', '1234567890'),

(002, 'Jane Smith', 'P101', 'Laptop', 1, 'TechSupply', '1234567890');

Step 2: Apply First Normal Form (1NF)

To convert the table to 1NF, we must:

1. Ensure all fields contain atomic values.


2. Remove repeating groups.

1NF Table:
Database Management System-L Lab Session 05
Iqra University Department of Software Engineering

Explanation of Changes:

● Each column now contains atomic values.


● Repeating groups were eliminated, and each product is listed in a separate row.

Query for First Normal Form

CREATE TABLE FirstNormalForm (

Order_ID INT,

Customer_Name VARCHAR(50),

Product_ID VARCHAR(10),

Product_Name VARCHAR(50),

Quantity INT,

Supplier_Name VARCHAR(50),

Supplier_Contact VARCHAR(15)

);

INSERT INTO FirstNormalForm (Order_ID, Customer_Name, Product_ID, Product_Name,


Quantity, Supplier_Name, Supplier_Contact)

VALUES

(001, 'John Doe', 'P101', 'Laptop', 2, 'TechSupply', '1234567890'),

(001, 'John Doe', 'P102', 'Mouse', 1, 'TechSupply', '1234567890'),

(002, 'Jane Smith', 'P101', 'Laptop', 1, 'TechSupply', '1234567890');

Step 3: Apply Second Normal Form (2NF)


Database Management System-L Lab Session 05
Iqra University Department of Software Engineering
To convert the table to 2NF, we must:

1. Identify partial dependencies.


○ Attributes like Product_Name, Supplier_Name, and Supplier_Contact
depend only on Product_ID and not the entire composite key (Order_ID,
Product_ID).
2. Remove partial dependencies by creating separate tables.

2NF Tables:

Orders Table:

Products Table:

Explanation of Changes:

● Partial dependencies were resolved by separating product-related attributes into a


Products table.
● The Orders table now only contains attributes directly related to orders.

Orders Table Query

CREATE TABLE Orders (

Order_ID INT PRIMARY KEY,

Customer_Name VARCHAR(50)

);

INSERT INTO Orders (Order_ID, Customer_Name) VALUES (001, 'John Doe'), (002, 'Jane
Smith');
Database Management System-L Lab Session 05
Iqra University Department of Software Engineering
OrderDetails Table

CREATE TABLE OrderDetails (

Order_ID INT,

Product_ID VARCHAR(10),

Quantity INT,

PRIMARY KEY (Order_ID, Product_ID),

FOREIGN KEY (Order_ID) REFERENCES Orders(Order_ID)

);

INSERT INTO OrderDetails (Order_ID, Product_ID, Quantity)

VALUES (001, 'P101', 2), (001, 'P102', 1), (002, 'P101', 1);

Products Table

CREATE TABLE Products (

Product_ID VARCHAR(10) PRIMARY KEY,

Product_Name VARCHAR(50),

Supplier_Name VARCHAR(50)

);

INSERT INTO Products (Product_ID, Product_Name, Supplier_Name)

VALUES ('P101', 'Laptop', 'TechSupply'), ('P102', 'Mouse', 'TechSupply');

Suppliers Table

CREATE TABLE Suppliers (

Supplier_Name VARCHAR(50) PRIMARY KEY,

Supplier_Contact VARCHAR(15)

);

INSERT INTO Suppliers (Supplier_Name, Supplier_Contact) VALUES ('TechSupply', '1234567890');


Database Management System-L Lab Session 05
Iqra University Department of Software Engineering
Analyze and Normalize the StudentCourse Table to 3NF

Original StudentCourse Table

Functi
onal Dependencies:

● StudentID StudentName .
● CourseID CourseName, InstructorName .

Issues:

● Transitive dependency exists: CourseID CourseName, InstructorName .

Queries for Normalization to 3NF

1. Create Original Table:

CREATE TABLE StudentCourse (


StudentID INT PRIMARY KEY,
StudentName NVARCHAR(50),
CourseID INT,
CourseName NVARCHAR(50),
InstructorName NVARCHAR(50)
);

INSERT INTO StudentCourse (StudentID, StudentName, CourseID, CourseName,


InstructorName)
VALUES
(1, 'Alice', 101, 'Database Systems', 'Dr. Smith'),
(2, 'Bob', 101, 'Database Systems', 'Dr. Smith'),
(3, 'Charlie', 102, 'Operating Systems', 'Dr. Taylor');

2. Decompose into Normalized Tables:


○ Create Student Table:

CREATE TABLE Student (


StudentID INT PRIMARY KEY,
StudentName NVARCHAR(50),
CourseID INT
);
Database Management System-L Lab Session 05
Iqra University Department of Software Engineering
INSERT INTO Student (StudentID, StudentName, CourseID)
VALUES
(1, 'Alice', 101),
(2, 'Bob', 101),
(3, 'Charlie', 102);

○ Create Course Table:

CREATE TABLE Course (


CourseID INT PRIMARY KEY,
CourseName NVARCHAR(50),
InstructorName NVARCHAR(50)
);

INSERT INTO Course (CourseID, CourseName, InstructorName)


VALUES
(101, 'Database Systems', 'Dr. Smith'),
(102, 'Operating Systems', 'Dr. Taylor');

3. Join Queries to Retrieve Original Data:

SELECT s.StudentID, s.StudentName, c.CourseID, c.CourseName,


c.InstructorName
FROM Student s
JOIN Course c ON s.CourseID = c.CourseID;

2.Analyze and Normalize the EmployeeDepartment Table to BCNF

Original EmployeeDepartment Table

Functional Dependencies:

● EmployeeID DepartmentID .
● DepartmentID DepartmentName, ManagerID .

Issues:
Database Management System-L Lab Session 05
Iqra University Department of Software Engineering
● DepartmentID ManagerID violates BCNF because DepartmentID is not a
candidate key.

Queries for Normalization to BCNF

1. Create Original Table:


CREATE TABLE EmployeeDepartment (
EmployeeID INT PRIMARY KEY,
DepartmentID INT,
DepartmentName NVARCHAR(50),
ManagerID NVARCHAR(50)
);

INSERT INTO EmployeeDepartment (EmployeeID, DepartmentID,


DepartmentName, ManagerID)
VALUES
(1, 101, 'Database Systems', 'Dr. Smith'),
(2, 101, 'Database Systems', 'Dr. Smith'),
(3, 102, 'Operating Systems', 'Dr. Taylor');

2. Decompose into Normalized Tables:


○ Create Employee Table:

CREATE TABLE Employee (


EmployeeID INT PRIMARY KEY,
DepartmentID INT
);

INSERT INTO Employee (EmployeeID, DepartmentID)


VALUES
(1, 101),
(2, 101),
(3, 102);

○ Create Department Table:

CREATE TABLE Department (


DepartmentID INT PRIMARY KEY,
DepartmentName NVARCHAR(50),
ManagerID NVARCHAR(50)
);

INSERT INTO Department (DepartmentID, DepartmentName, ManagerID)


VALUES
(101, 'Database Systems', 'Dr. Smith'),
(102, 'Operating Systems', 'Dr. Taylor');
Database Management System-L Lab Session 05
Iqra University Department of Software Engineering
3. Join Queries to Retrieve Original Data:
SELECT e.EmployeeID, e.DepartmentID, d.DepartmentName, d.ManagerID
FROM Employee e
JOIN Department d ON e.DepartmentID = d.DepartmentID;

CLASS TASKS:

Consider the following Unnormalized table:

Task 1: Identify Redundancy

Analyze the given unnormalized table and identify the redundancies present in it. Discuss how
these redundancies can lead to data anomalies.
Database Management System-L Lab Session 05
Iqra University Department of Software Engineering

Redundancies in the Table

Issue Type Description Example

"1234567890, 0987654321" or
Multiple contact numbers and
Repeating Groups "John Smith (CS101), Maria
instructors listed in the same cell.
Khan (CS102)"

Instructor and course information is John Smith appears multiple


Data Duplication repeated for each student who shares times for CS101 across
them. students.

CourseEnrollments and
Multi-valued
InstructorDetails hold multiple values CS101, CS102
Attributes
in a single column.

Courses and instructors are bundled InstructorDetails couples


Denormalized
together instead of being split into course and instructor in the
Structure
separate related tables. same field.

How This Leads


to Data Anomalies Cause Result
Anomaly Type

Instructor's name changes, but is Inconsistent updates if only


Update Anomaly
repeated in many rows. some rows are modified.

You want to add a new course Cannot store course unless it's
Insertion Anomaly
before any student enrolls. linked to a student.

If Ali Ahmed is deleted, and he’s the Course and instructor data for
Deletion Anomaly
only student in CS102. CS102 may also be lost.

Maria Khan (CS102) vs Maria


Instructors or courses stored
Data Inconsistency Khan(CS102) can cause
differently in different rows.
confusion.
Database Management System-L Lab Session 05
Iqra University Department of Software Engineering

Task 2: Normalize to 1NF

● Convert the unnormalized table to First Normal Form (1NF).


● Ensure that all columns contain atomic (indivisible) values.
1NF (First Normal Form):

 Remove repeating groups. Split multi-valued fields into separate rows.


Database Management System-L Lab Session 05
Iqra University Department of Software Engineering
 StudentID  CourseCode

 1  CS101

 1  CS102

 2  CS101

 2  CS103

 3  CS102

 3  CS103

CREATE TABLE StudentCourse1NF (

StudentID INT,

StudentName VARCHAR(50),

ContactNumber VARCHAR(15),

CourseCode VARCHAR(10),

InstructorName VARCHAR(50)

);

-- Inserting atomic values

INSERT INTO StudentCourse1NF VALUES

(1, 'Ali Ahmed', '1234567890', 'CS101', 'John Smith'),

(1, 'Ali Ahmed', '1234567890', 'CS102', 'Maria Khan'),

(1, 'Ali Ahmed', '0987654321', 'CS101', 'John Smith'),

(1, 'Ali Ahmed', '0987654321', 'CS102', 'Maria Khan'),

(2, 'Sara Malik', '9876543210', 'CS101', 'John Smith'),

(2, 'Sara Malik', '9876543210', 'CS103', 'David Brown'),

(2, 'Sara Malik', '1122334455', 'CS101', 'John Smith'),

(2, 'Sara Malik', '1122334455', 'CS103', 'David Brown'),

(3, 'Ahmed Raza', '5556667778', 'CS102', 'Maria Khan'),

(3, 'Ahmed Raza', '5556667778', 'CS103', 'David Brown'),


Database Management System-L Lab Session 05
Iqra University Department of Software Engineering
Task 3: Normalize to 2NF

● Take the 1NF table created in the previous step and normalize it to Second Normal Form
(2NF).
● Ensure there are no partial dependencies by creating new tables if necessary.
2NF (Second Normal Form):

 Remove partial dependencies. Create separate tables for Courses,


Database Management System-L Lab Session 05
Students, Instructors.
Iqra University Department of Software Engineering
Students Table

 StudentI  StudentNa
D me

 1  Ali Ahmed

 2  Sara Malik

 3  Ahmed Raza

CREATE TABLE Students (

StudentID INT PRIMARY KEY,

StudentName VARCHAR(50)

);

INSERT INTO Students VALUES

(1, 'Ali Ahmed'),

(2, 'Sara Malik'),

(3, 'Ahmed Raza');


Contacts Table:

StudentI ContactNumb
D er

1 1234567890

1 0987654321

2 9876543210

2 1122334455

3 5556667778

3 6667778889

CREATE TABLE Contacts (

ContactID INT IDENTITY(1,1) PRIMARY KEY,

StudentID INT FOREIGN KEY REFERENCES Students(StudentID),

ContactNumber VARCHAR(15)

);
Database Management System-L Lab Session 05
Iqra University Department of Software Engineering
Task 4:

Write a query to create and populate the original StudentCourse table in SQL Server.

CREATE TABLE StudentCourseOriginal (

StudentID INT,

StudentName VARCHAR(50),

ContactNumbers VARCHAR(100),

CourseEnrollments VARCHAR(100),

InstructorDetails VARCHAR(200)

);

INSERT INTO StudentCourseOriginal VALUES

(1, 'Ali Ahmed', '1234567890, 0987654321', 'CS101, CS102', 'John Smith (CS101), Maria Khan
(CS102)'),

(2, 'Sara Malik', '9876543210, 1122334455', 'CS101, CS103', 'John Smith (CS101), David Brown
(CS103)'),

(3, 'Ahmed Raza', '5556667778, 6667778889', 'CS102, CS103', 'Maria Khan (CS102), David Brown
(CS103)');

Task 5:

Write queries to create and populate the normalized Student and Course tables from the
StudentCourse table in SQL Server.
Database Management System-L Lab Session 05
Iqra University Department of Software Engineering

-- Students Table (already created in Task 3)

INSERT INTO Students (StudentID, StudentName)

SELECT DISTINCT StudentID, StudentName

FROM StudentCourseOriginal;

-- Courses (Manually map or extract unique course codes)

-- Already created and inserted manually above

Task 6:

Write queries to create and populate the normalized Employee and Department tables from the
EmployeeDepartment table in SQL Server.
Database Management System-L Lab Session 05
Iqra University Department of Software Engineering

CREATE TABLE EmployeeDepartment1NF (

EmployeeID INT,

EmployeeName VARCHAR(50),

DepartmentName VARCHAR(50)

);

INSERT INTO EmployeeDepartment1NF VALUES

(1, 'Ayesha', 'HR'),

(1, 'Ayesha', 'Finance'),

(2, 'Bilal', 'Finance'),

(2, 'Bilal', 'IT'),

(3, 'Farah', 'HR'),

(3, 'Farah', 'IT');

CREATE TABLE EmployeeDepartment1NF (

EmployeeID INT,

EmployeeName VARCHAR(50),

DepartmentName VARCHAR(50)

);

INSERT INTO EmployeeDepartment1NF VALUES

(1, 'Ayesha', 'HR'),

(1, 'Ayesha', 'Finance'),

(2, 'Bilal', 'Finance'),

(2, 'Bilal', 'IT'),

(3, 'Farah', 'HR'),

(3, 'Farah', 'IT');


Database Management System-L Lab Session 05
Iqra University Department of Software Engineering

HOME TASKS:

Task 1: Apply Normalization to a New Dataset

● Create an unnormalized table similar to the one provided (e.g., "Employee Projects").
● Normalize it up to Second Normal Form (2NF) and submit both 1NF and 2NF tables.
Let’s say we have the following unnormalized table that tracks employees and the projects they’re working on.

Database Management
EmpID EmpName System-LContactNumbers
Department Projects Lab Session 05
Iqra University Department of Software Engineering
1 Ayesha Khan IT 03211234567,03001122334 P101-Website Redesign, P102-Testing

2 Bilal Shah HR 03115556677 P103-Recruitment Campaign

3 Zara Ahmed IT 03007778899,03114445566 P101-Website Redesign, P104-SEO

FIRST NORMAL FORM (1NF): Objective: Remove multi-valued attributes, so


every field contains atomic values
-- Create Employee Table

CREATE TABLE Employees (

EmpID INT PRIMARY KEY,

EmpName VARCHAR(100),

Department VARCHAR(50)

);

-- Create EmployeeContacts Table

CREATE TABLE EmployeeContacts (

EmpID INT,

ContactNumber VARCHAR(15),

FOREIGN KEY (EmpID) REFERENCES Employees(EmpID)

);

-- Create Projects Table

CREATE TABLE Projects (

ProjectCode VARCHAR(10) PRIMARY KEY,

ProjectName VARCHAR(100)

);

-- Create EmployeeProjects Table

CREATE TABLE EmployeeProjects (

EmpID INT,

ProjectCode VARCHAR(10),

FOREIGN KEY (EmpID) REFERENCES Employees(EmpID),


Database Management System-L Lab Session 05
Iqra University Department of Software Engineering
Task 2: Real-World Example Identification

● Identify a real-world dataset or scenario from your surroundings (e.g., library records,
grocery store inventory).
● Design an unnormalized table for it and outline the process to normalize it to 2NF.
DataSet from Pakistani PharmacyStore:

Database Management
MedicineName ManufacturerSystem-L
BatchNo ExpiryDate StoreLocation Quantity SupplierName Lab Session 05
SupplierContact
Iqra University Department of Software Engineering
Panadol GSK B123 2025-12-30 Lahore 100 Ali Medical Supplies 03001234567

Augmentin Abbott A567 2025-06-15 Karachi 50 Ali Medical Supplies 03001234567

Panadol GSK B123 2025-12-30 Islamabad 80 HealthTrade Ltd 03445678901

-- 1. Medicines Table

CREATE TABLE Medicines (

MedicineID INT PRIMARY KEY,

MedicineName VARCHAR(50),

Manufacturer VARCHAR(50)

);

-- 2. Suppliers Table

CREATE TABLE Suppliers (

SupplierID INT PRIMARY KEY,

SupplierName VARCHAR(100),

SupplierContact VARCHAR(20)

);

-- 3. Stock Table

CREATE TABLE Stock (

StockID INT PRIMARY KEY,

MedicineID INT,

BatchNo VARCHAR(20),

ExpiryDate DATE,

StoreLocation VARCHAR(50),

Quantity INT,

SupplierID INT,

FOREIGN KEY (MedicineID) REFERENCES Medicines(MedicineID),

FOREIGN KEY (SupplierID) REFERENCES Suppliers(SupplierID)

);
Database Management System-L Lab Session 05
Iqra University Department of Software Engineering
Task 3: Discuss Limitations of 2NF

● Research and write a brief explanation about the limitations of stopping normalization at
2NF.
● Suggest scenarios where further normalization (e.g., 3NF) is beneficial.

Limitations of 2NF:

 Doesn’t eliminate transitive dependencies.

o Example: If in Students table, CityName depends on CityID, which in turn depends on


StudentID, you have a transitive dependency.

 Data anomalies still possible:

o Updating a city name requires multiple rows to be updated.

o Inconsistent data can still occur.

 Poor data integrity, especially in large systems.

Why Go Further (to 3NF or BCNF)?

 3NF removes transitive dependencies. Great for improving data integrity and
consistency.

 BCNF handles even more complex dependency situations (advanced normalization,


often in theoretical DBMS).

Task 4:

Write a query to insert additional data into the normalized Student and Course tables and test
the join query to retrieve combined data.
Database Management System-L Lab Session 05
Iqra University Department of Software Engineering

-- Insert Students

INSERT INTO Students (StudentID, StudentName)

VALUES (3, 'Hassan Malik');

-- Insert Student-Course mapping

INSERT INTO StudentCourses (StudentID, CourseID)

VALUES (3, 101);

-- Join to fetch full info

SELECT s.StudentName, c.CourseName

FROM Students s

JOIN StudentCourses sc ON s.StudentID = sc.StudentID

JOIN Courses c ON sc.CourseID = c.CourseID;

Task 5:

Write a query to insert additional data into the normalized Employee and Department tables and
test the join query to retrieve combined data.

-- Insert Employee

INSERT INTO Employees (EmpID, EmpName, DeptID)

VALUES (3, 'Faisal Qureshi', 20);

-- Join to fetch department info

SELECT e.EmpName, d.DeptName

FROM Employees e

JOIN Departments d ON e.DeptID = d.DeptID;

Task 6:
Database Management System-L Lab Session 05
Iqra University Department of Software Engineering
Modify the data in the Student table (e.g., update a student's course) and write a query to reflect
the change in the combined result.

-- Update Ali's course (assuming his ID is 1)

UPDATE StudentCourses

SET CourseID = 102

WHERE StudentID = 1 AND CourseID = 101;

-- Confirm the update

SELECT s.StudentName, c.CourseName

FROM Students s

JOIN StudentCourses sc ON s.StudentID = sc.StudentID

JOIN Courses c ON sc.CourseID = c.CourseID;

Discussion and analysis of results:


Database Management System-L Lab Session 05
Iqra University Department of Software Engineering
Unnormalized data had repeating and multi-valued attributes, risking data
duplication and inconsistencies.
2NF effectively removed partial dependencies, organizing data into logical,
interrelated tables that maintain data integrity and reduce storage inefficiency

Conclusion:

By normalizing the pharmacy inventory data to 2NF, we eliminated


redundancy and ensured data consistency across Medicines, Suppliers, and
Stock records.
This structure improves scalability, makes updates easier, and protects
against anomalies during insertion, deletion, or updates.
Database Management System-L Lab Session 06
Iqra University Department of Software Engineering

Lab Session 06

Objective:

The Purpose of this Lab is to Introduction to Data Manipulation Language (DML) or Basic
CRUD which includes Insert, Update & Delete Statements.

Theory:

Data Manipulation Language:

The DML SQL statements are used to manipulate database and table data. The statements shown
in the slide are followed by options to specify data operations (such as table name).

INSERT Statement:

• Syntax

INSERT INTO table_name (column1, column2, column3, ...)

VALUES (value1, value2, value3, ...);

• Example of inserting a multiple row:

Let's say you have a table called employees with the columns id, name, and age. You want to
insert multiple rows into this table. The SQL query would look like this.

INSERT INTO employees (id, name, age)

VALUES (1, 'John Doe', 28),

(2, 'Jane Smith', 34),

(3, 'Alice Johnson', 29),

(4, 'Bob Brown', 41);


Database Management System-L Lab Session 06
Iqra University Department of Software Engineering
UPDATE Statement:

Syntax:

UPDATE table_name

SET column1 = value1, column2 = value2, column3 = value3, ...

WHERE condition;

•Example

Let's say we have a table called employees with columns id, name, and age. You want to update
the age of the employee with id = 2.

UPDATE employees

SET age = 35

WHERE id = 2;

•Example

Now, if you want to update both the name and age of the employee with id = 3,

UPDATE employees

SET name = 'Alice Williams', age = 30

WHERE id = 3;

DELETE Statement:

Syntax:

DELETE FROM table_name

WHERE condition;

•Example

We have a table called employees with columns id, name, and age. If you want to delete the
record of the employee with id = 3, you would use the following query:

DELETE FROM employees WHERE id = 3;


Database Management System-L Lab Session 06
Iqra University Department of Software Engineering
•Example : Delete multiple records based on a condition

If you want to delete all employees who are under the age of 25, you would use this query:

DELETE FROM employees

WHERE age < 25;

Example : Delete all records in a table

DELETE FROM employees;

CLASS TASKS:
Task 1:

Insert the following data given below in a table form

Movie (id, title, year, director)


Database Management System-L Lab Session 06
Iqra University Department of Software Engineering

CREATE TABLE Movie (

id INT PRIMARY KEY,

title VARCHAR(100),

year INT,

director VARCHAR(100)

);
INSERT INTO Movie (id, title, year, director)

VALUES

(1, 'Inception', 2010, 'Christopher Nolan'),

(2, 'The Godfather', 1972, 'Francis Ford Coppola'),

(3, 'Parasite', 2019, 'Bong Joon-ho'),

(4, 'The Dark Knight', 2008, 'Christopher Nolan'),

(5, 'Titanic', 1997, 'James Cameron');

Task 2:

Update the following data given below in a table form.

Movie (id, title, year, director)


Database Management System-L Lab Session 06
Iqra University Department of Software Engineering

UPDATE Movie

SET director = 'Nolan'

WHERE title = 'The Dark Knight';

Task 3

Delete the following data given below into a table form

Movie (id, title, year, director)

DELETE FROM Movie

WHERE title = 'Parasite';

Home Tasks:
Task 1:

1. What is the syntax for the INSERT statement in SQL?


2. How do you insert multiple rows of data into a table in one statement?
Database Management System-L Lab Session 06
Iqra University Department of Software Engineering
3. What happens if you try to insert a NULL value into a non-nullable column?
4. Can you insert data into a table with some columns missing? How?

-- ✅ Syntax of INSERT:
INSERT INTO table_name (column1, column2, ...)
VALUES (value1, value2, ...);

-- ✅ Inserting Multiple Rows in One Statement:


INSERT INTO employees (id, name, age)
VALUES (1, 'Ali', 30),
(2, 'Sara', 28),
(3, 'Bilal', 26);

-- ✅ What happens if you insert NULL in a non-nullable column?


-- ❌ It will throw an error.
-- Example (if 'name' is NOT NULL):
INSERT INTO students (id, name) VALUES (1, NULL); -- ❌ Error

-- ✅ Can you insert data with some columns missing?


-- Yes, only if missing columns are nullable or have default values.
INSERT INTO employees (id, name)
VALUES (4, 'Ahmed'); -- Works if 'age' has default or allows NULL

Task 2:

1. What is the syntax for the UPDATE statement in SQL?


2. How do you update a specific row using a WHERE clause in SQL?
3. What happens if you forget to include a WHERE clause in an UPDATE statement?
4. Can you update multiple columns at once using a single UPDATE statement? How?
5. How do you avoid updating unintended rows when using the UPDATE command?
Database Management System-L Lab Session 06
Iqra University Department of Software Engineering
-- ✅ Syntax of UPDATE:
UPDATE table_name
SET column1 = value1, column2 = value2, ...
WHERE condition;

-- ✅ Updating a Specific Row:


UPDATE employees
SET age = 35
WHERE id = 2;

-- ❗ What if you forget WHERE clause?


-- ⚠️All rows will be updated!
UPDATE employees
SET age = 50; -- ❌ Everyone's age becomes 50

-- ✅ Updating Multiple Columns:


UPDATE employees
SET name = 'Ayesha', age = 29
WHERE id = 5;

-- ✅ How to avoid unintended updates:


-- 1. Always use WHERE
-- 2. First run a SELECT to check:
SELECT * FROM employees WHERE id = 5;
-- 3. Then run:
UPDATE employees SET age = 29 WHERE id = 5;

Task 3:

1. What is the syntax for the DELETE statement in SQL?


2. How do you delete a specific row using a WHERE clause in SQL?
3. What is the difference between DELETE and TRUNCATE commands in SQL?
4. How do you delete all rows from a table while keeping the structure intact?
5. What happens if you forget to include a WHERE clause in a DELETE statement?
6. Can you delete data from multiple tables in a single statement?
Database Management System-L Lab Session 06
Iqra University Department of Software Engineering
1. -- ✅ Syntax of DELETE:
2. DELETE FROM table_name
3. WHERE condition;
4.
5. -- ✅ Deleting a Specific Row:
6. DELETE FROM employees
7. WHERE id = 3;
8.
9. -- ✅ DELETE vs TRUNCATE:
10. -- DELETE: Can delete selected rows with WHERE, logs every row
11. -- TRUNCATE: Deletes all rows quickly, no WHERE, may not be rolled back
12.
13. -- ✅ Delete All Rows But Keep Table Structure:
14. DELETE FROM employees; -- slower, logs each row
15. -- OR
16. TRUNCATE TABLE employees; -- faster, resets table
17.
18. -- ❌ What happens if you forget WHERE?
19. -- ⚠️All rows will be deleted!
20. DELETE FROM employees; -- All gone
21.
22. -- ✅ Deleting from Multiple Tables:
23. -- 1. Use JOIN-based DELETE (if DBMS supports it):
24. DELETE e FROM employees e
25. JOIN departments d ON e.dept_id = d.id
26. WHERE d.name = 'Finance';
27.
28. -- 2. Or set up cascading delete with foreign key:
29. -- ON DELETE CASCADE in table schema (used in parent-child table design)

Discussion and analysis of results:

Analysis:
Carefully structuring INSERT queries ensures smooth data entry, while UPDATE and
DELETE commands must always be paired with specific WHERE clauses to avoid
unintended bulk operations. Together, these DML operations provide powerful control
over database content—but with great power comes the need for careful usage and testing.
Database Management System-L Lab Session 06
Iqra University Department of Software Engineering
Conclusion:

Conclusion:
The INSERT, UPDATE, and DELETE statements form the core of SQL’s Data
Manipulation Language (DML), allowing us to add, modify, and remove records from a
database efficiently. Understanding these commands is crucial for managing data
accurately in real-world applications.
Database Management System-L Lab
Session 06
Iqra University Department of Software
Engineering

You might also like