0% found this document useful (0 votes)
2 views

Dbms_experiments

The document outlines a series of experiments focused on database management using MySQL, covering installation, creating ER diagrams, writing SQL statements, normalization, using cursors, and creating procedures and functions. Each experiment includes objectives, prerequisites, equipment, procedures, and conclusions to enhance understanding of database concepts and practices. The content is structured to provide hands-on experience with practical applications in database design and management.

Uploaded by

Ritiz Shukla
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)
2 views

Dbms_experiments

The document outlines a series of experiments focused on database management using MySQL, covering installation, creating ER diagrams, writing SQL statements, normalization, using cursors, and creating procedures and functions. Each experiment includes objectives, prerequisites, equipment, procedures, and conclusions to enhance understanding of database concepts and practices. The content is structured to provide hands-on experience with practical applications in database design and management.

Uploaded by

Ritiz Shukla
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/ 23

Experiment 1 : Installing MySQL Database Server on Windows

Objectives:
 To understand the concept of database management systems.
 To learn how to install MySQL database server on a Windows system.
 To configure MySQL server for optimal performance.
Pre-requisites:
 Basic understanding of computer systems and operating systems.
 Administrative privileges on the system.
 Internet connection to download the MySQL installer.
Equipment:
 Computer system (Windows)
 Internet connection
Software:
 MySQL Installer
Procedure:
1. Download the MySQL Installer:
o Visit the official MySQL website ([invalid URL removed])

o Download the latest version of the MySQL Installer for Windows.

2. Run the Installer:


o Double-click the downloaded installer file to start the installation process.

3. Choose Setup Type:


o Select the "Custom" setup type to have more control over the installation process.

4. Select Products:
o Choose the following products to install:

 MySQL Server
 MySQL Workbench (Optional)
 MySQL Connector/ODBC (Optional)
5. Configure MySQL Server:
o Set the root password for the MySQL server.

o Choose the default character set and collation.

o Configure the port number (default is 3306).

6. Install MySQL Server:

pg. 1
o Click the "Execute" button to start the installation process.

Conclusion:
In this experiment, you have successfully installed MySQL database server on your Windows system.
You are now ready to explore the world of databases and start building your applications.

Output

pg. 2
Experiment 2: Creating an Entity-Relationship Diagram (ERD)
using a CASE Tool
Objectives:
 To understand the basic concepts of Entity-Relationship modeling.
 To learn how to use a CASE tool to create ERDs.
 To practice identifying entities, attributes, and relationships in a given scenario.
 To design a conceptual data model for a real-world application.
Pre-requisites:
 Basic understanding of database concepts.
 Familiarity with a CASE tool (e.g., Microsoft Visio, draw.io, Lucidchart).
Equipment:
 Computer with a CASE tool installed.
Procedure:
Scenario:
Consider a simple library management system. The system tracks books, members, and the borrowing
of books by members.
Steps:
1. Identify Entities:
o Book: Title, ISBN, Author, Publication Year, Publisher

o Member: Member ID, Name, Address, Contact Number

o Borrowing: Borrow Date, Due Date, Return Date

2. Identify Attributes:
o For each entity, identify the relevant attributes.

3. Identify Relationships:
o Book and Member: A member can borrow many books, and a book can be borrowed
by many members. This is a many-to-many relationship.
o Borrowing and Book: A borrowing record is associated with one book.

o Borrowing and Member: A borrowing record is associated with one member.

4. Create the ERD:


o Open the CASE tool: Launch the chosen CASE tool (e.g., Microsoft Visio, draw.io,
Lucidchart).
o Create Entities: Use the tool's shapes to represent entities and their attributes.

pg. 3
o Create Relationships: Use lines and symbols to represent relationships between
entities (e.g., one-to-one, one-to-many, many-to-many).
o Add Cardinality and Optionality: Indicate the cardinality (number of instances) and
optionality (whether participation is mandatory or optional) of each relationship.
Conclusion:
By following these steps and using a CASE tool, you can effectively create ERDs to visually
represent the structure of a database. ERDs are essential tools for database design as they help in
understanding and communicating the data requirements of an application.

Output

pg. 4
Experiment 3 : Writing SQL Statements Using MySQL
Objectives:
 To understand the basic syntax of SQL.
 To write SQL queries to retrieve, manipulate, and aggregate data from a MySQL database.
 To practice using various SQL clauses and functions.
 To create and manage database tables.
Pre-requisites:
 Basic understanding of database concepts.
 Access to a MySQL database server.
 A MySQL client tool (e.g., MySQL Workbench, MySQL Command-Line Client).
Procedure:
Part A: Writing Basic SQL SELECT Statements
1. Connect to the MySQL Server:
o Use the MySQL client tool to connect to your database server.

2. Retrieve All Data from a Table:


o SELECT * FROM table_name;

3. Retrieve Specific Columns:


o SELECT column1, column2 FROM table_name;

Output

Part B: Restricting and Sorting Data


1. Filtering Data:
o SELECT * FROM table_name WHERE condition;

pg. 5
o Example: SELECT * FROM customers WHERE city = 'New York';

2. Sorting Data:
o SELECT * FROM table_name ORDER BY column_name ASC/DESC;

o Example: SELECT * FROM customers ORDER BY last_name DESC;

Output

Part C: Displaying Data from Multiple Tables


1. Joining Tables:
o SELECT column1, column2 FROM table1 INNER JOIN table2 ON table1.column =
table2.column;
o Example: SELECT orders.order_id, customers.customer_name FROM orders INNER
JOIN customers ON orders.customer_id = customers.customer_id;
2. Output

pg. 6
Part D: Aggregating Data Using Group Functions
1. Counting Rows:
o SELECT COUNT(*) FROM table_name;

2. Finding the Sum:


o SELECT SUM(column_name) FROM table_name;

3. Finding the Average:


o SELECT AVG(column_name) FROM table_name;

4. Finding the Maximum Value:


o SELECT MAX(column_name) FROM table_name;

5. Finding the Minimum Value:


o SELECT MIN(column_name) FROM table_name;

6. Grouping Data:
o SELECT column1, COUNT(*) FROM table_name GROUP BY column1;

Output

Part E: Manipulating Data


1. Inserting Data:
o INSERT INTO table_name (column1, column2, ...) VALUES (value1, value2, ...);

2. Updating Data:
o UPDATE table_name SET column1 = value1, column2 = value2, ... WHERE
condition;

pg. 7
3. Deleting Data:
o DELETE FROM table_name WHERE condition;

Output

Part F: Creating and Managing Tables


1. Creating a Table:
o CREATE TABLE table_name ( column1 datatype, column2 datatype, ... );

2. Altering a Table:
o ALTER TABLE table_name ADD column_name datatype;

o ALTER TABLE table_name DROP COLUMN column_name;

o ALTER TABLE table_name MODIFY column_name datatype;

3. Dropping a Table:
o DROP TABLE table_name;

Output

pg. 8
Conclusion:
By practicing these SQL statements, you will gain a solid foundation in database querying and
manipulation. Experiment with different SQL queries to explore the full capabilities of MySQL.

pg. 9
Experiment 4 : Normalization of Database
Objectives:
 To understand the concept of normalization in database design.
 To identify anomalies in unnormalized data.
 To apply normalization techniques (1NF, 2NF, 3NF, BCNF) to normalize a given database
schema.
Pre-requisites:
 Basic understanding of database concepts.
 Knowledge of relational database models.
Equipment:
 Computer with a database design tool (e.g., ERwin Data Modeler, MySQL Workbench) or a
relational database management system (e.g., MySQL, PostgreSQL).
Procedure:
Scenario:
Consider a simple database for a library management system with the following unnormalized
relation:
Library(BookID, Title, Author, Publisher, Price, MemberID, MemberName, BorrowDate,
ReturnDate)
Steps:
1. Identify Anomalies:
o Redundancy: The same information (e.g., member details) is repeated for multiple
books.
o Update Anomaly: If a member's address changes, it needs to be updated in multiple
records.
o Deletion Anomaly: If a book is not borrowed by any member, the book's information
is lost.
2. First Normal Form (1NF):
o Eliminate repeating groups.

o Break the Library relation into three relations:

 Book(BookID, Title, Author, Publisher, Price)


 Member(MemberID, MemberName, Address)
 Borrowing(BookID, MemberID, BorrowDate, ReturnDate)
3. Second Normal Form (2NF):
o Eliminate partial dependencies.

pg. 10
o Ensure that each non-prime attribute is fully dependent on the primary key.

o In this case, the Library relation is already in 2NF.

4. Third Normal Form (3NF):


o Eliminate transitive dependencies.

o Ensure that no non-prime attribute is transitively dependent on the primary key.

o The Library relation is already in 3NF.

5. Boyce-Codd Normal Form (BCNF):


o A stricter form of 3NF.

o Ensure that every determinant is a candidate key.

o The Library relation is already in BCNF.

Using a Database Design Tool:


1. Create an ER Diagram:
o Use a database design tool to create an ER diagram for the unnormalized Library
relation.
2. Normalize the ER Diagram:
o Identify and eliminate anomalies.

o Break the Library relation into normalized relations.

3. Generate the Database Schema:


o Use the tool to generate SQL scripts to create the normalized database tables.

OUTPUT :
CREATE TABLE Books (
BookID INT PRIMARY KEY,
Title VARCHAR(100),
Author VARCHAR(100),
Publisher VARCHAR(100),
Price DECIMAL(10,2)
);

CREATE TABLE Members (


MemberID INT PRIMARY KEY,
MemberName VARCHAR(100)
);

pg. 11
CREATE TABLE Borrowings (
BorrowingID INT PRIMARY KEY,
BookID INT,
MemberID INT,
BorrowDate DATE,
ReturnDate DATE,
FOREIGN KEY (BookID) REFERENCES Books(BookID),
FOREIGN KEY (MemberID) REFERENCES Members(MemberID)
);

Conclusion:
By understanding and applying normalization techniques, you can design efficient and reliable
databases. Normalization helps to reduce data redundancy, improve data integrity, and enhance
database performance.

pg. 12
Experiment 5 : Creating and Using Cursors in MySQL
Objectives:
 To understand the concept of cursors in SQL.
 To learn how to declare and open cursors in MySQL.
 To practice fetching data using cursors.
 To close and deallocate cursors.
Pre-requisites:
 Basic understanding of SQL and MySQL.
 Access to a MySQL database server.
 A MySQL client tool (e.g., MySQL Workbench, MySQL Command-Line Client).
Procedure:
Scenario:
Consider a database with a table named employees containing columns employee_id, first_name,
last_name, and salary.
Steps:
1. Connect to the MySQL Server:
o Use your MySQL client tool to establish a connection to the database server.

2. Create a Stored Procedure:


SQL
DELIMITER //
CREATE PROCEDURE process_employees()
BEGIN
DECLARE done INT DEFAULT FALSE;
DECLARE emp_id INT;
DECLARE first_name VARCHAR(50);
DECLARE last_name VARCHAR(50);
DECLARE salary DECIMAL(10,2);

DECLARE cur1 CURSOR FOR


SELECT employee_id, first_name, last_name, salary FROM employees;

DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;

pg. 13
OPEN cur1;

read_loop: LOOP
FETCH cur1 INTO emp_id, first_name, last_name, salary;
IF done THEN
LEAVE read_loop;
END IF;

-- Process the fetched data here


SELECT CONCAT(first_name, ' ', last_name), salary;
END LOOP;

CLOSE cur1;
END //
DELIMITER ;
3. Execute the Stored Procedure:
SQL
CALL process_employees();
Explanation:
1. Declare Variables: Declare variables to store the fetched data from the cursor.
2. Declare Cursor: Declare a cursor cur1 to iterate over the result set of the SELECT statement.
3. Declare Handler: Declare a handler to handle the NOT FOUND condition when there are no
more rows to fetch.
4. Open Cursor: Open the cursor to make it ready for fetching data.
5. Fetch Data: Use the FETCH statement to retrieve rows from the cursor into the declared
variables.
6. Process Data: Inside the loop, process the fetched data as required (e.g., display, update, or
insert into another table).
7. Close Cursor: Close the cursor to release resources.
Additional Considerations:
 Cursor Types: MySQL supports different cursor types, including sensitive, insensitive,
scrollable, and read-only cursors.

pg. 14
 Cursor Scrolling: You can use FETCH NEXT, FETCH PRIOR, FETCH FIRST, and FETCH
LAST to navigate through the result set.
 Cursor Optimization: Be mindful of cursor usage as they can impact performance, especially
for large datasets. Consider alternative approaches like procedural SQL or temporary tables in
certain scenarios.

pg. 15
Experiment 6 : Creating Procedures and Functions in MySQL
Objectives:
 To understand the concept of stored procedures and functions in MySQL.
 To learn how to create and execute stored procedures.
 To practice creating and using user-defined functions.
 To improve database efficiency and maintainability.
Pre-requisites:
 Basic understanding of SQL and MySQL.
 Access to a MySQL database server.
 A MySQL client tool (e.g., MySQL Workbench, MySQL Command-Line Client).
Procedure:
Part A: Creating a Stored Procedure
1. Connect to the MySQL Server:
o Use your MySQL client tool to establish a connection to the database server.

2. Create a Stored Procedure:


SQL
DELIMITER //
CREATE PROCEDURE calculate_total_salary(IN department_id INT, OUT total_salary
DECIMAL(10,2))
BEGIN
SELECT SUM(salary) INTO total_salary
FROM employees
WHERE department_id = department_id;
END //
DELIMITER ;
3. Execute the Stored Procedure:
SQL
DECLARE @total_salary DECIMAL(10,2);
CALL calculate_total_salary(10, @total_salary);
SELECT @total_salary;
Part B: Creating a User-Defined Function
1. Create a User-Defined Function:

pg. 16
SQL
DELIMITER //
CREATE FUNCTION calculate_age(birthdate DATE)
RETURNS INT
DETERMINISTIC
BEGIN
DECLARE age INT;
SET age = YEAR(CURDATE()) - YEAR(birthdate);
IF DAYOFYEAR(CURDATE()) < DAYOFYEAR(birthdate) THEN
SET age = age - 1;
END IF;
RETURN age;
END //
DELIMITER ;
2. Use the User-Defined Function:
SQL
SELECT first_name, last_name, calculate_age(birthdate) AS age
FROM employees;
Explanation:
 Stored Procedures:
o Encapsulate complex SQL logic into reusable blocks.

o Can accept input parameters and return output parameters.

o Improve code modularity and maintainability.

 User-Defined Functions:
o Define custom functions to perform specific calculations or data manipulations.

o Can be used in SQL queries like built-in functions.

o Enhance query flexibility and readability.

Additional Considerations:
 Security: Be cautious when granting permissions to stored procedures and functions.
 Performance: Optimize stored procedures and functions for efficient execution.
 Debugging: Use logging and debugging tools to troubleshoot issues.

pg. 17
 Best Practices: Follow coding standards and conventions for better readability and
maintainability.

Experiment 7 : Creating Packages and Triggers in MySQL


Objectives:
 To understand the concept of packages and triggers in MySQL.
 To learn how to create and use packages to encapsulate related procedures and functions.
 To practice creating triggers to automate database operations.
Pre-requisites:
 Basic understanding of SQL and MySQL.
 Access to a MySQL database server.
 A MySQL client tool (e.g., MySQL Workbench, MySQL Command-Line Client).
Procedure:
Part A: Creating a Package
Note: MySQL doesn't have direct support for packages like PL/SQL. However, we can simulate
package-like behavior using stored procedures and functions.
1. Create a Stored Procedure:
SQL
DELIMITER //
CREATE PROCEDURE calculate_total_salary(IN department_id INT, OUT total_salary
DECIMAL(10,2))
BEGIN
SELECT SUM(salary) INTO total_salary
FROM employees
WHERE department_id = department_id;
END //
DELIMITER ;
2. Create a User-Defined Function:
SQL
DELIMITER //
CREATE FUNCTION calculate_age(birthdate DATE)
RETURNS INT
DETERMINISTIC
BEGIN

pg. 18
DECLARE age INT;
SET age = YEAR(CURDATE()) - YEAR(birthdate);
IF DAYOFYEAR(CURDATE()) < DAYOFYEAR(birthdate) THEN
SET age = age - 1;
END IF;
RETURN age;
END //
DELIMITER ;
3. Encapsulate Procedures and Functions (Simulated Package): While MySQL doesn't have
explicit package structures, you can group related procedures and functions logically and use
them together to achieve package-like behavior.
Part B: Creating a Trigger
1. Create a Trigger:
SQL
DELIMITER //
CREATE TRIGGER update_employee_salary_history
AFTER UPDATE ON employees
FOR EACH ROW
BEGIN
INSERT INTO employee_salary_history (employee_id, old_salary, new_salary,
update_date)
VALUES (OLD.employee_id, OLD.salary, NEW.salary, NOW());
END //
DELIMITER ;
Explanation:
 Packages (Simulated):
o Group related procedures and functions logically.

o Improve code organization and reusability.

o Consider using comments and naming conventions to clearly identify the package
components.
 Triggers:
o Automatically execute SQL statements in response to specific events (INSERT,
UPDATE, DELETE).
o Maintain data integrity and consistency.

pg. 19
o Automate data auditing and logging.

Additional Considerations:
 Security: Be cautious when granting permissions to stored procedures, functions, and triggers.
 Performance: Optimize triggers to avoid performance bottlenecks.
 Debugging: Use logging and debugging tools to troubleshoot issues.
 Best Practices: Follow coding standards and conventions for better readability and
maintainability.

pg. 20
Experiment 8 : Design and Implementation of a Payroll Processing System
using MySQL
Objectives:
 To design a relational database schema for a payroll system.
 To implement the database schema using MySQL.
 To write SQL queries to perform various payroll operations.
 To create stored procedures and functions to automate payroll calculations.
 To design a user interface (optional) to interact with the payroll system.
Pre-requisites:
 Basic understanding of SQL and MySQL.
 Knowledge of database design principles.
 Experience with a programming language (e.g., Python, Java, PHP) for user interface
development (optional).
Equipment:
 Computer with MySQL installed.
 MySQL Workbench or a similar database management tool.
 A text editor or IDE for writing SQL scripts.
Procedure:
1. Database Design:
 Identify Entities and Attributes:
o Employee: employee_id, first_name, last_name, salary, hire_date, department_id

o Department: department_id, department_name

o Deduction: deduction_id, deduction_name, deduction_amount

o Deduction_Employee: deduction_id, employee_id (to track deductions for each


employee)
o Salary_Slip: slip_id, employee_id, net_salary, gross_salary, deductions,
date_generated
 Create an ER Diagram:
o Visualize the entities and relationships between them.

 Normalize the Database:


o Ensure data integrity and avoid redundancy.

 Create the Database Schema:


o Write SQL statements to create the tables based on the normalized design.

pg. 21
2. Database Implementation:
 Create the Database:
o Use MySQL Workbench or the command-line tool to create a new database.

 Execute SQL Scripts:


o Run the SQL scripts to create the tables and define relationships.

 Populate the Database:


o Insert sample data into the tables.

3. SQL Queries:
 Retrieve Employee Information:
SQL
SELECT * FROM employees;
 Calculate Net Salary:
SQL
SELECT e.employee_id, e.first_name, e.last_name, e.salary - SUM(d.deduction_amount) AS
net_salary
FROM employees e
JOIN deduction_employee de ON e.employee_id = de.employee_id
JOIN deductions d ON de.deduction_id = d.deduction_id
GROUP BY e.employee_id;
 Generate Salary Slip:
SQL
-- Create a stored procedure or function to generate salary slips
4. Stored Procedures and Functions (Optional):
 Create a stored procedure to calculate net salary:
SQL
CREATE PROCEDURE calculate_net_salary(IN employee_id INT, OUT net_salary
DECIMAL(10,2))
BEGIN
SELECT salary - SUM(deduction_amount) INTO net_salary
FROM employees e
JOIN deduction_employee de ON e.employee_id = de.employee_id
JOIN deductions d ON de.deduction_id = d.deduction_id
WHERE e.employee_id = employee_id;

pg. 22
END;
 Create a function to calculate age:
SQL
CREATE FUNCTION calculate_age(birthdate DATE)
RETURNS INT
DETERMINISTIC
BEGIN
DECLARE age INT;
SET age = YEAR(CURDATE()) - YEAR(birthdate);
IF DAYOFYEAR(CURDATE()) < DAYOFYEAR(birthdate) THEN
SET age = age - 1;
END IF;
RETURN age;
END;
5. User Interface (Optional):
 Design the User Interface:
o Create a user-friendly interface using a programming language of your choice (e.g.,
Python, Java, PHP).
 Implement Functionality:
o Connect to the MySQL database.

o Execute SQL queries to retrieve and update data.

o Display data in a user-friendly format.

o Allow users to perform various payroll operations (e.g., add/edit employees, generate
salary slips).
Conclusion:
By following these steps, you can design and implement a robust payroll processing system
using MySQL. This experiment will help you gain practical experience in database design,
SQL programming, and application development.

pg. 23

You might also like