You are on page 1of 30

DBMS

Semester IV
LAB Sheet - 1
Due Date for submitting report : 8th February 2021
1. Introduction:
MySQL is an open-source database management software that helps users store,
organize, and later retrieve data. It has a variety of options to grant specific users
nuanced permissions within the tables and databases—this tutorial will give a short
overview of a few of the many options.
How to Create a New User:
While logging from root user MySQL, it would have full access to all of the databases.
However, in cases where more restrictions may be required, there are ways to create
users with custom permissions. Initially log in from root user and we would be creating
a new-user from root. We can create user within the MySQL shell:

mysql> CREATE USER 'newuser'@'localhost' IDENTIFIED BY


'password';

At this point new-user has no permissions to do anything with the databases. In fact,
even if new-user tries to login (with the password, password), they will not be able to
reach the MySQL shell. Therefore, we would provide the user with access to the
information they will need. A strong password should be kept including upper case/
lower case and special character.

mysql> GRANT ALL PRIVILEGES ON * . * TO 'newuser'@'localhost';

Once you have finalized the permissions that you want to set up for your new users,
always be sure to reload all the privileges.

mysql> FLUSH PRIVILEGES;

1.2 How To Grant Different User Permissions

Here is a short list of other common possible permissions that users can enjoy.

1. ALL PRIVILEGES- as we saw previously, this would allow a MySQL user full
access to a designated database (or if no database is selected, global access
across the system)
2. CREATE- allows them to create new tables or databases
3. DROP- allows them to them to delete tables or databases
4. DELETE- allows them to delete rows from tables
5. INSERT- allows them to insert rows into tables
6. SELECT- allows them to use the SELECT command to read through databases
7. UPDATE- allow them to update table rows
8. GRANT OPTION- allows them to grant or remove other users’ privileges

1
To provide a specific user with a permission, you can use this framework:

mysql> GRANT type_of_permission ON database_name.table_name TO


'username'@'localhost';

Note: Each time you update or change a permission be sure to use the Flush Privileges
command.

If you need to revoke a permission, the structure is almost identical to granting it:

mysql> REVOKE type_of_permission ON database_name.table_name


FROM 'username'@'localhost';

You can review a user’s current permissions by running the following:

mysql> SHOW GRANTS FOR 'username'@'localhost';

Just as you can delete databases with DROP, you can use DROP to delete a user
altogether:

mysql> DROP USER 'username'@'localhost';

To test out your new user, log out by typing:

mysql> quit

and log back in with this command in terminal:

mysql -u [username] -p

Note:

1. All MySQL commands end with a semicolon; if the phrase does not end with a
semicolon, the command will not execute.
2. Also, although it is not required, MySQL commands are usually written in
uppercase and databases, tables, usernames, or text are in lowercase to make
them easier to distinguish. However, the MySQL command line is not case
sensitive.

2. How to Create and Delete a MySQL Database


MySQL organizes its information into databases; each one can hold tables with specific
data.
You can quickly check what databases are available by typing:
mysql> SHOW DATABASES;
+--------------------+
| Database |
+--------------------+
| information_schema |
| mysql |
| performance_schema |
+--------------------+

2
3 rows in set (0.01 sec)

Creating a database is very easy:


CREATE DATABASE database name;

How to Access a MySQL Database:


Once we have a new database, we can begin to fill it with information. The first step is to
create a new table within the larger database. Let’s open up the database we want to use:
USE events;
In the same way that you could check the available databases, you can also see an
overview of the tables that the database contains.
SHOW tables;

Since this is a new database, MySQL has nothing to show, and you will get a message
that says, “Empty set”

How to Create a MySQL Table

Let’s imagine that we are planning a get together of friends. We can use MySQL to track
the details of the event. Let’s create a new MySQL table:
CREATE TABLE student (PRN INT NOT NULL PRIMARY KEY AUTO_INCREMENT,
FirsName VARCHAR(20),
LastName VARCHAR(30),
Batch INT,
DoB DATE);

Show table:
mysql> SHOW TABLES;
+------------------+
| Tables_in_events |
+------------------+
| student |
+------------------+
1 row in set (0.01 sec)

We can remind ourselves about the table’s organization with this command:
mysql> DESCRIBE student;
+----------+-------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+----------+-------------+------+-----+---------+----------------+
| PRN | int | NO | PRI | NULL | auto_increment |
| FirsName | varchar(20) | YES | | NULL | |
| LastName | varchar(30) | YES | | NULL | |
| Batch | int | YES | | NULL | |
| DoB | date | YES | | NULL | |
+----------+-------------+------+-----+---------+----------------+
5 rows in set (0.00 sec)

3. Exercise :

3
Create the following tables (Don’t specify any constraints):
A. Category_details (category_id numeric (2), category_name varchar (30) )
B. Sub_category_details (sub_category_id numeric(2), category_id
numeric(2),sub_category_name varchar(30)
C. Product_details (Product_id numeric (6), category_id numeric(2),sub_category_id
numeric(2), product_name varchar(30))

Now perform the following operations:


1. Add a primary key constraint (without any constraint name) on column category_id
of category_details table.
2. Add a primary key constraint with a constraint name on column sub_category_id
of sub_category_details table.
3. Add a foreign key constraint with constraint name on column category_id of
sub_category_details table referencing category_id of category_details table.
4. For product_details table add primary key constraint on product_id. Also add
foreign key constraint on category_id and sub_category_id columns referencing
category_details(category_id) and sub_category_details (sub_category_id). Give
appropriate names for all constraints.
5. Add a new column (price numeric(2)) to product_details table
6. Modify the data type of price to numeric(6,2)
7. Insert four tuples in the table. (With valid data)
8. Drop the price column
9. Using the rules defined in the beginning, add a new column BRANDNAME
varchar(20) NOT NULL
10. Rename Category_details table to Cat_dt

Deliverables:
A report should be prepared with AIM, Experiments, results and conclusion. (Not
more that 5 pages.
1. Draw the Schema diagram for the problem statement.
2. Paste the snaps of each of the table and enter some details for respect
tables.

4
DBMS
Semester IV
LAB Sheet - 2
Due Date for submitting report : 15th February 2021

More On Insert, update deleted table


Exercise Case study:
The Employees Database stores information about a business, including employees,
departments, and projects. Each employee works for one department and is assigned
many projects. Each department has many employees, has many projects, and may be
a subdepartment of one department (e.g., Accounting is a subdepartment of
Administration). Each project is assigned to one department and is worked on by many
employees.

Employees

EmployeeID Numeric(9) Unique employee identifier ( Primary Key)

Firstname Varchar(10) Employee first name

Lastname Varchar(20) Employee last name

Deptcode Char(5) Identifier of department the employee works for.

Foreign key referencing departments.code

Salary Numeric(9,2) Employee salary

Departments

Code Char(5) Unique Department Identifier


Name Varchar(30) Department name

Managerid Numeric(9) Identifier of employee who manages the


department. Foreign key referencing
employees.employeeid

Subdeptof Char(5) Code of department that includes this


department as one of its immediate
subdepartments. Foreign key referencing
departments.code

Projects

Projectid Char(8) Unique project identifier

Deptcode Char(5) Identifier of department managing this project.

Foreign key referencing departments.code

Description Varchar(200) Project description

Startdate Date Project start date

Stopdate Date Project stop date. NULL value indicates that


the project is ongoing

Revenue Numeric(12,2) Total project revenue

Workson
Employeeid Numeric(9) Identifier of employee working on a project.
Foreign key referencing employees.employeeid

Projectid Char(8) Identifier of project that employee is working on.


Foreign key referencing projects.projectid

Assignedtime Numeric(3,2) Percentage of time employee is assigned to


project

● Create department table, employee table in mySQL.


● Create project table with primary key
● Create workson table
● Create foreign keys between employees and department
● Create foreign keys between workson and employees
● Create foreign keys between projects and departments

Deliverables:
A report should be prepared with AIM, Experiments, results and conclusion. (Not
more that 5 pages.

1. Draw the Schema diagram for the problem statements.


2. Paste the snaps of each of the table and enter some details for respect
tables.
DBMS
Semester IV
LAB Sheet - 3
Due Date for submitting report : 22nd February 2021

Data Manipulation Language(DML)


DML is the short name of Data Manipulation Language which deals with data manipulation and
includes most common SQL statements such SELECT, INSERT, UPDATE, DELETE, etc., and
it is used to store, modify, retrieve, delete and update data in a database.
SELECT - retrieve data from a database
INSERT - insert data into a table
UPDATE - updates existing data within a table
DELETE - Delete all records from a database table

EXERCISES
❖ Write a single SQL query for each of the following based on employees
database(NOTE:- Use the same employee database created in Lab2)
The schema for the employee database is as shown below.
1. List the first and last names of all employees.
2. List all attributes of the projects with revenue greater than $40,000.
3. List the department codes of the projects with revenue between $100,000 and
$150,000.
4. List the project IDs for the projects that started on or before July 1, 2004.
5. List the names of the departments that are top level (i.e., not a sub department).
6. List the ID and descriptions of the projects under the departments with code ACCNT,
CNSLT, or HDWRE.
7. List all of the information about employees with last names that have exactly 8 characters and
end in 'ware'.
8. List the ID and last name of all employees who work for department ACTNG and make less
than $30,000.
9. List the “magical” projects that have not started (indicated by a start date in the future or
NULL) but are generating revenue.
10. List the IDs of the projects either from the ACTNG department or that are ongoing (i.e.,
NULL end date). Exclude any projects that have revenue of $50,000 or less.
11. List all employee names as one field called name.
12. List all the department codes assigned to a project. Remove all duplicates.
13. Find the project ID and duration of each project.
14. Find the project ID and duration of each project. If the project has not finished, report its
execution time as of now. [Hint: Getdate() gives current date]
15. For each completed project, find the project ID and average revenue per
day.
16. Find the years a project started. Remove duplicates.
17. Find the IDs of employees assigned to a project that is more than 20 hours per week. Write
three queries using 20, 40, and 60 hour work weeks.
18. For each employee assigned to a task, output the employee ID with the
following: ∙ 'part time' if assigned time is < 0.33
∙ 'split time' if assigned time is >= 0.33 and < 0.67
∙ 'full time' if assigned time is >= 0.67
19. We need to create a list of abbreviated project names. Each abbreviated name concatenates
the first three characters of the project description, a hyphen, and the department code. All
characters must be uppercase (e.g., EMP-ADMIN).
20. For each project, list the ID and year the project started. Order the results in ascending order
by year.
21. If every employee is given a 5% raise, find the last name and new salary of the employees
who will make more than $50,000.
22. For all the employees in the HDWRE department, list their ID, first name, last name, and
salary after a 10% raise. The salary column in the result should be named Next Year.
23. Create a neatly formatted directory of all employees, including their department code and
name. The list should be sorted first by department code, then by last name, then by first name.
24. Find the average salary for all employees.
25. Find the minimum and maximum project revenue for all active projects that make money.
26. Find the number of projects that are completed. You may not use a WHERE clause.
27. Find the number of projects that have been worked on or currently are being worked on by
an employee.
28. Find the last name of the employee whose last name is last in dictionary order.
29. Compute the employee salary standard deviation.
30. Calculate the salary cost for each department with employees that don’t have a last name
ending in “re” after giving everyone a 10% raise.

Deliverables:
A report should be prepared with AIM, Experiments, results and conclusion. (Not
more that 5 pages.
1. Snapshot of outputs- 5 questions.
2. Students with even PRN should paste snapshots(output) of even question
numbers(5 questions)
3. Students with odd PRN should paste snapshots(output) of odd question
numbers(5 questions)
DBMS
Semester IV
LAB Sheet - 4
Due Date for submitting report :1st March 2021

EXERCISE on restaurant database

Identify the referential integrity constraints from the schema.


EXERCISE
1. Find the ID of the vendor who supplies grape.
2. Find all of the ingredients from the fruit food group with an inventory greater
than 100
3. Display all the food groups from ingredients, in which ‘grape’ is not a member.
4. Find the ingredients, unit price supplied by ‘VGRUS’(vendor ID) order by unit
price(asc)
5. Find the date on which the last item was added.
6. Find the number of vendors each vendor referred, and only report the vendors referring
more than one.
7. Find the list of vendor representative first names that begin with ‘s’
8. Find all vendor names containing an ‘_’.
9. Find the name of all of the food items other than salads.
10. Find the ingredient ID, name, and unit of items not sold in pieces or strips.
11. Find the details of all vendors not referred by anyone.
12. Find the average and total price for all items
13. Find the total number of ingredient units in inventory
14. Find the store id and total sales from each store.
15. Find the number of nonbeverages sold at each store?
16. Find stores and store sales sorted by number items sold
17. Find the minimum and maximum unit price of all ingredients in each non-NULL food
group.The results are only reported for food groups with either two or more items or a
total inventory of more than 500 items.
18. Find all items from most to least expensive.

Deliverables:
A report should be prepared with AIM, Experiments, results and conclusion. (Not
more that 5 pages.
1. Snapshot of outputs- 5 questions.
2. Students with even PRN should paste snapshots(output) of even question
numbers(5 questions)
3. Students with odd PRN should paste snapshots(output) of odd question
numbers(5 questions)
DBMS
Semester IV
LAB Sheet - 5
Due Date for submitting report : 8th March 2021

Objective : to create view based on table(s) or view(s) and observe its behavior while
performing update operations on it.

Bakery dataset
The dataset contains information about one month worth of sales information for a small
bakery shop. The sales are made to known customers. The dataset contains
information about the customers, the assortments of baked goods offered for sale and
the purchases made.

The dataset consists of the following relations:

- customers : information about the bakery's customers


- products : information about the baked goods offered for sale by the bakery
- item_list : itemized receipt information for purchases
- receipts : general receipt information for purchases

Receipts stores information about individual receipts (purchases by customers). Each


purchase may contain from one to five items, regardless of whether any items
purchased are of the same kind (e.g., two "chocolate cakes" will be billed as two
separate items on the receipt). item_list contains itemized receipt information.

Individual relations have the following description.


Customers
Id: unique identifier of the customer
LastName: last name of the customer
FirstName: first name of the customer

Products
Id : unique identifier of the baked product
Flavor: flavor/type of the product (e.g., "chocolate", "lemon")
Food: category of the product (e.g., "cake", "tart")
Price: price (in dollars)
Item_list
Receipt : receipt number (see reciepts.RecieptNumber)
Ordinal : position of the purchased item on the receipts. (i.e., first purchased
item,second purchased item, etc...)
Item : identifier of the item purchased (see product.Id)

Receipts
ReceiptNumber : unique identifier of the receipt
Date : date of the purchase. The date is in DD-MM-YYY format,
CustomerId : id of the customer (see customers.Id)

Summary of Bakery database:

CUSTOMERS (cid , fname, lname)


PRODUCTS (pid, flavor, food, price)
RECEIPTS (rno, rdate, cid)
ITEM_LIST (rno, ordinal, item)

● Understand the database.


● Draw schema diagram for Bakery database.
● Create relations with appropriate data types and integrity constraints.
● Populate the database values using the Bakery.sql file.

Exercise :

Write the following using Sub-query:


1. Display the food details that is not purchased by any of customers.
2. Show the customer details who had placed more than 2 orders on the same date.
3. Display the products details that has been ordered maximum by the customers. (use
ALL)
4. Show the number of receipts that contain the product whose price is more than the
average price of its food type.
Write the following using JOIN: (Use sub-query if required)
5. Display the customer details along with receipt number and date for the receipts that
are dated on the last day of the receipt month.
6. Display the receipt number(s) and its total price for the receipt(s) that contain Twist
as one among five items. Include only the receipts with total price more than $25.
7. Display the details (customer details, receipt number, item) for the product that was
purchased by the least number of customers.
8. Display the customer details along with the receipt number who ordered all the
flavors of Meringue in the same receipt.
Write the following using Set Operations:
9. Display the product details of both Pie and Bear Claw.
10.Display the customers details who haven't placed any orders.
11. Display the food that has the same flavor as that of the common flavor between the
Meringue and Tart.
12. Create a view named Blue_Flavor, which display the product details (product id,
food, price) of Blueberry flavor.
13. Create a view named Cheap_Food, which display the details (product id, flavor,
food, price) of products with price lesser than $1. Ensure that, the price of these
food(s) should never rise above $1 through view.
14. Create a view called Hot_Food that show the product id and its quantity where the
same product is ordered more than once in the same receipt.
15. Create a view named Pie_Food that will display the details (customer lname, flavor,
receipt number and date, ordinal) who had ordered the Pie food with receipt details.
16. Create a view Cheap_View from Cheap_Food that shows only the product id, flavor
and food.

Deliverables:
A report should be prepared with AIM, Experiments, results and conclusion. (Not
more that 5 pages.
1. Snapshot of outputs- 5 questions.
2. Students with even PRN should paste snapshots(output) of even question
numbers(5 questions)
3. Students with odd PRN should paste snapshots(output) of odd question
numbers(5 questions)
4. ER Diagram of database
DBMS
Semester IV
LAB Sheet - 6
Due Date for submitting report : 12th April 2021

MySql Procedures

Stored Procedure in MySql:

“A stored routine is a set of SQL statements that can be stored in the server.”

A stored procedure (or, simply 'procedure') is a method to encapsulate repetitive tasks. They allow
variable declarations, flow control and other useful programming techniques.

Basic Syntax:

DELIMITER //

CREATE PROCEDURE `procedure_name` ([argument list])


...
COMMENT 'A procedure'
BEGIN
What to do – goes here
END//

Picking a Delimiter
The delimiter is the character or string of characters that you will use to tell the mySQL client that
you've finished typing in an SQL statement. For ages, the delimiter has always been a semicolon.
That, however, causes problems, because, in a stored procedure, one can have many statements,
and each must end with a semicolon (;). In this sheet we have used “//”.
Once you set a delimiter, you must end every query with the delimiter. For example, you may not
need to use a procedure for sometime, rather want to manipulate a table without-procedure
syntaxes (i.e. by using standard mysql queries), then still you must end your queries with //.

mysql> SELECT * FROM Employee;// [Enter]

How to Work with a Stored Procedure


Instruction: Create a database for today's practice.
mysql> DROP DATABASE IF EXISTS PROC;
mysql> CREATE DATABASE PROC;
Query OK, 1 row affected (0.00 sec)
mysql> USE PROC;
Database changed
Do not work with BANK database. (Anyway, it does not matter; you can drop the full database
and create a new one and then again load the bank.sql).

Let see how a procedure looks like.

DELIMITER //

CREATE PROCEDURE `p1` ()


LANGUAGE SQL
DETERMINISTIC
SQL SECURITY DEFINER
COMMENT 'A procedure'
BEGIN
SELECT 'Hello World !';
END//

The first part of the statement creates the procedure. The next clauses defines the optional
characteristics of the procedure. Then you have the name and finally the body or routine code.
Stored procedure names are case insensitive, and you cannot create procedures with the same
name. Inside a procedure body, you can't put database-manipulation statements.
The four characteristics of a procedure are:
Language : For portability purposes; the default value is SQL.
Deterministic : If the procedure always returns the same results, given the same input.
This is for replication and logging purposes. The default value is NOT
DETERMINISTIC.
SQL Security : At call time, check privileges of the user. INVOKER is the user who
calls the procedure. DEFINER is the creator of the procedure. The default value is
DEFINER.
Comment : For documentation purposes; the default value is "".

Calling a procedure:
To call a procedure, you only need to enter the word CALL, followed by the name of the procedure,
and then the parentheses, including all the parameters between them (variables or values).
Parentheses are compulsory.
CALL stored_procedure_name (param1, param2, ...)

CALL procedure1(10 , 'string parameter' , @parameter_var);

What is this @ symbol and when to use it?

The @variable syntax in MySQL denotes a user-defined session variable. You can set these user
variables outside a stored procedure, but you can also set them inside a stored procedure, and the
effect is that the variable retains the value after your procedure call returns.

Example:
mysql> CREATE DATABASE PROC;
Query OK, 1 row affected (0.00 sec)
mysql> USE PROC;
Database changed
mysql> CREATE TABLE Employee(ID INT, Name VARCHAR(40));
Query OK, 0 rows affected (0.08 sec)

mysql> DESC Employee;


+-------+-------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------+-------------+------+-----+---------+-------+
| ID | int(11) | YES | | NULL | |
| Name | varchar(40) | YES | | NULL | |
+-------+-------------+------+-----+---------+-------+
2 rows in set (0.00 sec)

Try the following:


mysql> DELIMITER //
mysql> CREATE PROCEDURE emp_count_2() BEGIN SELECT COUNT(*) INTO
@empCount FROM Employee; END;//
Query OK, 0 rows affected (0.00 sec)
mysql> CALL emp_count_2();
-> //
Query OK, 1 row affected (0.00 sec)

mysql> SELECT @empcount;//


+-----------+
| @empcount |
+-----------+
| 0 |
+-----------+
1 row in set (0.00 sec)

mysql> INSERT INTO Employee VALUES((1, 'aaaa'),(2,'bbbb'), (3,


'cccc'), (4, 'dddd'), (5, 'eeee'));
-> //
ERROR 1241 (21000): Operand should contain 1 column(s)
mysql> INSERT INTO Employee VALUES (1, 'aaaa'),(2,'bbbb'), (3,
'cccc'), (4, 'dddd'), (5, 'eeee');//
Query OK, 5 rows affected (0.03 sec)
Records: 5 Duplicates: 0 Warnings: 0

Now try:

mysql> CALL emp_count_2();


-> //
Query OK, 1 row affected (0.00 sec)

mysql> SELECT @empcount;//


+-----------+
| @empcount |
+-----------+
| 5 |
+-----------+
1 row in set (0.00 sec)

It's okay for multiple sessions to set the user variable in this way concurrently, because user
variables are scoped to a single session, and concurrent sessions may have variables of the same
name, but with different values.
The variable syntax with no @ prefix is for variables local to the procedure, either procedure
parameters, or else local variables declared with DECLARE within the procedure body.
This usage you have, passing a user variable as a parameter and assigning it in the body of the
procedure, is useful if you want to call a procedure several times and store the result in separate
user variables. Otherwise each call to the procedure would overwrite the previous value in the
@empCount user variable for the current session.

Modifying a stored procedure:


MySQL provides an ALTER PROCEDURE statement to modify a routine, but only allows for
the ability to change certain characteristics. If you need to alter the body or the parameters, you
must drop and recreate the procedure.

Drop a stored procedure:


mysql> DROP PROCEDURE IF EXISTS emp_count_2;//
Query OK, 0 rows affected (0.00 sec)

This is a simple command. The IF EXISTS clause prevents an error in case the procedure does
not exist.

Parameters:
Let's examine how you can define parameters within a stored procedure.
CREATE PROCEDURE proc1 () : Parameter list is empty
CREATE PROCEDURE proc1 (IN varname DATA-TYPE) : One input parameter. The
word IN is optional because parameters are IN (input) by default.
CREATE PROCEDURE proc1 (OUT varname DATA-TYPE) : One output parameter.
(No examples given here)
CREATE PROCEDURE proc1 (INOUT varname DATA-TYPE) : One parameter which
is both input and output. (No examples given here)
Of course, you can define multiple parameters defined with different types.
IN
mysql> DELIMITER //
mysql> CREATE PROCEDURE `proc_IN` (IN var1 INT)
-> BEGIN
-> SELECT var1 + 2 AS result;
-> END//
Query OK, 0 rows affected (0.00 sec)

mysql> call proc_IN(5);


-> //
+--------+
| result |
+--------+
| 7 |
+--------+
1 row in set (0.00 sec)

Variables:
The following step will teach you how to define variables, and store values inside a procedure.
You must declare them explicitly at the start of the BEGIN/END block, along with their data types.
Once you've declared a variable, you can use it anywhere that you could use a session variable, or
literal, or column name.
Declare a variable using the following syntax:
DECLARE varname DATA-TYPE DEFAULT defaultvalue;

IF statement:

mysql> CREATE PROCEDURE `proc_IF` (IN param1 INT)


-> BEGIN
-> DECLARE variable1 INT;
-> SET variable1 = param1 + 1;
->
-> IF variable1 = 0 THEN
-> SELECT variable1;
-> END IF;
->
-> IF param1 = 0 THEN
-> SELECT 'Parameter value = 0';
-> ELSE
-> SELECT 'Parameter value <> 0';
-> END IF;
-> END //
mysql> call proc_IF(50) ;//
+----------------------+
| Parameter value <> 0 |
+----------------------+
| Parameter value <> 0 |
+----------------------+
1 row in set (0.00 sec)

Query OK, 0 rows affected (0.00 sec)

mysql> call proc_IF(0) ;//


+---------------------+
| Parameter value = 0 |
+---------------------+
| Parameter value = 0 |
+---------------------+
1 row in set (0.00 sec)

Query OK, 0 rows affected (0.00 sec)


CASE statement
The CASE statement is another way to check conditions and take the appropriate path. It's an
excellent way to replace multiple IF statements. The statement can be written in two different
ways, providing great flexibility to handle multiple conditions.
mysql> DELIMITER //
mysql>
mysql> CREATE PROCEDURE `proc_CASE` (IN param1 INT)
-> BEGIN
-> DECLARE variable1 INT;
-> SET variable1 = param1 + 1;
->
-> CASE variable1
-> WHEN 0 THEN
-> INSERT INTO table1 VALUES (param1);
-> WHEN 1 THEN
-> INSERT INTO table1 VALUES (variable1);
-> ELSE
-> INSERT INTO table1 VALUES (99);
-> END CASE;
->
-> END //
Query OK, 0 rows affected (0.00 sec)

mysql> CREATE TABLE table1 ( id INT);


-> //
Query OK, 0 rows affected (0.09 sec)

mysql> call proc_CASE(0);


-> //
Query OK, 1 row affected (0.05 sec)
mysql> SELECT * FROM table1;
-> //
+------+
| id |
+------+
| 1 |
+------+
1 row in set (0.00 sec)

Or,
mysql> DROP PROCEDURE IF EXISTS proc_CASE;
-> //
Query OK, 0 rows affected (0.00 sec)

mysql> DELIMITER //
mysql>
mysql> CREATE PROCEDURE `proc_CASE` (IN param1 INT)
-> BEGIN
-> DECLARE variable1 INT;
-> SET variable1 = param1 + 1;
->
-> CASE
-> WHEN variable1 = 0 THEN
-> INSERT INTO table1 VALUES (param1);
-> WHEN variable1 = 1 THEN
-> INSERT INTO table1 VALUES (variable1);
-> ELSE
-> INSERT INTO table1 VALUES (99);
-> END CASE;
->
-> END //
Query OK, 0 rows affected (0.00 sec)

mysql> call proc_CASE(0);


-> //
Query OK, 1 row affected (0.05 sec)

mysql> SELECT * FROM table1;//


+------+
| id |
+------+
| 1 |
| 1 |
+------+
2 rows in set (0.00 sec)

WHILE statement
There are technically three standard loops: WHILE loops, LOOP loops, and REPEAT loops.
You also have the option of creating a loop using the “Darth Vader” of programming techniques:
the GOTO statement.

mysql> DELIMITER //
mysql>
mysql> CREATE PROCEDURE `proc_WHILE` (IN param1 INT)
-> BEGIN
-> DECLARE variable1, variable2 INT;
-> SET variable1 = 0;
->
-> WHILE variable1 < param1 DO
-> INSERT INTO table1 VALUES (param1);
-> SELECT COUNT(*) INTO variable2 FROM table1;
-> SET variable1 = variable1 + 1;
-> END WHILE;
-> END //
Query OK, 0 rows affected (0.02 sec)

mysql> call proc_WHILE(5);//


Query OK, 1 row affected (0.18 sec)

mysql> SELECT * FROM table1;


-> //
+------+
| id |
+------+
| 1 |
| 1 |
| 5 |
| 5 |
| 5 |
| 5 |
| 5 |
+------+
7 rows in set (0.00 sec)

Exercise :
(1) Write a mysql procedure to check whether a number is odd or even.
(2) Write a mysql procedure to find out the factorial of a number.
(3) Write a mysql procedure to find out the leap year.
(4) Write a mysql procedure to count the number of employees with following conditions
:(you can use database from lab3)

- MIN_SALARY > 10000


- MIN_SALARY < 10000

- MIN_SALARY = 10000

Deliverables:
A report should be prepared with AIM, Experiments, results and conclusion. (Not
more that 5 pages.

1. Paste the snaps of each of the output and enter some details for respective
output.
DBMS
Semester IV
LAB Sheet - 7
Due Date for submitting report : 19th April 2021

TRANSACTIONS
❖ Databases are all about sharing data, so it is common for multiple users to be accessing
and even changing the same data at the same time. The simultaneous execution of
operations is called concurrency. Sometimes concurrency can get us into trouble if our
changes require multiple SQL statements. In general, if two or more users access the
same data and one or more of the statements changes the data, we have a conflict. This
is a classic problem in database systems; it is called the isolation or serializability
problem. If the users perform multiple steps, conflicts can cause incorrect results to
occur. To deal with this problem, databases allow the grouping of a sequence of SQL
statements into an indivisible unit of work called a transaction. A transaction ends with
either a commit or a rollback:
o commit—A commit permanently stores all of the changes performed by the
transaction. o rollback—A rollback removes all of the updates performed by the
transaction, no matter how many rows have been changed. A rollback can be
executed either by the DBMS to prevent incorrect actions or explicitly by the user.

❖ The DBMS provides the following guarantees for a transaction, called the ACID
properties: Atomicity, consistency, Isolation, and durability. These properties will be
covered in the course at detail.
❖ SQL starts a transaction automatically when a new statement is executed if there is no
currently active transaction. This means that a new transaction begins automatically with
the first statement after the end of the previous transaction or the beginning of the session.
❖ A user may explicitly start a transaction using the START TRANSACTION statement.
SET TRANSACTION NAME <string>;

❖ Commit:
SET TRANSACTION NAME ‘t1’;
UPDATE vrs SET inventory = inventory + 10;
SELECT * FROM vrs;
COMMIT;
SELECT * FROM vrs;
❖ Rollback:
SET TRANSACTION NAME ‘t2’;
UPDATE vrs SET inventory = inventory -20;
SELECT * FROM vrs;
ROLLBACK;
SELECT * FROM vrs;

❖ Here note that without using start transaction, if you execute the update query alone, the
values are automatically committed. There is no way to revert back.

SAVEPOINTS
❖ SQL allows you to create named placeholders, called savepoints, in the sequence of
statements in a transaction. You can rollback to a savepoint instead of to the beginning
of the transaction. Only the changes made after the savepoint are undone. To set a
savepoint, use the SAVEPOINT command:
SAVEPOINT <savepoint name>

❖ If we create a savepoint, we can rollback to that savepoint with the


following: ROLLBACK TO SAVEPOINT <savepoint name>

❖ Executing ROLLBACK without designating a savepoint or executing a COMMIT deletes


all savepoints back to the start of the transaction. A rollback to a particular savepoint
deletes all intervening savepoints.

UPDATE vrs SET inventory = inventory + 25;


SELECT * FROM vrs;
SAVEPOINT spoint1;
UPDATE vrs SET inventory = inventory - 15;
SELECT * FROM vrs;
SAVEPOINT spoint2;
UPDATE vrs SET inventory = inventory + 30;
SELECT * FROM vrs;
SAVEPOINT spoint3;
ROLLBACK TO SAVEPOINT spoint1;
SELECT * FROM vrs;

EXERCISES ON EMPLOYEES DATABASE:


❖ Write a queries for each of the following based on employee database created in the
previous labs. The scheme for employee database is shown below.
1. Begin the transaction using the START TRANSACTION statement.Then, select
maximum income among the employee.Use the COMMIT statement to
complete the transaction.

2. Delete those records of employees whose first_name starts from ‘Y’ from the employee
table and then COMMIT the changes in the database.

3. Delete those records of employees whose last_name starts from ‘B’ from the employee
table and then ROLLBACK the changes in the database by keeping Savepoints.
.
4. Using a transaction, delete the Administration department and all of its sub departments.

Deliverables:
A report should be prepared with AIM, Experiments, results and conclusion. (Not
more that 5 pages.

1. Paste the snaps of each of the output and enter some details for respective
output.

You might also like