A
Practical File
On
RDBMS LAB
Bachelor of Technology
In
Computer Science & Engineering
Session 2023-2027 program under the Maharishi University of Information
Technology, Noida
Submitted to : Ms Cheshta
Submitted by: ……………………..
Roll no.: ……………………………
Course/Semester/Section:………….
School of Engineering & Technology
Maharishi University of Information Technology
Noida-201304
www.muitnoida.edu.in
2024
TABLE OF CONTENTS
S.No List of Programs Date of Teacher
Experiment Sign
1 Creating Entity Relationship Diagram using Case Tools (leave blank for
now)
2 Writing SQL Statements using Oracle/MySQL
3 Basic SQL SELECT Statements
4 Restricting and Sorting Data
5 Displaying Data from Multiple Tables
6 Aggregating Data Using Group Functions
7 Manipulating Data
8 Creating and Managing Tables
9 Normalization
10 Creating Cursor
11 Creating Procedures and Functions
12 Creating Packages and Triggers
I. Creating Entity Relationship Diagram using Case Tools
Objective
The ER diagram is a conceptual tool used in database design to visually map out entities,
relationships, and attributes within a database. It helps in understanding the structure and
relationships within the system, laying the foundation for creating an efficient, normalized
database schema.
ER Diagram is known as Entity-Relationship Diagram, it is used to analyze the structure of
the Database. It shows relationships between entities and their attributes. An ER Model
provides a means of communication.
Example Scenario
Let’s consider a simple Library Management System. In this system, we need to track Books,
Authors, Members, and Loans.
Key Entities:
1. Book: Represents a book in the library.
2. Author: Represents an author who has written one or more books.
3. Member: Represents a person who borrows books from the library.
4. Loan: Represents the borrowing event when a member borrows a book.
Relationships:
Writes: A relationship between Author and Book (an author can write multiple books,
and a book can have multiple authors).
Borrows: A relationship between Member and Loan (a member can borrow multiple
books).
Contains: A relationship between Loan and Book (a loan can contain one or more
books).
Entities:
Author: Stores information about authors with a unique author_id.
Book: Stores information about books with a unique book_id.
Member: Represents library members, uniquely identified by member_id.
Loan: Represents each loan transaction with a unique loan_id.
Relationships:
Writes: Many-to-Many relationship between Author and Book, represented by the
Book_Author table.
Borrows: One-to-Many relationship between Member and Loan (a member can have
multiple loans, but each loan is tied to a single member).
Contains: Many-to-Many relationship between Loan and Book, allowing each loan to
include multiple books (and each book to be part of multiple loans).
Cardinalities:
An Author can write multiple Books (1), and each Book can have multiple Authors
(M:1).
A Member can have multiple Loans (1), but each Loan is associated with a single
Member (M:1).
Each Loan can contain multiple Books (1), and each Book can be part of multiple Loans
(M:1).
1. Creating Tables
Creating the Books Table
CREATE TABLE Books (
BookID INT PRIMARY KEY,
Title VARCHAR(100) NOT NULL,
AuthorNo INT,
Price DECIMAL(6,2) CHECK (Price > 0),
Category VARCHAR(50),
PublisherID INT
);
Creating the Members Table
CREATE TABLE Members (
MemberID INT PRIMARY KEY,
FirstName VARCHAR(50),
LastName VARCHAR(50),
JoinDate DATE
);
Creating the Loans Table
CREATE TABLE Loans (
LoanID INT PRIMARY KEY,
MemberID INT,
BookID INT,
LoanDate DATE,
ReturnDate DATE,
FOREIGN KEY (MemberID) REFERENCES Members(MemberID),
FOREIGN KEY (BookID) REFERENCES Books(BookID)
);
Creating the Publishers Table
CREATE TABLE Publishers (
PublisherID INT PRIMARY KEY,
Name VARCHAR(100)
);
2. Inserting Data into Tables
Inserting Data into the Publishers Table
INSERT INTO Publishers (PublisherID, Name)
VALUES
(1, 'O\'Reilly Media'),
(2, 'Packt Publishing'),
(3, 'McGraw-Hill');
Publishers Table
PublisherID Name
1 O'Reilly Media
2 Packt Publishing
3 McGraw-Hill
Inserting Data into the Books Table
INSERT INTO Books (BookID, Title, AuthorNo, Price, Category, PublisherID)
VALUES
(1, 'Learning SQL', 101, 300.00, 'Database', 1),
(2, 'SQL for Data Analysis', 102, 500.00, 'Database', 2),
(3, 'Data Science with Python', 103, 700.00, 'Data Science', 3),
(4, 'Advanced SQL Queries', 101, 400.00, 'Database', 1),
(5, 'Introduction to Machine Learning', 104, 600.00, 'Machine Learning', 2),
(6, 'Big Data Analytics', 105, 750.00, 'Big Data', 3);
Books Table
BookID Title AuthorNo Price Category PublisherID
1 Learning SQL 101 300.00 Database 1
2 SQL for Data Analysis 102 500.00 Database 2
3 Data Science with Python 103 700.00 Data Science 3
4 Advanced SQL Queries 101 400.00 Database 1
BookID Title AuthorNo Price Category PublisherID
5 Introduction to Machine Learning 104 600.00 Machine Learning 2
6 Big Data Analytics 105 750.00 Big Data 3
Inserting Data into the Members Table
INSERT INTO Members (MemberID, FirstName, LastName, JoinDate)
VALUES
(1, 'John', 'Doe', '2023-01-15'),
(2, 'Jane', 'Smith', '2022-06-10'),
(3, 'Michael', 'Johnson', '2023-03-05'),
(4, 'Emily', 'Davis', '2021-12-20');
Members Table
MemberID FirstName LastName JoinDate
1 John Doe 2023-01-15
2 Jane Smith 2022-06-10
3 Michael Johnson 2023-03-05
4 Emily Davis 2021-12-20
Inserting Data into the Loans Table
INSERT INTO Loans (LoanID, MemberID, BookID, LoanDate, ReturnDate)
VALUES
(1, 1, 1, '2023-02-01', '2023-02-15'),
(2, 2, 3, '2023-03-05', '2023-03-20'),
(3, 3, 5, '2023-04-10', '2023-04-25'),
(4, 4, 6, '2023-05-01', '2023-05-15');
Loans Table
LoanID MemberID BookID LoanDate ReturnDate
1 1 1 2023-02-01 2023-02-15
2 2 3 2023-03-05 2023-03-20
3 3 5 2023-04-10 2023-04-25
4 4 6 2023-05-01 2023-05-15
II.Writing SQL Statements using MySQL
1. Basic SQL SELECT Statements
Objective: Retrieve data from a single table using the SELECT statement.
Query 1: Retrieve all columns from the Books table.
SELECT * FROM Books;
Query 2: Retrieve the Title and Price columns from the Books table.
SELECT Title, Price FROM Books;
Query 3: Retrieve all columns where the Category is "Database" from the Books table.
SELECT * FROM Books WHERE Category = 'Database';
2. Restricting and Sorting Data
Objective: Use WHERE to filter data and ORDER BY to sort the results.
Query 1: Retrieve books with price above 500 and sort by Title in descending order.
SELECT Title, Price FROM Books WHERE Price > 500 ORDER BY Title DESC;
Query 2: Retrieve members who joined after 2023-01-01 and sort by JoinDate in ascending
order.
SELECT FirstName, LastName, JoinDate FROM Members WHERE JoinDate > '2023-01-01' ORDER BY JoinDate
ASC;
Query 3: Retrieve books with price greater than 400 and sort them by Price in descending
order.
SELECT Title, Price FROM Books WHERE Price > 400 ORDER BY Price DESC;
3. Displaying Data from Multiple Tables
Objective: Use JOIN to retrieve related data from multiple tables.
Query 1: Retrieve LoanID, MemberName, and BookTitle from Loans, Members, and Books using
INNER JOIN.
SELECT Loans.LoanID, CONCAT(Members.FirstName, ' ', Members.LastName) AS MemberName, Books.Title
FROM Loans
INNER JOIN Members ON Loans.MemberID = Members.MemberID
INNER JOIN Books ON Loans.BookID = Books.BookID;
Query 2: Retrieve BookTitle, PublisherName from Books and Publishers using LEFT JOIN.
SELECT Books.Title, Publishers.Name AS PublisherName
FROM Books
LEFT JOIN Publishers ON Books.PublisherID = Publishers.PublisherID;
Query 3: Retrieve LoanID, MemberName, and BookTitle with members who haven’t borrowed
any books using LEFT JOIN.
SELECT Loans.LoanID, CONCAT(Members.FirstName, ' ', Members.LastName) AS MemberName, Books.Title
FROM Members
LEFT JOIN Loans ON Members.MemberID = Loans.MemberID
LEFT JOIN Books ON Loans.BookID = Books.BookID;
4. Aggregating Data Using Group Functions
Objective: Use aggregation functions (COUNT, SUM, AVG, MAX, MIN) to perform calculations.
Query 1: Count the total number of books in each category.
SELECT Category, COUNT(BookID) AS NumberOfBooks
FROM Books
GROUP BY Category;
Query 2: Calculate the average price of books in the "Database" category.
SELECT AVG(Price) AS AveragePrice
FROM Books
WHERE Category = 'Database';
Query 3: Get the maximum price of books in each category.
SELECT Category, MAX(Price) AS MaxPrice
FROM Books
GROUP BY Category;
5. Manipulating Data
Objective: Use INSERT, UPDATE, and DELETE statements to manage data.
Query 1: Insert a new book into the Books table.
INSERT INTO Books (BookID, Title, AuthorNo, Price, Category, PublisherID)
VALUES (7, 'Data Engineering Essentials', 106, 650.00, 'Data Engineering', 1);
Query 2: Update the price of the book "Learning SQL" to 350.
UPDATE Books
SET Price = 350
WHERE Title = 'Learning SQL';
Query 3: Delete the member with MemberID = 4 from the Members table.
DELETE FROM Members
WHERE MemberID = 4;
6. Creating and Managing Tables
Objective: Create and manage tables, including adding, modifying, and deleting columns.
Query 1: Create a new table Authors with AuthorID, FirstName, LastName, and Country columns.
CREATE TABLE Authors (
AuthorID INT PRIMARY KEY,
FirstName VARCHAR(50),
LastName VARCHAR(50),
Country VARCHAR(50)
);
Query 2: Add a new column PublishYear to the Books table.
ALTER TABLE Books
ADD PublishYear INT;
Query 3: Drop the Authors table.
DROP TABLE Authors;
III. Normalization
Objective: Normalization is the process of organizing data in a database to minimize redundancy
and improve data integrity. Each normal form builds on the previous one to achieve an efficient
database design.
Examples of Normal Forms
1. First Normal Form (1NF):
o Definition: Ensures that all values in a column are atomic (indivisible). There
should be no repeating groups.
o Example:
Unnormalized Table:
StudentID | Name | Subjects
----------|-----------|---------------------
1 | John Doe | Math, Science
2 | Jane Smith| English, History
1NF Table:
StudentID | Name | Subject
----------|------------|---------
1 | John Doe | Math
1 | John Doe | Science
2 | Jane Smith | English
2 | Jane Smith | History
2. Second Normal Form (2NF):
o Definition: Achieves 1NF and removes partial dependency (i.e., non-key
attributes must depend on the whole primary key).
o Example:
1NF Table:
CourseID | StudentID | CourseName | Instructor
---------|-----------|------------|------------
1 | 101 | Math | Dr. Smith
2 | 101 | Science | Dr. Jones
2NF Table (split into two tables):
Courses Table:
CourseID | CourseName | Instructor
---------|------------|-----------
1 | Math | Dr. Smith
2 | Science | Dr. Jones
Enrollments Table:
StudentID | CourseID
----------|---------
101 |1
101 |2
3. Third Normal Form (3NF):
o Definition: Achieves 2NF and removes transitive dependency (i.e., non-key
attributes should not depend on other non-key attributes).
o Example:
2NF Table:
EmployeeID | DeptID | DeptName | Manager
-----------|--------|----------|--------
1 | 10 | Sales | John
2 | 20 | HR | Mary
3NF Table (split to remove transitive dependency):
Employee Table:
EmployeeID | DeptID
-----------|-------
1 | 10
2 | 20
Department Table:
DeptID | DeptName | Manager
-------|----------|--------
10 | Sales | John
20 | HR | Mary
4. Boyce-Codd Normal Form (BCNF):
o Definition: Achieves 3NF and handles more complex cases of dependency.
o Example: Similar structure to 3NF but requires that every determinant is a
candidate key.
IV. Creating Cursors
Objective: A cursor is used to retrieve and process individual rows returned by a query in a
sequential manner.
Syntax and Types of Cursors
Implicit Cursor: Automatically created by SQL for single-row queries.
Explicit Cursor: Defined by users for multi-row queries.
Syntax:
DECLARE cursor_name CURSOR FOR SELECT_statement;
Example steps:
OPEN cursor_name;
FETCH cursor_name INTO variable;
CLOSE cursor_name;
Example:
DECLARE emp_cursor CURSOR FOR
SELECT emp_id, emp_name FROM employees;
OPEN emp_cursor;
FETCH emp_cursor INTO emp_id, emp_name;
CLOSE emp_cursor;
V. Creating Procedures and Functions
Objective: Stored procedures and functions encapsulate SQL code for reusability and better
performance.
Differences between Procedures and Functions
Procedures: Perform actions, can return multiple values, and use OUT parameters.
Functions: Return a single value and can be used in SQL expressions.
Syntax and Example
Stored Procedure:
CREATE PROCEDURE GetEmployee (IN emp_id INT)
BEGIN
SELECT * FROM employees WHERE employee_id = emp_id;
END;
Function:
CREATE FUNCTION GetEmployeeSalary(emp_id INT)
RETURNS DECIMAL(10, 2)
BEGIN
DECLARE salary DECIMAL(10, 2);
SELECT emp_salary INTO salary FROM employees WHERE employee_id = emp_id;
RETURN salary;
END;
Use Case:
Use a procedure for complex business logic that may affect multiple tables.
Use a function when a single value needs to be returned (e.g., computing a total or
retrieving a specific attribute).
7. Creating Packages and Triggers
Objective: Packages group multiple procedures, functions, and other database elements, while
triggers execute actions in response to specific events.
Example Package
Creating a Package:
CREATE PACKAGE EmployeePkg AS
PROCEDURE AddEmployee(emp_id INT, emp_name VARCHAR(100), emp_salary DECIMAL);
FUNCTION GetEmployeeCount RETURN INT;
END EmployeePkg;
Package Body:
CREATE PACKAGE BODY EmployeePkg AS
PROCEDURE AddEmployee(emp_id INT, emp_name VARCHAR(100), emp_salary DECIMAL) IS
BEGIN
INSERT INTO employees (employee_id, name, salary) VALUES (emp_id, emp_name, emp_salary);
END AddEmployee;
FUNCTION GetEmployeeCount RETURN INT IS
emp_count INT;
BEGIN
SELECT COUNT(*) INTO emp_count FROM employees;
RETURN emp_count;
END GetEmployeeCount;
END EmployeePkg;
Example Trigger
Objective: Create a trigger that runs before inserting a record to enforce specific business rules.
Syntax and Example:
CREATE TRIGGER before_insert_employee
BEFORE INSERT ON employees
FOR EACH ROW
BEGIN
-- Check if the salary is above a certain limit
IF :NEW.salary < 3000 THEN
RAISE_APPLICATION_ERROR(-20001, 'Salary must be above 3000');
END IF;
END;
Explanation:
Packages: Use packages to bundle related procedures/functions for better organization
and manageability.
Triggers: Use triggers to enforce rules or audit changes in data (e.g., logging updates,
validating data).