Professional Documents
Culture Documents
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:
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.
Once you have finalized the permissions that you want to set up for your new users,
always be sure to reload all the privileges.
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:
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:
Just as you can delete databases with DROP, you can use DROP to delete a user
altogether:
mysql> quit
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
3 rows in set (0.01 sec)
Since this is a new database, MySQL has nothing to show, and you will get a message
that says, “Empty set”
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))
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
Employees
Departments
Projects
Workson
Employeeid Numeric(9) Identifier of employee working on a project.
Foreign key referencing employees.employeeid
Deliverables:
A report should be prepared with AIM, Experiments, results and conclusion. (Not
more that 5 pages.
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
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.
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)
Exercise :
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
“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 //
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 //.
DELIMITER //
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, ...)
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)
Now try:
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.
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)
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:
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)
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)
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
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>
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.