Lab Manual Spring 2024
Lab Manual Spring 2024
Introduction to
Database
CSC-217
Spring 2024
Lab Manual
Introduction to Database
2. Database Design
5. Views
6. SQL Functions
8. Advance SQL
9. Complex SQL
10. Triggers
● Conversion
● Numeric functions
● Date functions
● String functions
7. Advance SQL
SQL Clauses
● SELECT
● FROM
● WHERE
● GROUP BY
● HAVING
● ORDER BY
● LIMIT (or FETCH FIRST)
● OFFSET
● LIKE
● DISTINCT
● UNION
● AS
● AND
● OR
8. Advance SQL
Aggregate Functions
o COUNT()
o SUM()
o AVG()
o MIN()
o MAX()
9. Complex SQL
Nested Queries
1. Subquery in the WHERE Clause:
● Single-Row Subquery
● Multi-Row Subquery
10. Triggers
● Creating Triggers
● Trigger Syntax
● Timing (BEFORE vs. AFTER)
● Event Types (INSERT, UPDATE,
DELETE)
11. User-Defined Functions
● Creating and using PL-SQL procedures and
functions
12. Data Transaction Language (DTL) and Concurrency
Control
Implementing and Managing Database
Transactions
● Commit
● Savepoint
● Rollback
15 FINAL PROJECT
INSTITUTE OF BUSINESS MANAGEMENT
COLLEGE OF COMPUTER SCIENCE & INFORMATION SYSTEM
COMPUTER SCIENCE DEPARTMENT
Able to use software Able to use software Able to use Unable to use the
Digital with its standard and with its standard and software with software
Competencies advanced features advanced features its standard
3 without assistance with minimal features with
assistance assistance
Able to program/ Able to program/ Able to Unable to
Technical simulate the lab tasks simulate the lab program/ program/simulate
Implementation 3 with simplification tasks without errors simulate lab
tasks with
errors
Able to achieve all the Able to achieve all Able to achieve Unable to achieve
Lab Evaluation
3 desired results in the desired results most of the thedesired results
Results
alternate ways desired results
with errors
The laboratory manual Laboratory manual Laboratory Laboratory
has no grammatical has very few manual has manual has
and/ or spelling errors. grammatical/ multiple several
All sections of the spelling errors. grammatical/ grammatical/
Laboratory
1 report are very well- All sections of the spelling errors. spelling errors and
Manual
written and technically report are A few sections sentence
accurate. technically accurate. of the report construction is
contain poor.
technical errors.
RUBRIC-LABORATORY MANUAL
Score Sheet
Digital Problem-Solving Lab Evaluation Lab Total
Competencies Skills Results Manual Score
Lab (3) (3) (3) (1) (10)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
Total
The manual includes now 14 experiments. Each experiment is divided into two parts,
a theoretical part that explains the theory required to experiment properly. The
second part is practical; it consists of a set of programs that the student has to run to
understand the functioning of the tools introduced in the first part. Finally, the
student has to write his/her programs to show his/her understanding of the material
given in each lab session.
Software:
The software used is MySQL Workbench, Erd plus, draw.io
Projects:
The last part of the lab is dedicated to a project in which the student is required to use all
knowledge she/he has gained in the course.
LAB EXPERIMENT # 1
What Is a Database?
A database is an organized collection of structured information, or data, typically stored
electronically in a computer system. A database is usually controlled by a database
management system (DBMS).
MySQL Workbench
MySQL Workbench is a unified visual tool for database architects, developers, and DBAs.
MySQL Workbench provides data modeling, SQL development, and comprehensive
administration tools for server configuration, user administration, backup, and much more.
4. Click on Next. With this, you will install MySQL server, MySQL Workbench, and MySQL
shell.
5. Open MySQL Servers, select the server you want to install and move it to
the Products/Features to be installed window section. Now, expand Applications, choose
MySQL Workbench and MySQL shell. Move both of them to ‘Products/Features to be
installed’.
6. Click on the Next button. Now, click on the Execute button to download and install the
MySQL server, MySQL Workbench, and the MySQL shell.
7. Once the product is ready to configure, click on Next. Under Type and Networking, go
with the default settings and select Next.
8. For authentication, use the recommended strong password encryption.
10. Go for the default windows service settings and under apply configuration, click on
execute. Once the configuration is complete, click on finish.
11. Complete the installation. This will now launch the MySQL Workbench and the MySQL
Shell.
Once MySQL Workbench is installed, select the Local instance and enter the password.
Now, you can use the MySQL query tab to write your SQL queries.
CREATE:
ALTER:
RENAME:
TRUNCATE:
SELECT:
INSERT:
UPDATE:
DELETE:
LAB ASSIGNMENT
1. MAKE A DATABASE OF ABC HOSPITAL.
2. CREATE TABLES DOCTOR, STAFF, AND PATIENT (ANY 2 WITHOUT PRIMARY
KEYS).
3. WRITE A QUERY TO DISPLAY THE STRUCTURE OF ANY 2 TABLES.
4. WRITE A QUERY TO CREATE A PRIMARY KEY WITH THE ALTER TABLE
COMMAND IN THE DOCTOR AND STAFF TABLE.
5. WRITE A QUERY TO CREATE A FOREIGN KEY WITH THE ALTER TABLE
COMMAND IN THE PATIENT TABLE
6. WRITE A QUERY TO MODIFY A COLUMN IN STAFF TABLE.
7. WRITE A QUERY TO CHANGE A COLUMN NAME IN THE DOCTOR TABLE.
8. INSERT DATA UP TO 5 ROWS IN ALL TABLES
9. UPDATE DATA OF ANY 2 TABLES
10. DELETE DATA OF ANY 2 ROWS IN ANY TABLE.
DATABASE DESIGN
Objectives:
1. Using CASE tool
2. Forward and Reverse Engineering
To create a new ERD within the model, double-click on the “Add Diagram” button at the top
of the panel.
A new tab is opened, called “EER Diagram”. In MySQL Workbench, they are called EER
Add a Table
On the EER Diagram page, you’ve got a range of buttons on the top toolbar for saving and
opening diagrams. A toolbar on the left shows a range of tools for adding things to your
diagram.
We want to add a table to the diagram. Click on the button called “Place a New Table”,
which is about halfway down the left toolbar. Or, you can press “T” as a keyboard shortcut.
The cursor will change. Click anywhere on the diagram and a new table will be added.
It’s called “table1” by default. Next, you’ll probably want to rename the table and add
columns.
To do this, double-click on the table. A large panel will open at the bottom of the screen.
In this panel, you can rename the table.
You can also add columns. When you add the first column, it defaults to the primary key.
You can change this if you like.
You can add multiple columns, and specify data types, constraints, and more for each
column.
Here’s an example of a table with some columns:
Keep adjusting the table until you’re happy with the columns.
Relate a Second Table
Your ERD will likely need more than one table. To add a second table, follow the same steps
as adding the first table: click on the “Place a New Table” button and click anywhere on the
diagram.
You can then double-click on the table to rename the table and add columns in the same
way.
How can you relate these two tables together?
You can do this by adding a foreign key to the table and specifying the table and column it
relates to. The diagram will be updated to show this automatically.
In the table that you want to add a foreign key to, double-click on it to open the panel.
Open the Foreign Key tab at the bottom of the screen.
Enter the name of the new foreign key you want to create.
In this example, I’ve called it fk_model_make.
Then, select the table you want to relate this to.
Once you’ve selected the table, you can then select the two columns that are related in the
“Foreign key details” section to the right.
In this example, I’ve specified that the make_id in this table is related to the id column in the
make table.
Once you do this, the diagram will be updated to show a dotted line between the two
columns in each table.
You’ve now added two tables to your diagram. You can repeat this process to add as many
tables as you need.
Save the ERD File
To save your changes, go to File > Save Model. The Save dialog box is shown. Select the
location where you want to save your file and a filename. This model file is saved as a .mwb
file.
REVERSE ABD FORWARD ENGINEERING IN MYSQL WORKBENCH
We normally create a physical database from the ER diagram. First, we design and then
implement. This is called Forward Engineering.
We normally build a physical database from the ER diagram – this is called forward
engineering. But there are times when you want to do the opposite – create diagram from
existing database schema. This task is called reverse engineering,
To reverse engineer a database in MySQL Workbench:
1. Select Database > Reverse Engineer from the top menu of MySQL Workbench
2. Set/review parameters for connecting to the DBMS then click Continue
3. Enter password if required, then click OK
4. The wizard will connect to the DBMS, fetch a list of databases, and check for any
issues. Click Continue
5. Select the database/s you would like to reverse engineer, then click Continue
6. The wizard will retrieve all objects from the selected schema/s and check the results.
Click Continue
7. Select the database objects you’d like to have reverse engineered, then click Execute
8. The wizard will now reverse engineer all selected objects and generate the EER
diagram (behind the scenes). Click Continue
9. A summary is displayed. Click Close
Lab Assignment
Generate the SQL script from the designed database and verify the database structure in the
MySQL server.
Reverse engineering the database schema of your choice into an ERD. Modifying the ERD
and applying changes to the database.
Data Query Language is a subset of SQL (Structured Query Language) that is used to retrieve
or query data from a database. The primary DQL command is SELECT, which is used to
specify the columns you want to retrieve and the conditions for retrieving the data.
1. Column Alias:
Column aliases are used to provide a temporary name to a column in the result set. This is
particularly useful when the original column names are complex or when you want to
improve the readability of your output. The AS keyword is optional.
Syntax: Example:
2. Table Alias:
Table aliases are used to provide a shorthand notation for a table name. They are especially
important when dealing with self-joins or queries involving multiple tables. The alias is used
to reference columns from a specific table in the query.
Syntax: Example:
3. Calculation:
Calculation in SQL involves performing operations on numerical values in columns. This can
include basic arithmetic operations like addition, subtraction, multiplication, and division.
The result can be given a temporary name using an alias.
Syntax: Example:
4. Concatenation:
Concatenation is the process of combining two or more strings into a single string. In SQL,
the CONCAT function or the || operator (depending on the database system) is commonly
used for concatenation. This is useful for creating more informative or formatted output.
Syntax: Example:
SELECT CONCAT(column1, ' ', column2) AS SELECT CONCAT(first_name, ' ', last_name)
full_name AS full_name
LAB ASSIGNMENT
Column Alias:
Write a query that retrieves the student names and GPAs from the "Students"
table, giving them meaningful column aliases (e.g., "Student Name" and "GPA").
Display the results with the column aliases.
Table Alias:
Write a query that retrieves student names and their corresponding department
names using a table alias for the "Students" and "Departments" tables.
Display the results with the table alias in use.
Calculation:
Create a new table named "Products" with columns for product name, price, and
quantity.
Insert 5 records into the "Products" table with various product names, prices, and
quantities.
Write a query to calculate the total cost for each product by multiplying the price
and quantity.
Display the results with the calculated total costs.
Concatenation:
Write a query that retrieves the full names of students by concatenating their first
name and last name.
Display the results with the concatenated full names.
JOINS
JOINS
A JOIN clause is used to combine rows from two or more tables based on a common field
between them allowing us to retrieve data from multiple tables. There are 4 different kinds
of joins as described below.
INNER JOIN
This join returns records that have matching values in both tables. The records in Table 1
that do not have matching values in Table 2 will not show.
SELECT col1_name, col2_name, col3_name
FROM tb1_name
INNER JOIN tb2_name
ON tb1_name.col_name = tb2_name.col_name;
SELECT t1.col_name(s), t2.col_name(s)
FROM tb1_name as t1
INNER JOIN tb2_name as t2
ON t1.col_name = t2.col_name;
Example:
OUTER JOIN
1. LEFT JOIN:
This join returns all the records from the left table and only the matched records from the
right table or NULL if there is no match in the right table.
SELECT col1_name, col2_name, col3_name
FROM tb1_name
LEFT JOIN tb2_name
ON tb1_name.col_name = tb2_name.col_name;
SELECT t1.col_name(s), t2.col_name(s)
FROM tb1_name as t1
LEFT JOIN tb2_name as t2
ON t1.col_name = t2.col_name
WHERE t2.col_name IS NULL;
Example:
2. RIGHT JOIN
This join does the reverse of the aforementioned LEFT JOIN. It returns all the records from
the right table and only the matched records from the left table or NULL if there is no match
in the left table.
SELECT col1_name, col2_name, col3_name
FROM tb1_name
RIGHT JOIN tb2_name
ON tb1_name.col_name = tb2_name.col_name;
SELECT t1.col_name(s), t2.col_name(s)
FROM tb1_name as t1
RIGHT JOIN tb2_name as t2
ON t1.col_name = t2.col_name
WHERE t1.col_name IS NULL;
Example:
FULL JOIN
This join combines the results of both LEFT and RIGHT joins and returns all the records
wherever there is a match in either the left or the right table. Some DB management
software (such as MySQL) do not support FULL JOIN. In such cases, the UNION clause is used
to combine the two joins.
SELECT col1_name, col2_name, col3_name
FROM tb1_name
FULL OUTER JOIN tb2_name
ON tb1_name.col_name = tb2_name.col_name;
SELECT t1.col_name(s), t2.col_name(s)
FROM tb1_name as t1
FULL OUTER JOIN tb2_name as t2
ON tb1.col_name = tb2.col_name
WHERE t1.col_name IS NULL
OR t2.col_name IS NULL;
UNION
This union keyword is used to combine the results of two or more select statements. By
default, UNION returns only distinct records. In order to use the UNION operator, we must
ensure that:
Each SELECT statement in UNION must have the same number of columns.
The columns must in each SELECT statement must be in the same order.
The columns must have similar datatypes.
The syntax for using UNION is:
SELECT col1_name, col2_name, col3_name FROM tb1_name
WHERE condition(s)
UNION
SELECT col1_name, col2_name, col3_name FROM tb2_name
WHERE condition(s);
Example:
LAB ASSIGNMENT
1. Create a database named "HospitalManagementSystem".
2. Create a table named "Doctors" with the following fields:
(DoctorID (Primary Key, INT),
DoctorName (VARCHAR(12)),
ContactNumber(VARCHAR(15)).
PatientName (VARCHAR(7)),
Age (INT),
Gender(VARCHAR(10)).
AppointmentDate (DATE),
AppointmentTime (TIME)).
TASKS:
1. Write an SQL query to retrieve the details of all appointments along with the
corresponding patient names.
2. Write an SQL query to display the details of all doctors along with the appointments,
if any, made by the patients.
3. Write an SQL query to list the details of all patients, including those who have not
made any appointments yet.
4. Write an SQL query to retrieve the details of all doctors along with their associated
department information, even if no appointments have been made by any patient.
5. Write an SQL query to list the details of all patients along with their appointments,
including cases where there are no corresponding appointments made.
6. Write an SQL query to fetch the details of all patients and doctors where there are
no matching appointments.
VIEWS
VIEWS
In SQL, a view is a virtual table or logical table based on the result-set of an SQL statement.
Since a database view is similar to a database table, which consists of rows and columns, we
can query data against it. The database system stores database views as a SQL SELECT
statement. When the actual data of the tables changes, the view mirrors that change as
well.
Advantages of SQL Views:
Simplicity – A database view allows us to simplify complex queries.
Security – Views can be made accessible to users while the underlying tables are not
directly accessible.
Flexibility – Queries of views may not change when underlying tables change.
2. Joint View:
A joint view in MySQL is a view that combines columns from two or more tables using a join
operation. This allows you to create a consolidated view that pulls data from multiple tables,
enabling you to work with data from different sources in a single virtual table.
Example:
Suppose you have two tables, `Sales` and `Customers`. You can create a joint view to display
the sales information along with the corresponding customer names:
CREATE VIEW SalesCustomerView AS
SELECT s.SaleID, s.Amount, c.CustomerName
FROM Sales s
JOIN Customers c ON s.CustomerID = c.CustomerID;
Lab Tasks
Task 1: Creating a Simple View
Create the Doctor, Patient, and Appointment tables with appropriate fields.
Insert some sample data into these tables.
Create a simple view to display appointment details, including the doctor's name,
patient's name, and appointment date.
Task 2: Creating a Joint View
Using the same database, create a joint view that combines data from the Doctor
and Appointment tables to display the appointments along with the corresponding
doctor's information.
Task 3: Creating a View with Check Option
Assuming you have an Appointment table with fields AppointmentID,
AppointmentDate, and Status, create this table with some sample data.
Create a view with a check option to display only those appointments that have the
status set to 'Confirmed'.
Task 4: Test the Views
Query the views you created in Tasks 1, 2, and 3 to observe the combined data.
Attempt to modify the views and observe how the underlying tables are affected (if
applicable).
SQL FUNCTIONS
SQL Functions:
SQL functions are pre-defined or user-defined operations that can be applied to manipulate
and process data in a database. They are used within SQL queries to perform various tasks,
such as data manipulation, calculation, and formatting. Functions can operate on one or
more values and typically return a single value as a result.
There are two main types of SQL functions:
1. Built-in Functions
2. User-Defined Functions
1. Conversion Functions:
Conversion functions are used to convert a value from one data type to another. They
ensure compatibility between different data types within SQL expressions.
Example 1 Example 2
Convert a numeric value to a string Convert a string to an integer
SELECT CAST(123 AS VARCHAR) AS result; SELECT CONVERT(INT, '456') AS result;
2. Numeric Functions:
Numeric functions perform operations on numeric data types. They can be used for
calculations, rounding, and other mathematical operations.
Example 1 Example 2
Calculate the square root of a number Round a decimal number to the nearest
SELECT SQRT(25) AS result; integer
SELECT ROUND(3.14159) AS result;
3. Date Functions:
Date functions are used for working with date and time values. They can calculate
differences between dates, extract components of dates, and perform various other
operations.
Example 1 Example 2
Get the current date Calculate the difference between two dates
SELECT GETDATE() AS current_date; SELECT DATEDIFF(DAY, '2023-01-01', '2023-
01-10') AS days_difference;
4. String Functions:
String functions operate on character data and are used for manipulating and formatting
strings.
Example 1 Example 2
Concatenate two strings Get the length of a string
SELECT CONCAT('Hello', ' ', 'World') AS SELECT LEN('Database') AS string_length;
greeting;
LAB ASSIGNMENT
Perform the following SQL Row Level Built in Function:
Conversion
Numeric functions
Date functions
String functions
Teacher Signature: ________________________
Student Registration No: ________________________
LAB EXPERIMENT # 7
Q#1(b). You are tasked with developing a small employee management system for a
company. The company has two main components in its system: Employees and
Departments. You need to manage employee data such as ID, name, age, and department
details, and perform various SQL queries to retrieve specific information.
1. Create Tables:
o Create two tables: Employees and Departments.
The Employees table should have fields such as id, name, age, and department_id.
The Departments table should have fields such as department_id and
department_name.
2. Insert Data:
o Insert at least 6 sample records into both the Employees and Departments
tables.
3. Basic Queries:
o You are now required to retrieve data using the following SQL queries:
o Retrieve the id and name of all employees.
o From which table will you retrieve employee information? Specify the table in the
FROM clause.
o Retrieve the details of employees who are older than 30 years.
o Retrieve department details and order them by department_name in descending order.
o Retrieve the first 5 records from the Departments table.
o Retrieve records from the Employees table starting from the 6th record.
o Find employees whose names start with the letter 'J'.
o Retrieve unique department names from the Employees table.
o Combine results from the Employees and Departments tables.
o Retrieve details of employees who are older than 30 years and work in the Sales
department.
o Retrieve details of employees who are either older than 30 years or work in the
Sales department.
Task: Based on the above requirements, write SQL queries to create the tables, insert the
data, and perform the necessary retrievals. Make sure to use appropriate filtering, ordering,
and pagination where needed.
LAB EXPERIMENT # 8
AGGREGATE FUNCTIONS
Aggregation in SQL refers to the process of summarizing or combining multiple rows of data
into a single value. This is often done using aggregate functions. Aggregate functions
perform operations on a set of values and return a single result. Here are common
aggregate functions:
1. COUNT():
lab Assignment
Create database lab 07 and make 3 tables with following attributes in it :
1. product table (product name , product id , price)
2. Customers ( CustomerID , CustomerName , Address )
3. Orders ( OrderID , ProductID , CustomerID , Quantity )
TASKS:
1. Write a query to find the total number of products in the "Products" table.
2. Calculate the total quantity of all orders in the "Orders" table.
3. Find the average price of all products in the "Products" table.
4. Determine the minimum quantity of products ordered in the "Orders" table.
5. Find the maximum price among all the products in the "Products" table.
6. Count the number of orders for each product in the "Orders" table and display only
those products that have more than one order.
7. Calculate the total quantity of orders for each customer in the "Orders" table and
display only those customers who have a total quantity of more than 3.
8. Find the average price of each product in the "Products" table and display only those
products that have an average price higher than $50.
9. Write a query to find the total number of orders in the "Orders" table.
10. Calculate the total price of all products in the "Products" table.
NESTED QUERIES
Nested Queries:
Nested queries, also known as subqueries, are queries embedded within another query.
They can be used in various parts of a SQL statement to perform operations on data more
dynamically and efficiently.
Example:
SELECT employee_name
FROM employees
WHERE salary > (SELECT AVG(salary) FROM employees);
Multi-Row Subquery: A multi-row subquery returns multiple rows, and it can be
used with operators like IN, ANY, or ALL in the outer query's condition.
Example:
SELECT department_name
FROM departments
WHERE department_id IN (SELECT department_id FROM employees WHERE salary > 50000);
UPDATE employees
SET salary = salary * 1.1
WHERE department_id IN (SELECT department_id FROM departments WHERE
department_name = 'Finance');
DELETE with Subquery:
Lab Assignment:
Task 1: Write a query to retrieve the names of employees who have a salary greater than
the average salary of their department.
Task 2: Write a query to find the departments where the number of employees is greater
than the average number of employees in all departments.
Task 3: Write a query to retrieve the employee names along with the difference between
their salary and the average salary across all employees.
Task 4: Perform subqueries with insert update and delete operations.
Teacher Signature: ________________________
Student Registration No: ________________________
1.
LAB EXPERIMENT # 10
TRIGGERS
Triggers:
Triggers are a special type of stored procedure in a database that automatically execute in
response to certain events on a particular table or view. These events can be INSERT,
UPDATE, DELETE, or a combination of these. Triggers are used to enforce business rules,
maintain data integrity, or perform specific actions when certain conditions are met.
They are associated with a specific table or view and are executed automatically when the
specified event occurs.
Syntax
The basic syntax for creating a trigger includes the trigger name, the event (INSERT,
UPDATE, DELETE), the table or view associated with the trigger, and the trigger body.
CREATE TRIGGER trigger_name
AFTER INSERT ON table_name
FOR EACH ROW
BEGIN
-- Trigger logic goes here
END;
LAB ASSIGNMENT
Create triggers of the following:
Scenario 1:
i want to generate a log table for employee table which will catch all the activities on it
(insert, update , delete)
Scenario 2:
Now create a trigger which will multiply the salary whenever a new employee is inserted
in the table
Scenario 3:
Create a trigger on inventory table that whenever a customer place an order , it will
minus the product quantity from that table
Example:
DELIMITER //
CREATE PROCEDURE GetEmployeeDetails (IN employee_id INT)
BEGIN
SELECT * FROM employees WHERE id = employee_id;
END //
DELIMITER ;
TYPES OF PROCEDURES
1. Basic Procedure:
This is a simple stored procedure that performs a specific task or set of tasks.
Example:
DELIMITER //
CREATE PROCEDURE SimpleProcedure()
BEGIN
-- Procedure logic goes here
SELECT 'Hello, World!' AS Message;
END //
DELIMITER ;
Example:
DELIMITER //
CREATE PROCEDURE GetEmployeeDetails(IN employee_id INT)
BEGIN
SELECT * FROM employees WHERE id = employee_id;
END //
DELIMITER ;
Example:
DELIMITER //
CREATE PROCEDURE GetEmployeeCount(IN department_name VARCHAR(255), OUT
employee_count INT)
BEGIN
SELECT COUNT(*) INTO employee_count FROM employees WHERE department =
department_name;
END //
DELIMITER ;
Example:
DELIMITER //
CREATE PROCEDURE UpdateSalary(INOUT emp_salary DECIMAL(10,2))
BEGIN
SET emp_salary = emp_salary * 1.1;
END //
DELIMITER ;
5. Conditional Procedure:
Procedures can include conditional statements for more complex logic.
Example:
DELIMITER //
CREATE PROCEDURE CheckDepartment(IN department_name VARCHAR(255))
BEGIN
IF department_name = 'IT' THEN
SELECT 'IT Department' AS Message;
ELSE
SELECT 'Other Department' AS Message;
END IF;
END //
DELIMITER ;
User-Defined Functions:
User-Defined Functions (UDFs) in MySQL are custom functions created by users to perform
specific tasks. They can be classified into two main types: stored procedures and stored
functions.
Example:
DELIMITER //
CREATE FUNCTION GetEmployeeCount (IN department_name VARCHAR(255)) RETURNS INT
BEGIN
DECLARE count INT;
SELECT COUNT(*) INTO count FROM employees WHERE department = department_name;
RETURN count;
END //
DELIMITER ;
Calling Functions:.
-- Calling a stored function
SELECT GetEmployeeCount('IT');
TYPES OF FUNCTIONS
1. Scalar Functions:
Scalar functions return a single value.
Example:
DELIMITER //
CREATE FUNCTION GetEmployeeCount() RETURNS INT
BEGIN
DECLARE count INT;
SELECT COUNT(*) INTO count FROM employees;
RETURN count;
END //
DELIMITER ;
2. Table-Valued Functions:
Table-valued functions return a result set (table).
Example:
DELIMITER //
CREATE FUNCTION GetEmployeesInDepartment(department_name VARCHAR(255))
RETURNS TABLE
BEGIN
RETURN (SELECT * FROM employees WHERE department = department_name);
END //
DELIMITER ;
3. Deterministic Functions:
Deterministic functions produce the same result for the same input values.
They are identified by the DETERMINISTIC keyword.
Example:
DELIMITER //
CREATE FUNCTION AddNumbers(a INT, b INT) RETURNS INT DETERMINISTIC
BEGIN
RETURN a + b;
END //
DELIMITER ;
4. Non-Deterministic Functions:
Non-deterministic functions may produce different results for the same input values.
They are identified by the NOT DETERMINISTIC keyword.
Example:
DELIMITER //
CREATE FUNCTION GetCurrentTime() RETURNS TIMESTAMP NOT DETERMINISTIC
BEGIN
RETURN NOW();
END //
DELIMITER ;
Example:
DELIMITER //
CREATE FUNCTION MultiplyNumbers(a INT, b INT) RETURNS INT
BEGIN
RETURN a * b;
END //
DELIMITER ;
Example:
DELIMITER //
CREATE FUNCTION DivideNumbers(a INT, b INT, OUT result DECIMAL(10,2))
BEGIN
SET result = a / b;
END //
DELIMITER ;
Stored procedures are typically called using Stored functions can be used directly in SQL
the CALL statement and are not directly queries, WHERE clauses, and expressions.
used in SQL queries.
Stored procedures can be more complex, as Stored functions are designed for simpler
they can include multiple SQL statements tasks and calculations, focusing on
and perform complex logic. returning a single value.
Used for encapsulating business logic. Used for calculations, data retrieval, and
tasks requiring a single return value.
Ideal for usage in SELECT statements,
WHERE clauses, and expressions.
LAB ASSIGNMENT
Question 1: Create a stored procedure named GetEmployeeDetails that takes an employee
ID as input and returns the details of that employee.
Question 2: Call the stored procedure GetEmployeeDetails for a specific employee ID. What
is the output?
Question 3: Create a stored function named CalculateBonus that takes an employee's salary
and years of service as inputs and returns the bonus amount. Assume a bonus of 5% of the
salary for each year of service.
Question 4: Use the function CalculateBonus in a SELECT query to calculate the bonus for an
employee with a salary of $50,000 and 3 years of service. What is the bonus amount?
Question 5: Create a stored procedure named GetDepartmentCount that takes a
department name as input and returns the count of employees in that department. Use an
output parameter to return the count.
Question 6: Call the stored procedure GetDepartmentCount for a specific department
name. What is the output count?
Question 7: Create a stored function named UpdateSalary that takes an employee ID and a
salary increase percentage as inputs, updates the salary, and returns the updated salary.
Assume the percentage is in decimal form (e.g., 0.1 for 10%).
Question 8: Use the function UpdateSalary to update the salary for an employee with ID 101
by a 15% increase. What is the updated salary?
Question 9: Create a combined procedure for Insert, Update, and delete operations
Question 10: Create a BMI calculator Function. Also call it with all 3 methods of function
calling.
-- Start a transaction
START TRANSACTION;
-- Perform some operations
UPDATE employees SET salary = salary * 1.1 WHERE department = 'IT';
-- Create a savepoint
SAVEPOINT salary_update;
-- Perform more operations
DELETE FROM employees WHERE department = 'HR';
-- Roll back to the savepoint
ROLLBACK TO salary_update;
Output Explanation:
1. The transaction starts.
2. Salaries of employees in the 'IT' department are increased by 10%.
3. A savepoint named salary_update is created.
4. Some operations are performed, such as deleting employees from the 'HR'
department.
5. The transaction is rolled back to the savepoint (salary_update), undoing changes made
after the savepoint.
2. Commit:
The COMMIT statement is used to permanently save the changes made during the
current transaction.
Once a transaction is committed, its changes become permanent and cannot be rolled
back.
Example:
-- Start a transaction
START TRANSACTION;
-- Perform some operations
UPDATE employees SET salary = salary * 1.1 WHERE department = 'IT';
-- Commit the transaction
COMMIT;
Output Explanation:
1. The transaction starts.
2. Salaries of employees in the 'IT' department are increased by 10%.
3. The transaction is committed, making the changes permanent.
3. Rollback:
The ROLLBACK statement is used to undo transactions that have not been committed.
It can be used to roll back the entire transaction or to a specific savepoint.
Example:
-- Start a transaction
START TRANSACTION;
-- Perform some operations
UPDATE employees SET salary = salary * 1.1 WHERE department = 'IT';
-- Roll back the entire transaction
ROLLBACK;
Output Explanation:
1. The transaction starts.
2. Salaries of employees in the 'IT' department are increased by 10%.
3. The entire transaction is rolled back, undoing all changes made within the transaction.
LAB ASSIGNMENT
Question 1: Update the status of order ID 789 to 'Shipped' and ensure the changes are
permanently saved using which SQL statement?
Question 2: Insert a new product review and use which SQL statement to undo the
transaction if an error (e.g., missing rating) occurs?
Question 3: Change the address for customer ID 123 to '123 Main Street,' create a
savepoint, attempt to update the postal code, and roll back to the savepoint if the
update fails, using which SQL feature?
Performance Tuning:
Performance tuning involves adjusting various parameters and configurations to enhance
the overall performance of a database system.
Areas of Focus:
Hardware Configuration: Ensure adequate resources (CPU, RAM, Disk) are allocated.
Database Configuration: Optimize database settings and parameters.
Query Performance: Enhance the performance of individual queries.
Indexing Strategy: Evaluate and refine the use of indexes.
Caching and Buffering: Optimize caching mechanisms to reduce disk I/O.
2. Indexing Strategies:
Proper indexing is a cornerstone of database performance. Selecting the right indexes on
columns frequently used in queries can significantly improve retrieval speed. However, an
overabundance of indexes can lead to diminishing returns and increased maintenance
overhead.
Example: In a customer database, an index on the "customer_id" column might be
beneficial for queries that retrieve customer information. However, blindly indexing every
column can lead to unnecessary overhead, so strategic choices based on query patterns are
essential.
LAB ASSIGNMENT
Sample Query:
SELECT course_id, AVG(grade) AS average_grade
FROM student_grades
WHERE course_id = 101
GROUP BY course_id;
Tasks:
1. Execute the sample query against your database. What is the execution time?
2. Use the EXPLAIN statement to analyze the execution plan of the original query. What
insights can you gather?
3. Based on the execution plan, identify potential areas for optimization. What
optimizations could improve performance?
4. Apply optimizations to the query. Specify the optimizations you applied.
5. Run the optimized query against your database. What is the execution time of the
optimized query?
6. Compare the execution times of the original and optimized queries. What
differences do you observe?
7. Use database tools or queries to measure resource consumption for both queries.
What insights do you gain from resource consumption metrics?
Data Control Language (DCL) is a subset of SQL (Structured Query Language) that deals with
the control and management of access to data stored in a database. DCL commands are
responsible for defining the permissions and restrictions on the database objects, such as
tables and views.
DCL ensures the security and integrity of a database by regulating who can access and
manipulate the data. It allows database administrators to grant or revoke permissions to
users and roles.
Example Steps:
Step 1: Define Users
-- Create users 'john' and 'alice'
CREATE USER 'john'@'localhost' IDENTIFIED BY 'password';
CREATE USER 'alice'@'localhost' IDENTIFIED BY 'password';
If you want to see more detailed information about each user, you can use:
After resetting the password, it's a good practice to run the FLUSH PRIVILEGES;
statement to apply the changes immediately:
FLUSH PRIVILEGES;
LAB ASSIGNMENT
1. Create 2 users in MySQL and Verify that the new user has been created successfully.
2. Grant the SELECT privilege on the 'company.department' table to the ‘first user’ and
all privileges to the ‘company’ to ‘second user’
3. Revoke the UPDATE privilege from the second user. Confirm the revocation by
attempting to execute an UPDATE query with the 'student' user.
4. Grant both SELECT and INSERT privileges on the 'department' table First user. Verify
that the user can SELECT and INSERT data into the ' department' table.
5. Use the SHOW GRANTS statement to view the privileges granted to both the users.
6. Change the password for the First user to a new password of your choice. Attempt to
connect to MySQL Workbench using the new password to ensure the change is
effective.
7. Challenge Exercise - Research and execute commands to create a role named
'data_analyst.' Grant the SELECT privilege on the 'sales' table to the 'data_analyst'
role. Assign the 'First' user to the 'data_analyst' role.