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

Lab Manual Spring 2024

The lab manual for CSC-217: Introduction to Database outlines the course structure for Spring 2024, detailing various topics such as SQL, database design, and advanced SQL concepts. It includes a comprehensive table of contents, weekly session topics, and evaluation criteria for lab assignments. Additionally, it provides guidelines for using MySQL Workbench and conducting practical experiments related to database management and design.

Uploaded by

wahid.ali
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Lab Manual Spring 2024

The lab manual for CSC-217: Introduction to Database outlines the course structure for Spring 2024, detailing various topics such as SQL, database design, and advanced SQL concepts. It includes a comprehensive table of contents, weekly session topics, and evaluation criteria for lab assignments. Additionally, it provides guidelines for using MySQL Workbench and conducting practical experiments related to database management and design.

Uploaded by

wahid.ali
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 60

Lab Manual

Introduction to
Database
CSC-217

Spring 2024
Lab Manual
Introduction to Database

Semester : Spring 2024


Program : BSCS
Course Code : CSC-217
Credits :1
Faculty Name : Ms. Ujala Rehan
Student Name :
Student ID :
Total Marks : 25
Obtained Marks :
Submitted Date :
Table of Contents
S.NO DATE SESSION TOPICS SIGNATURE

1. Database Setup and Basic SQL

2. Database Design

3. SQL Queries (DQL)


4. Joins

5. Views

6. SQL Functions

7. OPEN ENDED LAB (Advance SQL)

8. Advance SQL

9. Complex SQL

10. Triggers

11. User-Defined Functions

12. Data Transaction Language (DTL) and Concurrency


Control
13. Query Optimization and Performance Tuning

14. Data Control Language (DCL) and Security


Weekly Contents
S.NO DATE SESSION TOPICS SIGNATURE

01. Database Setup and Basic SQL


1. Setting up the development environment
2. Basic SQL queries
DDL:
● Create
● Drop
● Alter
● Truncate
● rename
DML:
● Insert
● Update
● Delete
3. Creating and Populating a Database
02. Database Design
1. Using CASE tool
2. Forward and Reverse Engineering
3. SQL Queries (DQL)
To understand the basics of SQL and be able to
create the basic commands.
● Column Alias
● Table alias
● Calculation
● Concatenation
4. Joins
● Inner join,
● Left join,
● Right join
● Full join
5. Views
● View
● joint view
● View with check option
6. SQL Functions
SQL Row Level Built in Function:

● 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

2. Subquery in the FROM Clause (Derived Tables)


3. Subquery in the SELECT Clause (Scalar
Subqueries)
5. Subqueries in INSERT, UPDATE, and DELETE
Statements

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

13. Query Optimization and Performance Tuning


Practical exercises in optimizing SQL queries
14. Data Control Language (DCL) and Security
Practical exercises in optimizing SQL queries
● Grant
● Revoke

15 FINAL PROJECT
INSTITUTE OF BUSINESS MANAGEMENT
COLLEGE OF COMPUTER SCIENCE & INFORMATION SYSTEM
COMPUTER SCIENCE DEPARTMENT

RUBRICS GUIDELINE FOR SOFTWARE BASED LAB

Course Name (Course Code), ______________________Semester, Batch_____________

Name of Student: _______________________________ Roll No. __________________


Criteria Scor Exceeds Expectations Meets Expectations Developing Unsatisfactory
e (>=90%) (70%-89%) (50%-69%) (<50%)

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

Course Name (Course Code), ______________________Semester, Batch_____________

Name of Student: _______________________________ Roll No. __________________

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

Formula = (obtained marks/140) *25


Total lab manual marks 25
Preface

About the Manual:

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

DATABASE SETUP AND BASIC SQL

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.

MySQL installation Steps:


1.To download MySQL Installer, go to the following link
https://dev.mysql.com/downloads/installer/. There are two files are available. If you are
connecting to the internet while installing MySQL, you can choose the online installation
version mysql-installer-web-community.exe If you want to install MySQL offline, you can
download the mysql-installer-community.exe file.

2.After the download, open the installer.


3.It will ask for permission; when it does, click Yes. The installer will then open. Now, it will
ask to choose the setup type. Here, select Custom.

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.

9. Set your MySQL Root password and click on next.

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.

DATA DEFINITION LANGUAGE (DDL)


DDL refers to Data Definition Language, a subset of SQL statements that change the
structure of the database schema in some way, typically by creating, deleting, or modifying
schema objects such as databases, tables, and views.

CREATE:

Creates a new database, table, view of a table, or object in the database.


 CREATE DATABASE db_name;
 SHOW databases;
 USE db_name;

 CREATE TABLE tb_name(col1_name datatype(size), col2_name datatype(size));


 SHOW tables;
 DESCRIBE tb_name;

ALTER:

Modifies an existing database object such as a table.


 ALTER TABLE tb_name CHANGE old_col_name new_col_name datatype(size),
CHANGE old_col_name new_col_name datatype(size);
 ALTER TABLE tb_name MODIFY col_name datatype(size),
MODIFY col_name datatype(size)
 ALTER TABLE tb_name ADD col_name datatype(size), ADD col_name
datatype(size);
 ALTER TABLE tb_name DROP col_name, DROP col_name;
DROP:

Delete an entire database, table, view of a table, or object in the database.


 DROP DATABASE db_name;
 DROP TABLE tb_name;

RENAME:

Renames an object in the database.


 RENAME TABLE old_tb_name to new_tb_name;

TRUNCATE:

Removes all the records from a database table.


 TRUNCATE TABLE tb_name;

DATA MANIPULATION LANGUAGE (DML)


DML refers to Data Manipulation Language, a subset of SQL statements which deals with
data manipulation.

SELECT:

Retrieves (reads) data from the table.


 SELECT * FROM tb_name;

INSERT:

Adds data into the database table.


 INSERT INTO tb_name(field(s)_name) VALUES (field(s)_data);

UPDATE:

Updates an existing record in a table.


 UPDATE tb_name SET col1_name = col1_value, col2_name = col2_value,
WHERE col_name = col_value;

DELETE:

Deletes data from a table.


 DELETE FROM tb_name;
 DELETE FROM tb_name WHERE col_name = col_value;

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.

Teacher Signature: ________________________


Student Registration No: ________________________
LAB EXPERIMENT # 2

DATABASE DESIGN
Objectives:
1. Using CASE tool
2. Forward and Reverse Engineering

What is an Entity Relationship Diagram (ERD)?


An entity relationship diagram (ERD), also known as an entity relationship model, is a
graphical representation that depicts relationships among people, objects, places, concepts
or events within an information technology (IT) system. An ERD uses data
modeling techniques that can help define business processes and serve as the foundation
for a relational database.

How to Create a Simple ERD in MySQL Workbench?


In MySQL Workbench, you can create a type of file called a “model”. Within a model, you
can create one or more Entity Relationship Diagrams.
First, we’ll need to create a Model. To do this, go to File > New Model.
A new tab is shown at the top of the window called “MySQL Model”.

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

Diagrams, where EER stands for Enhanced Entity Relationship.

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

How to Forward Engineer a Database in MySQL Workbench:

We normally create a physical database from the ER diagram. First, we design and then
implement. This is called Forward Engineering.

To generate a script from a diagram in MySQL Workbench:

1. Select database > Forward Engineer


2. Set/review parameters for connecting to the DBMS then click Continue
3. Set/review options for DB to be created then click Continue
4. Select object to Forward engineer. Exclude any objects by deselecting them,
otherwise leave them as is, then click Continue
5. Review the generated SQL script in the "Output Preview" window. (Optionally,
customize the script by editing the SQL code directly in the "Output Preview"
window). Click on the "Next" or "Continue" button to proceed.
6. Click on the "Finish" or "Apply" button to complete the forward engineering process.

How to Reverse Engineer a Database in MySQL Workbench:

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

The EER diagram is now displayed on the screen.

Lab Assignment

Task 1: Database Design with MySQL Workbench


Creating an entity-relationship diagram (ERD) of the hospital management system using
MySQL Workbench. Establishing relationships between entities.

Task 2: Implementing Forward Engineering

Generate the SQL script from the designed database and verify the database structure in the
MySQL server.

Task 3: Implementing Reverse Engineering

Reverse engineering the database schema of your choice into an ERD. Modifying the ERD
and applying changes to the database.

Teacher Signature: ________________________


Student Registration No: ________________________
LAB EXPERIMENT # 3
SQL Queries (DQL)
Data Query Language (DQL):

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:

SELECT column_name AS SELECT employee_id AS ID, employee_name AS


alias_name Name

FROM table_name; FROM employees;

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:

SELECT t1.column_name, SELECT o.order_id, c.customer_name


t2.column_name FROM orders AS o
FROM table1 AS t1, table2 AS t2 JOIN customers AS c ON o.customer_id =
WHERE t1.column_name = c.customer_id;
t2.column_name;

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:

SELECT column_name1 + column_name2 SELECT quantity, price, quantity * price AS


AS sum_result total_sales

FROM table_name; FROM sales;

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

FROM table_name; FROM employees;

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.

Teacher Signature: ________________________


Student Registration No: ________________________
LAB EXPERIMENT # 4

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

This join is further divided into three categories:

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)).

3. Create a table named "Patients" with the following fields:


(PatientID (Primary Key, INT),

PatientName (VARCHAR(7)),

Age (INT),

Gender(VARCHAR(10)).

4. Create a table named "Appointments" with the following fields:


(AppointmentID (Primary Key, INT),

PatientID (INT) with a foreign key constraint referencing Patients(PatientID),

DoctorID (INT) with a foreign key constraint referencing Doctors(DoctorID),

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.

Teacher Signature: ________________________


Student Registration No: ________________________
LAB EXPERIMENT # 5

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.

TYPES OF SQL VIEWS


1. Simple View:
In MySQL, a view is a virtual table that is created as a result of a predefined query. It does
not store any data physically but rather displays data from one or more underlying tables.
Views can be used to simplify complex queries, restrict access to specific data, or provide a
tailored view of the data for different users.
Example:
Suppose you have two tables, `Employees` and `Departments`. You can create a view to
display the names and ages of employees from a specific department:
CREATE VIEW EmployeeDetails AS
SELECT e.Name, e.Age, d.DepartmentName
FROM Employees e
JOIN Departments d ON e.DepartmentID = d.DepartmentID;

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;

3. View with Check Option:


In MySQL, a view with a check option allows you to ensure that any modifications made
through the view satisfy the conditions specified in the view's definition. It prevents data
from being modified in a way that would cause the modified data to be excluded from the
result set of the view.
Example:
Suppose you have a table `Orders` and you want to create a view that only displays orders
with a specific status. You can create a view with the check option to enforce this condition:
CREATE VIEW ValidOrders AS
SELECT OrderID, OrderDate, Status
FROM Orders
WHERE Status = 'Valid'
WITH CHECK OPTION;
This will ensure that any modifications made through the view will adhere to the condition
`Status = 'Valid'`. Any attempts to modify data that would violate this condition will be
rejected.

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).

Teacher Signature: ________________________


Student Registration No: ________________________
LAB EXPERIMENT # 6

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

Row Level Built-in Functions:


Row Level Built-in Functions are functions that operate on individual rows of a result set.
They are applied to each row separately and can be used in the SELECT, WHERE, and ORDER
BY clauses. Now, let's look at specific categories of Row Level Built-in 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

SQL CLAUSES (OPEN ENDED LAB)


Q#1(a). Define the Clauses discussed in theory class.

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.

Your goal is to perform the following tasks:

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.

Teacher Signature: ________________________


Student Registration No: ________________________

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():

Returns the number of rows in a result set.


Example: SELECT COUNT(*) AS total_employees FROM employees;
2. SUM():

Returns the total sum of a numeric column.


Example: SELECT SUM(salary) AS total_salary FROM employees;
3. AVG():

Returns the average value of a numeric column.


Example: SELECT AVG(salary) AS average_salary FROM employees;
4. MIN():

Returns the minimum value in a column.


Example: SELECT MIN(salary) AS min_salary FROM employees;
5. MAX():

Returns the maximum value in a column.


Example: SELECT MAX(salary) AS max_salary FROM employees;

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.

Teacher Signature: ________________________


Student Registration No: ________________________
11.
LAB EXPERIMENT # 9

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.

1. Subquery in the WHERE Clause:


 Single-Row Subquery: A single-row subquery returns one value to be compared
with the outer query's condition. It is typically used with single-row operators such as
=, >, <, etc.

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);

2. Subquery in the FROM Clause (Derived Tables):


A subquery in the FROM clause is used to create a derived table. This derived table is
treated as a temporary table for the outer query and can be used for more complex queries.
Example:
SELECT department_name, AVG(salary) as avg_salary
FROM (SELECT department_id, department_name, salary FROM employees) AS emp_details
GROUP BY department_name;

3. Subquery in the SELECT Clause (Scalar Subqueries):


A subquery in the SELECT clause, also known as a scalar subquery, returns a single value that
can be used in the outer query's SELECT list.
Example:
SELECT employee_name, (SELECT AVG(salary) FROM employees) AS avg_salary
FROM employees;

4. Subqueries in INSERT, UPDATE, and DELETE Statements:


Subqueries can be used in conjunction with INSERT, UPDATE, and DELETE statements to
modify or retrieve data based on conditions from another table.
Examples:
 INSERT with Subquery:

INSERT INTO new_employees (employee_id, employee_name)


SELECT employee_id, employee_name
FROM old_employees
WHERE department = 'IT';
 UPDATE with Subquery:

UPDATE employees
SET salary = salary * 1.1
WHERE department_id IN (SELECT department_id FROM departments WHERE
department_name = 'Finance');
 DELETE with Subquery:

DELETE FROM employees


WHERE employee_id NOT IN (SELECT employee_id FROM assigned_projects);

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;

Timing (BEFORE vs. AFTER):


Triggers can be classified based on when they are executed with the triggering event. The
two main types are BEFORE triggers and AFTER triggers.
BEFORE Triggers: These triggers are executed before the triggering event occurs. They are
often used to modify the values being inserted or updated.
AFTER Triggers: These triggers are executed after the triggering event has occurred. They
are commonly used for validation, logging, or additional actions.

Event Types (INSERT, UPDATE, DELETE):


Triggers can be associated with one or more events: INSERT, UPDATE, and DELETE. Each
event type specifies when the trigger should be executed.

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

Teacher Signature: ________________________


Student Registration No: ________________________
LAB EXPERIMENT # 11

PROCEDURE AND FUNCTIONS (USER-


DEFINED)
A procedure in a database, often referred to as a stored procedure, is a precompiled
collection of one or more SQL statements that perform a specific task or set of tasks. It is
stored in the database and can be executed multiple times. Procedures are commonly used
to encapsulate and execute a sequence of SQL statements with a single call.

Creating and Using Stored Procedures:


A stored procedure is a set of SQL statements that can be stored in the database and
executed by calling the procedure name. They can have input parameters and can return
multiple values.

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 ;

2. Procedure with Parameters:


Procedures can accept input parameters for more dynamic behavior.

Example:
DELIMITER //
CREATE PROCEDURE GetEmployeeDetails(IN employee_id INT)
BEGIN
SELECT * FROM employees WHERE id = employee_id;
END //
DELIMITER ;

3. Procedure with Output Parameters:


You can use output parameters to return values from a procedure.

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 ;

4. Procedure with INOUT Parameters:


INOUT parameters allow passing values into the procedure and receiving modified values.

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.

Creating and Using Stored Functions:


A stored function is similar to a stored procedure but returns a single value. It can be used in
SQL queries and expressions.

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 ;

5. Stored Functions with Input Parameters:


Stored functions can accept input parameters for more dynamic behavior.

Example:
DELIMITER //
CREATE FUNCTION MultiplyNumbers(a INT, b INT) RETURNS INT
BEGIN
RETURN a * b;
END //
DELIMITER ;

6. Stored Functions with Output Parameters:


Stored functions can use output parameters to return values.

Example:
DELIMITER //
CREATE FUNCTION DivideNumbers(a INT, b INT, OUT result DECIMAL(10,2))
BEGIN
SET result = a / b;
END //
DELIMITER ;

Differences Between Procedure and Function


Procedure Functions
Stored procedures do not have a Stored functions must have a return type
mandatory return type. They can have specified using the RETURNS keyword and
output parameters but do not use the use the RETURN statement to return a
RETURN statement to return values. value.

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.

Teacher Signature: ________________________


Student Registration No: ________________________
LAB EXPERIMENT # 12
Data Transaction Language (DTL) and
Concurrency Control

Data Transaction Language (DTL):


Data Transaction Language (DTL) is a subset of SQL (Structured Query Language) that deals
specifically with the management and control of database transactions.
DTL includes commands that allow users to define the boundaries of a transaction, make
changes to the database, and control the finality of those changes.
Transaction: A transaction is a sequence of one or more SQL statements that are executed
as a single unit of work.
The transaction ensures the consistency and integrity of the database.

Savepoint, Commit, and Rollback:


1. Savepoint:
A SAVEPOINT is a point within a transaction to which you can later roll back.
It allows you to create a point of consistency within a transaction.
Savepoints are useful for dividing a transaction into smaller, more manageable parts.
Example:

-- 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?

Teacher Signature: ________________________


Student Registration No: ________________________
LAB EXPERIMENT # 13
QUERY OPTIMIZATION AND PERFORMANCE TUNING
Query Optimization:
Query optimization is the process of improving the performance of database queries by
selecting the most efficient execution plan. It involves various techniques to minimize query
execution time and resource consumption.
Goals: Reduce response time, utilize system resources efficiently, and enhance overall
database performance.
Techniques:
 Indexing: Properly index columns used in WHERE clauses and JOIN conditions.
 Query Rewriting: Modify queries to achieve the same results more efficiently.
 Use of Views: Create and use views to simplify complex queries.
 Proper Joins: Choose appropriate join types (INNER, LEFT, RIGHT) based on data
relationships.
 Subquery Optimization: Optimize subqueries for better performance.

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.

1. Understanding Query Execution Plans:


Efficient query optimization begins with a deep understanding of query execution plans. The
query optimizer's task is to determine the most effective way to retrieve data, considering
factors such as indexes, join methods, and filter conditions. For instance, a query involving
multiple tables might benefit from index usage or a different join strategy to minimize
execution time.
Example: Consider a scenario where a SELECT query retrieves data from two large tables. By
analyzing the execution plan, one may discover that creating a composite index on the join
columns significantly reduces the query execution time.

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.

3. Query Rewriting and Refactoring:


Sometimes, optimizing performance involves rewriting or refactoring queries. This may
include breaking down complex queries into simpler ones, eliminating redundant
operations, or reordering conditions for better efficiency.
Example: A poorly performing query retrieving sales data for a specific product range might
benefit from breaking it into two separate queries—one for basic information retrieval and
another for more detailed statistics.

4. Regular Maintenance and Monitoring:


Continuous monitoring and maintenance are critical for sustained performance. Regularly
analyzing query performance, identifying bottlenecks, and optimizing accordingly ensure
that the database system operates at peak efficiency over time.
Example: Monitoring tools can highlight queries that have suddenly become resource-
intensive, indicating the need for intervention. Regular index rebuilds and statistics updates
are also part of ongoing maintenance strategies.

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?

Teacher Signature: ________________________


Student Registration No: ________________________
LAB EXPERIMENT # 14
DATA CONTROL LANGUAGE (DCL) AND
SECURITY

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.

Key DCL Commands:


GRANT: Gives specific privileges to a user or a role.

-- Grant SELECT privilege on 'employees' table to user 'john'


GRANT SELECT ON employees TO john;

REVOKE: Removes specific privileges from a user or a role.

-- Revoke UPDATE privilege on 'products' table from user 'alice'


REVOKE UPDATE ON products FROM alice;

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';

Step 2: Verify Users


To check all users in MySQL, you can query the mysql.user table, which contains
information about all users and their privileges.

SELECT user, host FROM mysql.user;


This query will return a list of all users and their corresponding hosts.

If you want to see more detailed information about each user, you can use:

SELECT * FROM mysql.user;


This query returns all columns from the mysql.user table, providing detailed
information about each user, including their privileges.
Step 3: Grant Privileges
-- Grant SELECT privilege on 'employees' to 'john'
GRANT SELECT ON employees.* TO 'john'@'localhost';
OR
-- Grant ALL privileges on a database to user 'john'
GRANT ALL PRIVILEGES ON your_database.* TO 'john'@'%';
-- Grant INSERT, UPDATE, DELETE privileges on 'products' to 'alice'
GRANT INSERT, UPDATE, DELETE ON products.orders TO 'alice'@'localhost';

Step 4: Check Privileges

SHOW GRANTS FOR 'alice'@'localhost';


SHOW GRANTS FOR 'john'@'localhost';

Step 5: Revoke Privileges


-- Revoke SELECT privilege on 'employees' from 'john'
REVOKE SELECT ON employees FROM 'john'@'localhost';
-- Revoke all privilege on 'products.orders' from 'alice'
REVOKE all priviliges ON products.order FROM 'alice'@'localhost';
After executing the REVOKE statement, remember to run:
FLUSH PRIVILEGES;
This ensures that the changes take effect immediately.

Step 6: Reset password


To reset the password for a user in MySQL or MariaDB, you can use the SET
PASSWORD statement. Here's an example:

SET PASSWORD FOR 'alice'@'localhost' = 'new_password';


OR
ALTER USER 'alice'@'localhost' IDENTIFIED BY 'new_password';

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.

Teacher Signature: ________________________


Student Registration No: ________________________

You might also like