Sunteți pe pagina 1din 105

CSE 253 DBMS LAB MANUAL 2018-19

Introduction to MySQL
MySQL is an open source database management software that helps users store, organize, and
retrieve data. It is a very powerful program with a lot of flexibility.

How to Install MySQL on Ubuntu:


Ubuntu: Execute the following command.

sudo apt-get install mysql-server

We can access the MySQL shell by typing the following command into terminal:

mysql -u root -p

After entering the root MySQL password into the prompt , you will be able to start building your
MySQL database.

A MySQL database server contains many databases (or schemas). Each database consists of one
or more tables. A table is made up of columns (or fields) and rows (records).
The SQL keywords and commands are NOT case-sensitive. For clarity, they are shown in
uppercase. The names or identifiers (database names, table names, column names, etc.) are case-
sensitive in some systems, but not in other systems. Hence, it is best to treat identifiers as case-
sensitive.
SHOW DATABASES;
You can use SHOW DATABASES to list all the existing databases in the server.

mysql> SHOW DATABASES;


+--------------------+
| Database |
+--------------------+
| information_schema |
| mysql |
| performance_schema |
| test |
........

Department of CS&E, SOE, PRESIDENCY UNIVERSITY 1


CSE 253 DBMS LAB MANUAL 2018-19

The databases "mysql", "information_schema" and "performance_schema" are system databases


used internally by MySQL.

Summary of MYSQL commands:

Database-Level:
DROP DATABASE databaseName -- Delete the database (irrecoverable!)
DROP DATABASE IF EXISTS databaseName -- Delete if it exists
CREATE DATABASE databaseName -- Create a new database
CREATE DATABASE IF NOT EXISTS databaseName -- Create only if it does not exists
SHOW DATABASES -- Show all the databases in this server
USE databaseName -- Set the default (current) database
SELECT DATABASE() -- Show the default database
SHOW CREATE DATABASE databaseName -- Show the CREATE DATABASE
statement

Table-Level:
DROP TABLE [IF EXISTS] tableName, ...
CREATE TABLE [IF NOT EXISTS] tableName (
columnName columnType columnAttribute, ...
PRIMARY KEY(columnName),
FOREIGN KEY (columnNmae) REFERENCES tableName (columnNmae)
)
SHOW TABLES -- Show all the tables in the default database
DESCRIBE|DESC tableName -- Describe the details for a table
ALTER TABLE tableName ... -- Modify a table, e.g., ADD COLUMN and DROP COLUMN
ALTER TABLE tableName ADD columnDefinition
ALTER TABLE tableName DROP columnName
ALTER TABLE tableName ADD FOREIGN KEY (columnNmae) REFERENCES tableName
(columnNmae)
ALTER TABLE tableName DROP FOREIGN KEY constraintName

Department of CS&E, SOE, PRESIDENCY UNIVERSITY 2


CSE 253 DBMS LAB MANUAL 2018-19

SHOW CREATE TABLE tableName -- Show the CREATE TABLE statement for this
tableName

Row-Level:
INSERT INTO tableName VALUES (column1Value, column2Value,...) -- Insert on all
Columns
INSERT INTO tableName VALUES (column1Value, column2Value,...), ... -- Insert
multiple rows
INSERT INTO tableName (column1Name, ..., columnNName) VALUES (column1Value, ...,
columnNValue) -- Insert on selected Columns
DELETE FROM tableName WHERE criteria
UPDATE tableName SET columnName = expr, ... WHERE criteria
SELECT * | column1Name AS alias1, ..., columnNName AS aliasN
FROM tableName

Department of CS&E, SOE, PRESIDENCY UNIVERSITY 3


CSE 253 DBMS LAB MANUAL 2018-19

Experiment No.1 : To Study and Implement Data Definition Language


Commands
Data Definition Language:
Syntax:
CREATE TABLE table_name
(Column_name datatype[(size)],
Column_name datatype[(size)],
)
Example:
CREATE TABLE STUDENT
(SNUM VARCHAR(10),
SNAME VARCHAR(20),
MAJOR VARCHAR(20),
LEVEL VARCHAR(10),
DOB DATE);
• Creates a table with five columns
Data Types in SQL:
Following below are the broad categories of data types exist in most databases:
• String Data
• Numeric Data
• Temporal Data
• Large Objects

i) String Data Types:


a).Fixed Length:
Occupies the same length of space in memory no matter how much data is stored in them.
Syntax:
char(n) where n is the length of the String

Department of CS&E, SOE, PRESIDENCY UNIVERSITY 4


CSE 253 DBMS LAB MANUAL 2018-19

e.g. name char(50)


If the variable stored for name is ‘Presidency’ the extra 40 fields are padded with blanks
b).Variable Length string is specified with maximum length of characters possible in the
string, however, the allocation is sized to the size of the data stored in memory.
Syntax:
Varchar(n) – n is the maximum length of data possible for the type
There may be a restriction in the maximum length of the data that you can specify in the
declaration which will vary according to the database.
All character data has to be enclosed in single quotes during specification
ii). Numeric Data Types:

• Store all the data related to purely numeric data.

• Some numeric data may also be stored as a character field e.g. zip codes
• Common Numeric Types:
Decimal :Floating point number
Float: Floating point number
Integer(size):Integer of specified length
Money: A number which contains exactly two digits after the decimal point
Number:A standard number field that can hold a floating point data.

iii). Temporal Data Types:


• These represent the dates and time:
• Three basic types are supported:
• Dates
• Times
• Date-Time Combinations
• MySQL comes with the following data types for storing a date or a date/time value in the
database:
• DATE - format YYYY-MM-DD
• DATETIME - format: YYYY-MM-DD HH:MI:SS

Department of CS&E, SOE, PRESIDENCY UNIVERSITY 5


CSE 253 DBMS LAB MANUAL 2018-19

• TIMESTAMP - format: YYYY-MM-DD HH:MI:SS


• YEAR - format YYYY or YY
iv). Large Data Objects:
• These are used for storing data objects like files and images:
• There are two types:
• Character Large Objects (clobs)
• Binary Large Objects (blobs)

1. To create a new database called STUDENTDB


mysql> CREATE DATABASE STUDENTDB;
Query OK, 1 row affected (0.12 sec)

2. To display the databases;


mysql> SHOW DATABASES;
+--------------------+
| Database |
+--------------------+
| information_schema |
| mysql |
| performance_schema |
| studentdb |
| test |
+--------------------+
5 rows in set (0.02 sec)

3. To use the created database STUDENTDB


mysql> USE STUDENTDB;

Department of CS&E, SOE, PRESIDENCY UNIVERSITY 6


CSE 253 DBMS LAB MANUAL 2018-19

Database changed

mysql> CREATE TABLE STUDENT(


-> SNUM INT PRIMARY KEY,
-> SNAME VARCHAR(20) NOT NULL,
-> MAJOR VARCHAR(5) NOT NULL,
-> LEVEL CHAR(5),
-> DOB DATE);
Query OK, 0 rows affected (0.13 sec)

4. To display/view all the tables in the STUDENTDB database.


mysql> SHOW TABLES;
+---------------------+
| Tables_in_studentdb |
+---------------------+
| student |
+---------------------+
1 row in set (0.00 sec)

5. To display the table description/schema/intension/structure of the database


mysql> DESC STUDENT;
+-------+-------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------+-------------+------+-----+---------+-------+
| SNUM | int(11)| NO | PRI | NULL | |
| SNAME | varchar(20) | NO | | NULL | |
| MAJOR | varchar(5) | NO | | NULL | |
| LEVEL | char(5) | YES | | NULL | |

Department of CS&E, SOE, PRESIDENCY UNIVERSITY 7


CSE 253 DBMS LAB MANUAL 2018-19

| DOB | date | YES | | NULL | |


+-------+-------------+------+-----+---------+-------+
5 rows in set (0.08 sec)

6. To add a new column called “SEM” to the existing table STUDENT and whose default
value is “4”

mysql> ALTER TABLE STUDENT ADD SEM INT DEFAULT 4;


Query OK, 0 rows affected (0.27 sec)
Records: 0 Duplicates: 0 Warnings: 0

mysql> DESC STUDENT;


+-------+-------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------+-------------+------+-----+---------+-------+
| SNUM | int(11) | NO | PRI | NULL | |
| SNAME | varchar(20) | NO | | NULL | |
| MAJOR | varchar(5) | NO | | NULL | |
| LEVEL | char(5) | YES | | NULL | |
| DOB | date | YES | | NULL | |
| SEM | int(11) | YES | |4 | |
+-------+-------------+------+-----+---------+-------+
6 rows in set (0.13 sec)

7. To modify the definition of a column of the existing table STUDENT

mysql> ALTER TABLE STUDENT MODIFY MAJOR VARCHAR(20) NULL;


Query OK, 0 rows affected (0.27 sec)
Records: 0 Duplicates: 0 Warnings: 0

Department of CS&E, SOE, PRESIDENCY UNIVERSITY 8


CSE 253 DBMS LAB MANUAL 2018-19

mysql> DESC STUDENT;


+-------+-------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------+-------------+------+-----+---------+-------+
| SNUM | int(11) | NO | PRI | NULL | |
| SNAME | varchar(20) | NO | | NULL | |
| MAJOR | varchar(20) | YES | | NULL | |
| LEVEL | char(5) | YES | | NULL | |
| DOB | date | YES | | NULL | |
| SEM | int(11) | YES | |4 | |
+-------+-------------+------+-----+---------+-------+
6 rows in set (0.03 sec)

8. To make other column as primary key(unique) in an existing table STUDENT


mysql> ALTER TABLE STUDENT MODIFY SNAME VARCHAR(20) UNIQUE;
Query OK, 0 rows affected (0.22 sec)
Records: 0 Duplicates: 0 Warnings: 0

mysql> DESC STUDENT;


+-------+-------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------+-------------+------+-----+---------+-------+
| SNUM | int(11) | NO | PRI | NULL | |
| SNAME | varchar(20) | YES | UNIQUE | NULL | |
| MAJOR | varchar(20) | YES | | NULL | |
| LEVEL | char(5) | YES | | NULL | |
| DOB | date | YES | | NULL | |
| SEM | int(11) | YES | |4 | |

Department of CS&E, SOE, PRESIDENCY UNIVERSITY 9


CSE 253 DBMS LAB MANUAL 2018-19

+-------+-------------+------+-----+---------+-------+

9. To drop a column in an already created table.

mysql> ALTER TABLE STUDENT DROP COLUMN LEVEL;


Query OK, 0 rows affected (0.20 sec)
Records: 0 Duplicates: 0 Warnings: 0

mysql> DESC STUDENT;


+-------+-------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------+-------------+------+-----+---------+-------+
| SNUM | int(11) | NO | PRI | NULL | |
| SNAME | varchar(20) | YES | UNI | NULL | |
| MAJOR | varchar(20) | YES | | NULL | |
| DOB | date | YES | | NULL | |
| SEM | int(11) | YES | |4 | |
+-------+-------------+------+-----+---------+-------+
5 rows in set (0.03 sec)

10. Truncating the tables.


Syntax:
Truncate table <tablename>;
mysql> TRUNCATE TABLE ENROLL1;
Query OK, 0 rows affected (0.11 sec)

11. To delete the definition/schema/description/structure of a table.


Syntax:
Drop table <tablename>;

Department of CS&E, SOE, PRESIDENCY UNIVERSITY 10


CSE 253 DBMS LAB MANUAL 2018-19

Example:
mysql> DROP TABLE ENROLL1;
Query OK, 0 rows affected (0.08 sec)

Department of CS&E, SOE, PRESIDENCY UNIVERSITY 11


CSE 253 DBMS LAB MANUAL 2018-19

Experiment No.2: To Study and Implement Data Manipulation Language


commands:
Data Manipulation Language:
i)Insert Statement:
Allows you to add new records to the Table
Syntax:
insert into table_name[(column_list)] values (value_list)
Example:
INSERT INTO student VALUES (1, ‘Ganesh’, ‘CSE’, ‘JR’, ’2000-05-01’)
INSERT INTO Student (snum, sname, major, level, DOB) VALUES (2, ‘ramesh’, ‘CSE’, ‘SR’,
’2000-07-31’))
• Note1: If the columns are not specified as in the first example the data goes in the order
specified in the table
• Note2: There are two ways of inserting Null values
1. If the field has a default value of Null, you can use an Insert statement that ignores the
column where the value is to be Null.
2. You can specify the column in the column list specification and assign a value of Null
to the corresponding value field.

ii)Delete Statement:
It is used to remove records from a table of the database. The where clause in the syntax is used
to restrict the rows deleted from the table otherwise all the rows from the table are deleted.
Syntax: DELETE FROM table_name [WHERE Condition]
Example:
DELETE FROM STUDENT
WHERE SNAME = ‘Ramesh’
• Deletes all the rows where the sname is ‘Ramesh’ keeps all the other rows.

iii) Update Statement:

Department of CS&E, SOE, PRESIDENCY UNIVERSITY 12


CSE 253 DBMS LAB MANUAL 2018-19

It is used to make changes to existing rows of the table. It has three parts. First, you ,must specify
which table is going to be updated. The second part of the statement is the set clause, in which
you should specify the columns that will be updated as well as the values that will be inserted.
Finally, the where clause is used to specify which rows will be updated.
Syntax:
UPDATE table_name
SET column_name1 = value1, column_name2 = value2, …..
[WHERE Condition]
Example:
UPDATE STUDENT SET SNAME = ‘Vignesh’, MAJOR = ‘IS’
WHERE snum = 1;

1. Inserting Data into Tables: - once a table is created the most natural thing to do is load this
table with data to be manipulated later.
Syntax:
i)insert into <tablename> (<col1>,<col2>) values(<exp>,<exp>);
mysql> INSERT INTO STUDENT(SNUM,SNAME,MAJOR,DOB,SEM) VALUES
(1001,'CHETHAN','CSE','2000-05-03',4);
Query OK, 1 row affected (0.07 sec)

ii) insert into <tablename> values(<exp>,<exp>);


mysql> INSERT INTO STUDEN VALUES (1002,'KIRAN','CSE','2000-05-03',4);
Query OK, 1 row affected (0.07 sec)

2. Delete operations.

i) To remove all rows of a table


Syntax: delete from <tablename>;
mysql> DELETE FROM STUDENT;
Query OK, 1 row affected (0.09 sec)

Department of CS&E, SOE, PRESIDENCY UNIVERSITY 13


CSE 253 DBMS LAB MANUAL 2018-19

ii) removal of a specified row/s


mysql> DELETE FROM STUDENT WHERE SNUM=1001;
Query OK, 1 row affected (0.10 sec)

3. Updating the contents of a table.


i) updating all rows
Syntax: Update <tablename> set <col>=<exp>,<col>=<exp>;
Before updating the snapshot of Student Table
mysql> SELECT * FROM STUDENT;
+------+----------------+-------+------------+------+
| SNUM | SNAME | MAJOR | DOB | SEM |
+------+----------------+-------+------------+------+
| 1001 | CHETHAN | CSE | 2000-11-03 | 4 |
| 1002 | CHETHAN CHAVAN | CSE | 2000-11-03 | 4 |
+------+----------------+-------+------------+------+
2 rows in set (0.00 sec)

mysql> UPDATE STUDENT SET MAJOR='ISE';


Query OK, 2 rows affected (0.07 sec)
Rows matched: 2 Changed: 2 Warnings: 0
After updating the snapshot of Student Table
mysql> SELECT * FROM STUDENT;
+------+----------------+-------+------------+------+
| SNUM | SNAME | MAJOR | DOB | SEM |
+------+----------------+-------+------------+------+
| 1001 | CHETHAN | ISE | 2000-11-03 | 4 |
| 1002 | CHETHAN CHAVAN | ISE | 2000-11-03 | 4 |
+------+----------------+-------+------------+------+

Department of CS&E, SOE, PRESIDENCY UNIVERSITY 14


CSE 253 DBMS LAB MANUAL 2018-19

2 rows in set (0.00 sec)

ii) updating seleted records.


Syntax: Update <tablename> set <col>=<exp>, <col>=<exp> where <condition>;
mysql> UPDATE STUDENT SET MAJOR='ECE' WHERE SNUM=1001;
Query OK, 1 row affected (0.07 sec)
Rows matched: 1 Changed: 1 Warnings: 0

Department of CS&E, SOE, PRESIDENCY UNIVERSITY 15


CSE 253 DBMS LAB MANUAL 2018-19

Experiment No.3: To Study and Implement SQL Constraints

Types of Constraints in SQL


• NOT NULL - Ensures that a column cannot have a NULL value
• UNIQUE - Ensures that all values in a column are different
• PRIMARY KEY - A combination of a NOT NULL and UNIQUE. Uniquely identifies
each row in a table
• FOREIGN KEY - Uniquely identifies a row/record in another table
• CHECK - Ensures that all values in a column satisfies a specific condition
• DEFAULT - Sets a default value for a column when no value is specified

1. To create a new table Faculty with FID auto_increment constraint

mysql> CREATE TABLE FACULTY


-> ( FID INT PRIMARY KEY AUTO_INCREMENT,
-> FNAME VARCHAR(20) NOT NULL,
-> ADDRESS VARCHAR(20),
-> DEPTID INT);
Query OK, 0 rows affected (0.13 sec)

mysql> DESC FACULTY;


+---------+-------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+---------+-------------+------+-----+---------+----------------+
| FID | int(11) | NO | PRI | NULL | auto_increment |
| FNAME | varchar(20) | NO | | NULL | |
| ADDRESS | varchar(20) | YES | | NULL | |
| DEPTID | int(11) | YES | | NULL | |

Department of CS&E, SOE, PRESIDENCY UNIVERSITY 16


CSE 253 DBMS LAB MANUAL 2018-19

+---------+-------------+------+-----+---------+----------------+
4 rows in set (0.03 sec)

2. To create a relationship table called COURSE with ON DELETE CASCADE


Referential Integrity Constraint.
mysql> CREATE TABLE COURSE (
-> CNAME VARCHAR(10) PRIMARY KEY,
-> MEETS_AT VARCHAR(10),
-> ROOM VARCHAR(5),
-> FID INTEGER,
-> FOREIGN KEY(FID) REFERENCES FACULTY(FID) ON DELETE CASCADE);
Query OK, 0 rows affected (0.13 sec)
mysql> DESC COURSE;
+----------+-------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+----------+-------------+------+-----+---------+-------+
| CNAME | varchar(10) | NO | PRI | NULL | |
| MEETS_AT | varchar(10) | YES | | NULL | |
| ROOM | varchar(5) | YES | | NULL | |
| FID | int(11) | YES | MUL | NULL | |
+----------+-------------+------+-----+---------+-------+
4 rows in set (0.03 sec)

3. To CREATE a Many to Many relationship table “ENROLL” between STUDENT and


COURSE relations with ON DELETE CASCADE

mysql> CREATE TABLE ENROLL(


-> SNUM INTEGER,CNAME VARCHAR(10),
-> PRIMARY KEY(SNUM,CNAME),

Department of CS&E, SOE, PRESIDENCY UNIVERSITY 17


CSE 253 DBMS LAB MANUAL 2018-19

-> FOREIGN KEY(SNUM) REFERENCES STUDENT(SNUM) ON DELETE


CASCADE,
-> FOREIGN KEY(CNAME) REFERENCES COURSE(CNAME) ON DELETE
CASCADE);
Query OK, 0 rows affected (0.15 sec)

mysql> DESC ENROLL;


+-------+-------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------+-------------+------+-----+---------+-------+
| SNUM | int(11) | NO | PRI | 0 | |
| CNAME | varchar(10) | NO | PRI | | |
+-------+-------------+------+-----+---------+-------+
2 rows in set (0.03 sec)

4. To CREATE a Many to Many relationship table “ENROLL” between STUDENT and


COURSE relations with ON DELETE SET NULL ON UPDATE CASCADE

mysql> CREATE TABLE ENROLL1(


-> SNUM INTEGER,CNAME VARCHAR(10),
-> FOREIGN KEY (SNUM) REFERENCES STUDENT(SNUM) ON DELETE SET NULL
ON UPDATE CASCADE,
-> FOREIGN KEY (CNAME) REFERENCES COURSE(CNAME) ON DELETE SET
NULL ON UPDATE CASCADE);
Query OK, 0 rows affected (0.14 sec)
mysql> DESC ENROLL1;
+-------+-------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------+-------------+------+-----+---------+-------+
| SNUM | int(11) | YES | MUL | NULL | |

Department of CS&E, SOE, PRESIDENCY UNIVERSITY 18


CSE 253 DBMS LAB MANUAL 2018-19

| CNAME | varchar(10) | YES | MUL | NULL | |


+-------+-------------+------+-----+---------+-------+
2 rows in set (0.04 sec)

i)Entity Integrity Constraint: Primary Key Value cannot be NULL and duplicate.
mysql> INSERT INTO STUDENT VALUES (NULL,'CHETHAN','CSE','2000-20-03',4);
ERROR 1048 (23000): Column 'SNUM' cannot be null.
mysql> INSERT INTO STUDENT(SNUM,SNAME,MAJOR,DOB,SEM) VALUES
(1001,'CHETHAN','CSE','2000-05-03',4);
ERROR 1062 (23000): Duplicate entry '1001' for key 'PRIMARY'.

ii)DOMAIN Constraint: incorrect date format(‘YYYY-MM-DD’)


mysql> INSERT INTO STUDENT VALUES (1002,'CHETHAN','CSE','2000-20-03',4);
ERROR 1292 (22007): Incorrect date value: '2000-20-03' for column 'DOB' at row 1
mysql> INSERT INTO COURSE VALUES('PYTHON','10:05','DGL0123',123);
ERROR 1406 (22001): Data too long for column 'ROOM' at row 1

iii)Referential Integrity Constraint:


mysql> INSERT INTO COURSE VALUES('PYTHON','10:05','DGL01',123);
ERROR 1452 (23000): Cannot add or update a child row: a foreign key constraint fails
(`studentdb`.`course`, CONSTRAINT `course_ibfk_1` FOREIGN KEY (`FID`) REFERENCES
`faculty` (`FID`) ON DELETE CASCADE).

Department of CS&E, SOE, PRESIDENCY UNIVERSITY 19


CSE 253 DBMS LAB MANUAL 2018-19

Experiment No. 4: To study and implement SQL data retrieval using


SELECT, FROM and WHERE clause.
To retrieve information from a database we can query the databases. SQL SELECT statement is
used to select rows and columns from a database/relation
SELECT Command
This command can perform selection as well as projection.
Selection: This is the capability of SQL can return you the tuples form a relation with all the
attributes.
Projection:This is the capability of SQL to return only specific attributes in the relation.

Data Retrieval/Manipulation Commands:

Operators in SQL:
The following are the commonly used operators in SQL
Arithmetic Operators +, -, *, /
Relational Operators =, <, >, <=, >=, <>
Logical Operators OR, AND, NOT
Arithmetic operators are used to perform simple arithmetic operations.

Department of CS&E, SOE, PRESIDENCY UNIVERSITY 20


CSE 253 DBMS LAB MANUAL 2018-19

Relational Operators are used when two values are to be compared and
Logical operators are used to connect search conditions in the WHERE Clause in SQL.

SELECT Command:
SELECT count(*) AS “Total Number of Records” FROM student;
Display the total number of records with title as “Total Number of Records” i.e an alias

We can also use arithmetic operators in select statement, like


SELECT Roll_no, name, marks+20 FROM student;
SELECT name, (marks/500)*100 FROM student WHERE Roll_no > 103;

Eliminating Duplicate/Redundant data:

DISTINCT keyword is used to restrict the duplicate rows from the results of a SELECT
statement.
e.g. SELECT DISTINCT name FROM student;

Conditions based on a range


SQL provides a BETWEEN operator that defines a range of values that the column value must
fall for the condition to become true.
e.g. SELECT Roll_no, name FROM student WHERE Roll_no BETWENN 100 AND
103;
The above command displays Roll_no and name of those students whose Roll_no lies in the
range 100 to 103 (both 100 and 103 are included in the range).

Conditions based on Pattern


SQL provides two wild card characters that are used while comparing the strings with LIKE
operator.
percent ( % ) Matches any string
Underscore ( _ ) Matches any one character

e.g SELECT Roll_no, name, city FROM student WHERE Roll_no LIKE “%3”;

Department of CS&E, SOE, PRESIDENCY UNIVERSITY 21


CSE 253 DBMS LAB MANUAL 2018-19

displays those records where last digit of Roll_no is 3 and may have any number of characters in
front.
Illustration:
1. Viewing data in the tables: - once data has been inserted into a table, the next most logical
operation would be to view what has been inserted.
a) all rows and all columns
Syntax: Select <col> to <col n> from tablename;
mysql> SELECT * FROM STUDENT;
+------+----------------+-------+------------+------+
| SNUM | SNAME | MAJOR | DOB | SEM |
+------+----------------+-------+------------+------+
| 1001 | CHETHAN | ECE | 2000-11-03 | 4 |
| 1002 | CHETHAN CHAVAN | ISE | 2000-11-03 | 4 |
+------+----------------+-------+------------+------+
2 rows in set (0.00 sec)

2. Filtering table data: - while viewing data from a table, it is rare that all the data from table
will be required each time. Hence, sql must give us a method of filtering out data that is not
required data.
a) All columns and all rows:
Syntax: select <col1>,<col2> from <tablename>;
mysql> SELECT * FROM STUDENT;
+------+----------------+-------+------------+------+
| SNUM | SNAME | MAJOR | DOB | SEM |
+------+----------------+-------+------------+------+
| 1001 | CHETHAN | ECE | 2000-11-03 | 4 |
| 1002 | CHETHAN CHAVAN | ISE | 2000-11-03 | 4 |
+------+----------------+-------+------------+------+
2 rows in set (0.00 sec)

Department of CS&E, SOE, PRESIDENCY UNIVERSITY 22


CSE 253 DBMS LAB MANUAL 2018-19

b) selected rows and all columns:


Syntax:
select * from <tablename> where <condition>;

mysql> SELECT * FROM STUDENT WHERE SNUM=1001;


+------+---------+-------+------------+------+
| SNUM | SNAME | MAJOR | DOB | SEM |
+------+---------+-------+------------+------+
| 1001 | CHETHAN | ECE | 2000-11-03 | 4 |
+------+---------+-------+------------+------+
1 row in set (0.04 sec)
c) selected columns and selected rows
Syntax: select <col1>,<col2> from <tablename> where<condition>;
mysql> SELECT SNUM,SNAME FROM STUDENT WHERE SNUM=1001;
+------+---------+
| SNUM | SNAME |
+------+---------+
| 1001 | CHETHAN |
+------+---------+
1 row in set (0.00 sec)

Example: STUDENT Database:


TABLE CREATION:

mysql> CREATE TABLE STUDENT


(SNUM INTEGER PRIMARY KEY,
SNAME VARCHAR(10),
MAJOR VARCHAR(10),
LEVEL VARCHAR(10),
AGE INTEGER);

Department of CS&E, SOE, PRESIDENCY UNIVERSITY 23


CSE 253 DBMS LAB MANUAL 2018-19

mysql> CREATE TABLE FACULTY


(FID INTEGER PRIMARY KEY,
FNAME VARCHAR(10),
DEPTID INTEGER);

mysql> CREATE TABLE CLASS


(CNAME VARCHAR(10) PRIMARY KEY,
MEETS_AT VARCHAR(10), ROOM VARCHAR(5),
FID INTEGER, FOREIGN KEY (FID) REFERENCES FACULTY (FID) ON DELETE
CASCADE);

mysql> CREATE TABLE ENROLLED


(SNUM INTEGER, CNAME VARCHAR(10),
PRIMARY KEY(SNUM, CNAME),
FOREIGN KEY(SNUM) REFERENCES STUDENT (SNUM) ON DELETE CASCADE,
FOREIGN KEY(CNAME) REFERENCES CLASS (CNAME) ON DELETE CASCADE);

mysql> INSERT INTO STUDENT VALUES(101,'ABHI','CSE','JR',19);


mysql> INSERT INTO STUDENT VALUES(102,'ANIL','ISE','JR',18);
mysql> INSERT INTO STUDENT VALUES(103,'BHAVYA','ISE','SR',20);
mysql> INSERT INTO STUDENT VALUES(104,'CHETHAN','CSE','JR',19);
mysql> INSERT INTO STUDENT VALUES(105,'SURESH','MECH','JR',18);
mysql> INSERT INTO STUDENT VALUES(106,'JAYANTH','CSE','SR',20);

mysql> SELECT * FROM STUDENT;


+---------+-------------------+----------+-----------+------+
| SNUM | SNAME | MAJOR | LEVEL | AGE |
+-------- +-------------------+-----------+----------+------+
| 101 | ABHI | CSE | JR | 19 |
| 102 | ANIL | ISE | JR | 18 |
| 103 | BHAVYA | ISE | SR | 20 |
| 104 | CHETHAN | CSE | JR | 19 |
| 105 | SURESH | MECH | JR | 18 |
| 106 | JAYANTH | CSE | SR | 20 |
+--------+--------------------+-----------+---------+------+

mysql> INSERT INTO FACULTY VALUES(1001,'JAMES',41);


mysql> INSERT INTO FACULTY VALUES(1002,'SUNIL',42);
mysql> INSERT INTO FACULTY VALUES(1002,'SUKRUTH',43);

Department of CS&E, SOE, PRESIDENCY UNIVERSITY 24


CSE 253 DBMS LAB MANUAL 2018-19

mysql> INSERT INTO FACULTY VALUES(1003,'SUKRUTH',43);


mysql> INSERT INTO FACULTY VALUES(1004,'NARASIMHA',44);
mysql> INSERT INTO FACULTY VALUES(1005,'AFROZ',41);
mysql> INSERT INTO FACULTY VALUES(1006,'JOHN',42);
mysql> INSERT INTO FACULTY VALUES(1007,'AHMED',45);
mysql> INSERT INTO FACULTY VALUES(1008,'SUNITHA',46);
mysql> INSERT INTO FACULTY VALUES(1009,'SRIVINAY',42);

mysql> SELECT * FROM FACULTY;


+------+-------------------+-----------+
| FID | FNAME | DEPTID |
+------+-------------------+-----------+
| 1001 | JAMES | 41 |
| 1002 | SUNIL | 42 |
| 1003 | SUKRUTH | 43 |
| 1004 | NARASIMHA | 44 |
| 1005 | AFROZ | 41 |
| 1006 | JOHN | 42 |
| 1007 | AHMED | 45 |
| 1008 | SUNITHA | 46 |
| 1009 | SRIVINAY | 42 |
+------+------------------+-----------+
9 rows in set (0.00 sec)

mysql> INSERT INTO CLASS VALUES('4CSE1','9:00','NG01',1001);


mysql> INSERT INTO CLASS VALUES('4CSE2','10:00','NG02',1001);
mysql> INSERT INTO CLASS VALUES('4CSE3','11:15','NG03',1002);
mysql> INSERT INTO CLASS VALUES('4CSE4','12:10','NG04',1002);
mysql> INSERT INTO CLASS VALUES('4CSE5','1:05','NG05',1003);
mysql> INSERT INTO CLASS VALUES('4CSE6','1:05','NG06',1004);
mysql> INSERT INTO CLASS VALUES('4CSE7','2:05','KG01',1005);
mysql> INSERT INTO CLASS VALUES('4CSE8','3:00','KG02',1006);
mysql> INSERT INTO CLASS VALUES('4CSE9','9:00','KG03',1007);
mysql> INSERT INTO CLASS VALUES('4CSE10','10:00','KG04',1008);
mysql> INSERT INTO CLASS VALUES('4CSE11','10:00','KF04',1009);

mysql> INSERT INTO CLASS VALUES('4CSE12','10:00','KF03',1009);


mysql> SELECT * FROM CLASS;
+--------+----------+------+------+

Department of CS&E, SOE, PRESIDENCY UNIVERSITY 25


CSE 253 DBMS LAB MANUAL 2018-19

| CNAME | MEETS_AT | ROOM | FID |


+--------+----------+------+------+
| 4CSE1 | 9:00 | NG01 | 1001 |
| 4CSE10 | 10:00 | KG04 | 1008 |
| 4CSE11 | 10:00 | KF04 | 1009 |
| 4CSE12 | 10:00 | KF03 | 1009 |
| 4CSE2 | 10:00 | NG02 | 1001 |
| 4CSE3 | 11:15 | NG03 | 1002 |
| 4CSE4 | 12:10 | NG04 | 1002 |
| 4CSE5 | 1:05 | NG05 | 1003 |
| 4CSE6 | 1:05 | NG06 | 1004 |
| 4CSE7 | 2:05 | KG01 | 1005 |
| 4CSE8 | 3:00 | KG02 | 1006 |
| 4CSE9 | 9:00 | KG03 | 1007 |
+--------+----------+------+------+
12 rows in set (0.00 sec)

mysql> INSERT INTO ENROLLED VALUES(101,'4CSE1');


mysql> INSERT INTO ENROLLED VALUES(102,'4CSE2');
mysql> INSERT INTO ENROLLED VALUES(103,'4CSE3');
mysql> INSERT INTO ENROLLED VALUES(101,'4CSE4');
mysql> INSERT INTO ENROLLED VALUES(104,'4CSE5');
mysql> INSERT INTO ENROLLED VALUES(105,'4CSE5');
mysql> INSERT INTO ENROLLED VALUES(106,'4CSE5');

mysql> INSERT INTO ENROLLED VALUES(101,'4CSE6');


mysql> INSERT INTO ENROLLED VALUES(102,'4CSE7');
mysql> INSERT INTO ENROLLED VALUES(103,'4CSE8');
mysql> INSERT INTO ENROLLED VALUES(104,'4CSE9');
mysql> INSERT INTO ENROLLED VALUES(105,'4CSE10');
mysql> INSERT INTO ENROLLED VALUES(106,'4CSE11');
mysql> INSERT INTO ENROLLED VALUES(106,'4CSE12');
mysql> SELECT * FROM ENROLLED;
+------+---------------+
| SNUM | CNAME |
+------+---------------+
| 101 | 4CSE1 |
| 105 | 4CSE10 |
| 106 | 4CSE11 |
| 106 | 4CSE12 |
| 102 | 4CSE2 |
| 103 | 4CSE3 |
| 101 | 4CSE4 |

Department of CS&E, SOE, PRESIDENCY UNIVERSITY 26


CSE 253 DBMS LAB MANUAL 2018-19

| 104 | 4CSE5 |
| 105 | 4CSE5 |
| 106 | 4CSE5 |
| 101 | 4CSE6 |
| 102 | 4CSE7 |
| 103 | 4CSE8 |
| 104 | 4CSE9 |
+------+--------------+
14 ows in set (0.00 sec)

Basic Queries:
1. Add the columns 'Fees' & 'Email' to the STUDENT table with default value '30000' &
'someone@gmail.com'.

Department of CS&E, SOE, PRESIDENCY UNIVERSITY 27


CSE 253 DBMS LAB MANUAL 2018-19

2. Update the fees & email of students with different values.

3. Display the Average Fees of students department-wise.

Department of CS&E, SOE, PRESIDENCY UNIVERSITY 28


CSE 253 DBMS LAB MANUAL 2018-19

4. Find the names of students having fees between 25000 to 30000.

5. Find the names of students having domain 'gmail.com'

6. Display Names of students in CAPITAL Letters.

Department of CS&E, SOE, PRESIDENCY UNIVERSITY 29


CSE 253 DBMS LAB MANUAL 2018-19

7. Increase the fees of all students by 10%;

UPDATE STUDENT SET FEES=FEES*1.1;

Department of CS&E, SOE, PRESIDENCY UNIVERSITY 30


CSE 253 DBMS LAB MANUAL 2018-19

UPDATE STUDENT SET FEES=FEES-FEES/11;

SELECT SNUM, FEES AS OLD_FEE, FEES+2000 AS NEW_FEE FROM STUDENT;

Department of CS&E, SOE, PRESIDENCY UNIVERSITY 31


CSE 253 DBMS LAB MANUAL 2018-19

8.Display the details of the student whose email id is missing.(NULL)


SELECT * FROM STUDENT WHERE EMAILID IS NULL;

Other than NULL:


SELECT * FROM STUDENT WHERE EMAILID IS NOT NULL;

9.Display the details of the student whose student name starts with letter A.

10.Delete the first two records of a student table.

DELETE FORM STUDENT LIMIT 2;

Department of CS&E, SOE, PRESIDENCY UNIVERSITY 32


CSE 253 DBMS LAB MANUAL 2018-19

Note: Nestred and Complex Queries will be implemented in Experiment No.9

Department of CS&E, SOE, PRESIDENCY UNIVERSITY 33


CSE 253 DBMS LAB MANUAL 2018-19

Experiment No.5: To study and implement different SQL single row and
multiple row functions.
Functions available in SQL:
SQL provide large collection of inbuilt functions also called library functions that can be used
directly in SQL statements.
1. Mathematical functions
2. String functions
3. Date & Time functions
1.Mathematical functions:
Some of the commonly used mathematical functions are sum() avg(), count(), min(), max() etc.
Example: SELECT sum(marks) FROM student;
displays the sum of all the marks in the table student.
Example: SELECT min(Roll_no), max(marks) FROM student;
displays smallest Roll_no and highest marks in the table student.
2. String functions:
These functions are used to deal with the string type values like
ASCII, LOWEWR, UPPER, LENGTH,LEFT, RIGHT, TRIM, LTRIM, RTRIM etc.
ASCII : Returns the ASCII code value of a character (leftmost character of string).
Syntax: ASCII(character)
Example:

SELECT ASCII('a') returns 97

SELECT ASCII('A') returns 65

SELECT ASCII('1') returns 49

SELECT ASCII('ABC') returns 65

Note:
 For Upper character 'A' to 'Z' ASCII value 65 to 90
 For Lower character 'A' to 'Z' ASCII value 97 to 122
 For digit '0' to '9' ASCII value 48 to 57

Department of CS&E, SOE, PRESIDENCY UNIVERSITY 34


CSE 253 DBMS LAB MANUAL 2018-19

LOWER : Convert character strings data into lowercase.


Syntax: LOWER(string)
SELECT LOWER('STRING FUNCTION')
returns string function

UPPER : Convert character strings data into Uppercase.


Syntax: UPPER(string)
SELECT UPPER('string function')
returns STRING FUNCTION

LEN : Returns the length of the character string.


Syntax: LENGTH(string)
SELECT LENGTH('STRING FUNCTION')
returns 15

LEFT : Returns left part of a string with the specified number of characters counting from
left.LEFT function is used to retrieve portions of the string.
Syntax: LEFT(string,integer)
SELECT LEFT('STRING FUNCTION', 6)
returns STRING

REVERSE : Returns reverse of a input string.


Syntax: REVERSE(string)
SELECT REVERSE('STRING FUNCTION')
returns NOITCNUF GNIRTS

SUBSTRING : Returns part of a given string.


SELECT SUBSTRING('STRING FUNCTION', 1, 6)
returns STRING

Department of CS&E, SOE, PRESIDENCY UNIVERSITY 35


CSE 253 DBMS LAB MANUAL 2018-19

SELECT SUBSTRING('STRING FUNCTION', 8, 8)


returns FUNCTION
SELECT NOW();
Displays Current time and Date
mysql> select now();
+---------------------+
| now() |
+---------------------+
| 2019-03-12 13:36:31 |
+---------------------+
1 row in set (0.08 sec)

mysql> select sysdate();


+---------------------+
| sysdate() |
+---------------------+
| 2019-03-12 13:37:58 |
+---------------------+
1 row in set (0.06 sec)

Multi Row Functions:


Functions can manipulate group of rows to gibe one result per group of rows.These function are
called as group function.

Department of CS&E, SOE, PRESIDENCY UNIVERSITY 36


CSE 253 DBMS LAB MANUAL 2018-19

Experiment No.6: To study and implement aggregating Data using Group By


Clause, HAVING clause and sort data using Order By clause.
GROUP BY Clause
The GROUP BY clause can be used in a SELECT statement to collect data across multiple
records and group the results by one or more columns.
The syntax for the GROUP BY clause is:
SELECT column1,column2, ... column_n, aggregate_function (expression)
FROM tables
WHERE conditions
GROUP BY column1, column2, ... column_n;
Where
aggregate_function can be a function such as SUM, COUNT, MAX, MIN, AVG etc.
Example:

1. Display the Average Fees of students department-wise.


SELECT MAJOR,AVG(FEES)
FROM STUDENT
GROUP BY MAJOR;

HAVING Clause
The HAVING clause is used in combination with the GROUP BY clause. It can be used in a
SELECT statement to filter the records that a GROUP BY returns.
The syntax for the HAVING clause is:
SELECT column1, column2, ... column_n, aggregate_function (expression)
FROM tables
WHERE predicates
GROUP BY column1, column2, ... column_n
HAVING condition1 ... condition_n;

ORDER BY Clause

Department of CS&E, SOE, PRESIDENCY UNIVERSITY 37


CSE 253 DBMS LAB MANUAL 2018-19

ORDER BY clause is used to display the result of a query in a specific order(sorted order).
The sorting can be done in ascending or in descending order. It should be kept in mind that the
actual data in the database is not sorted but only the results of the query are displayed in sorted
order.
Example: SELECT name, city FROM student ORDER BY name;
The above query returns name and city columns of table student sorted by name in
increasing/ascending order.
Example: SELECT * FROM student ORDER BY city DESC;
It displays all the records of table student ordered by city in descending order.
Note:- If order is not specifies that by default the sorting will be performed in ascending
order.

Example of BANK Database:


CREATE ALL THE TABLES

BRANCH TABLE
CREATE TABLE BRANCH (BR_NAME VARCHAR(20) PRIMARY KEY, BR_CITY
VARCHAR(20), ASSETS REAL);

ACCOUNT TABLE
CREATE TABLE ACCOUNT (ACCNO INT PRIMARY KEY, BR_NAME VARCHAR(20),
BALANCE REAL, FOREIGN KEY (BR_NAME) REFERENCES BRANCH (BR_NAME) ON
DELETE CASCADE);

CUSTOMER TABLE
CREATE TABLE CUSTOMER (CUST_NAME VARCHAR(20) PRIMARY KEY,
CUST_STREET VARCHAR (20), CUST_CITY VARCHAR (20));

DEPOSITOR TABLE
CREATE TABLE DEPOSITOR (CUST_NAME VARCHAR (20), ACCNO INT, PRIMARY
KEY (CUST_NAME, ACCNO), FOREIGN KEY (CUST_NAME) REFERENCES
CUSTOMER (CUST_NAME) ON DELETE CASCADE, FOREIGN KEY (ACCNO)
REFERENCES ACCOUNT (ACCNO) ON DELETE CASCADE);

LOAN TABLE
CREATE TABLE LOAN (LOAN_NO INT PRIMARY KEY, BR_NAME VARCHAR (20),
AMOUNT REAL, FOREIGN KEY (BR_NAME) REFERENCES BRANCH (BR_NAME) ON
DELETE CASCADE);

BORROWER TABLE

Department of CS&E, SOE, PRESIDENCY UNIVERSITY 38


CSE 253 DBMS LAB MANUAL 2018-19

CREATE TABLE BORROWER (CUST_NAME VARCHAR (20), LOAN_NO INT,


PRIMARY KEY (CUST_NAME, LOAN_NO), FOREIGN KEY (CUST_NAME)
REFERENCES CUSTOMER (CUST_NAME) ON DELETE CASCADE, FOREIGN KEY
(LOAN_NO) REFERENCES LOAN (LOAN_NO) ON DELETE CASCADE);

INSERT INTO TABLES

INSERT INTO BRANCH VALUES


(‘KORMANGALA’ , ’BENGALURU’ , 20500.3),
(‘SADASHIVANAGAR’ , ’BENGALURU’ , 154329.5),
(‘VITTALNAGAR’ , ’HYDERABAD’ , 350000),
(‘KASTHURINAGAR’ , ’DELHI’ , 125000),
(‘MARUTINAGAR’ , ’HYDERABAD’ , 212351.6),
(‘RAJANKUNTE’ , ’MUMBAI’ , 53535.8);

INSERT INTO ACCOUNT VALUES


(123456 , ’KORMANGALA’ , 5000),
(123457 , ’SADASHIVANAGAR’ , 35000),
(123458 , ’VITTALNAGAR’ , 60000),
(123459 , ’KASTHURINAGAR’ , 255600),
(123460 , ’VITTALNAGAR’ , 37890),
(123461 , ’MARUTINAGAR’ , 20000),
(123462 , ’SADASHIVANAGAR’ , 40000);

INSERT INTO CUSTOMER VALUES


(‘KAVYA’ , ‘SADASHIVANAGAR’ , ‘BENGALURU’),
(‘ABHAY’ , ‘KAMALANAGAR’ , ‘TUMKUR’),
(‘SHEETAL’ , ‘KASTHURINAGAR’ , ‘BENGALURU’),
(‘KSHAMITHA’ , ‘MARUTILAYOUT’ , ‘TUMKUR’),
(‘LIKITH’ , ‘MADHURANAGAR’ , ‘HYDERABAD’),
(‘SACHIN’ , ‘VITTALNAGAR’ , ‘HYDERABAD’);

INSERT INTO DEPOSITOR VALUES


(‘KAVYA’ , 123457),
(‘ABHAY’ , 123456),
(‘KAVYA’ , 123456),
(‘KSHAMITHA’ , 123458),
(‘KSHAMITHA’ , 123460),
(‘LIKITH’ , 123461),
(‘KAVYA’ , 123462);

INSERT INTO LOAN VALUES


(231 , ’SADASHIVANAGAR’ , 50500.5),
(232 , ’VITTALNAGAR’ , 25000),
(233 , ’MARUTINAGAR’ , 60300.3),
(234 , ’KASTHURINAGAR’ , 45000.7),

Department of CS&E, SOE, PRESIDENCY UNIVERSITY 39


CSE 253 DBMS LAB MANUAL 2018-19

(235 , ’KORMANGALA’ , 25534);

INSERT INTO BORROWER VALUES


(‘KAVYA’ , 231),
(‘KSHAMITHA’ , 232),
(‘ABHAY’ , 235),
(‘LIKITH’ , 234),
(‘SACHITH’ , 233);

Write and Execute the SQL Queries for the following statements:
1. Find bank accounts with a balance greater than 20000

SELECT ACCNO,BALANCE
FROM ACCOUNT
WHERE BALANCE>20000;

2. Order results in increasing

SELECT ACCNO,BALANCE
FROM ACCOUNT
WHERE BALANCE>20000
ORDER BY BALANCE DESC;

3. Retrieve a list of all bank branch details, ordered by branch city, with each city’s branches
listed in reverse order of assets.

SELECT BR_NAME, BR_CITY, ASSETS


FROM BRANCH
ORDER BY BR_CITY, ASSETS DESC;

4. Find average balance of accounts at “Sadashivanagar” branch.

SELECT AVG(BALANCE)
FROM ACCOUNT WHERE BR_NAME= 'SADASHIVANAGAR';

5. Find the sum of total account balance of any branch.

SELECT branch_name, SUM(balance) AS total_bal


FROM account GROUP BY branch_name;

Note: Nestred and Complex Queries will be implemented in Experiment No.9

Department of CS&E, SOE, PRESIDENCY UNIVERSITY 40


CSE 253 DBMS LAB MANUAL 2018-19

Experiment No.7: To Study and Implement different types of Set Operation in


SQL.
SET OPERATIONS:
SQL has directly incorporated some set operations such as union operation (UNION), set
difference (MINUS) and intersection (INTERSECT) operations. The resulting relations of these
set operations are sets of tuples; duplicate tuples are eliminated from the result. The set
operations apply only to union compatible relations; the two relations must have the same
attributes and the attributes must appear in the same order

Illustration of all Set Operations:


CREATE TABLE DEPARTMENT(DEPT_ID INT PRIMARY KEY, DEPT_NAME
VARCHAR(20));
CREATE TABLE EMPLOYEE(EMP_ID INT PRIMARY KEY, EMP_NAME VARCHAR(20),
DEPT_NUM INT, FOREIGN KEY(DEPT_NUM) REFERENCES DEPARTMENT(DEPT_ID)
ON DELETE CASCADE);

INSERT INTO DEPARTMENT VALUES(1,'Accounting');


INSERT INTO DEPARTMENT VALUES(2,'SALES');
INSERT INTO DEPARTMENT VALUES(3,'Marketing');

INSERT INTO EMPLOYEE VALUES(1,'Alice',NULL);


INSERT INTO EMPLOYEE VALUES(2,'Bob',1);
INSERT INTO EMPLOYEE VALUES(3,'Charles',2);
INSERT INTO EMPLOYEE VALUES(4,'Dan',1);

Department of CS&E, SOE, PRESIDENCY UNIVERSITY 41


CSE 253 DBMS LAB MANUAL 2018-19

1.UNION OPERATION:
SELECT EMP_ID FROM EMPLOYEE
UNION
SELECT DEPT_ID FROM DEPARTMENT ORDER BY EMP_ID;
Output:

Department of CS&E, SOE, PRESIDENCY UNIVERSITY 42


CSE 253 DBMS LAB MANUAL 2018-19

2. INTERSECTION OPERATION
SELECT EMP_ID FROM
EMPLOYEE
WHERE EMP_ID IN(SELECT DEPT_ID FROM DEPARTMENT);

Output:

3.MINUS/DIFFERENCE OPEARATION:
SELECT EMP_ID
FROM EMPLOYEE
WHERE EMP_ID NOT IN(SELECT DEPT_ID FROM DEPARTMENT);

Department of CS&E, SOE, PRESIDENCY UNIVERSITY 43


CSE 253 DBMS LAB MANUAL 2018-19

4.CARTESIAN PRODUCT
select * from employee cross join department;

Department of CS&E, SOE, PRESIDENCY UNIVERSITY 44


CSE 253 DBMS LAB MANUAL 2018-19

Experiment No.8: To Study and Implement different types of Joins in SQL.

SQL JOIN
SQL Join is used to fetch data from two or more tables, which is joined to appear as single set of
data. It is used for combining column from two or more tables by using values common to both
tables.
JOIN Keyword is used in SQL queries for joining two or more tables. Minimum required
condition for joining table, is (n-1) where n, is number of tables. A table can also join to itself,
which is known as, Self Join.

Types of JOIN:
Following are the types of JOIN that we can use in SQL:

 Inner
 Outer
 Left
 Right

Cross JOIN or Cartesian Product


This type of JOIN returns the cartesian product of rows from the tables in Join. It will return a
table which consists of records which combines each row from the first table with each row of
the second table.
Cross JOIN Syntax is,
SELECT column-name-list
FROM
table-name1 CROSS JOIN table-name2;

INNER Join or EQUI Join


This is a simple JOIN in which the result is based on matched data as per the equality condition
specified in the SQL query.
Inner Join Syntax is,
SELECT column-name-list FROM
table-name1 INNER JOIN table-name2

Department of CS&E, SOE, PRESIDENCY UNIVERSITY 45


CSE 253 DBMS LAB MANUAL 2018-19

WHERE table-name1.column-name = table-name2.column-name;


Natural JOIN
Natural Join is a type of Inner join which is based on column having same name and same
datatype present in both the tables to be joined.
The syntax for Natural Join is,
SELECT * FROM
table-name1 NATURAL JOIN table-name2;

OUTER JOIN
Outer Join is based on both matched and unmatched data. Outer Joins subdivide further into,

1. Left Outer Join


2. Right Outer Join
3. Full Outer Join

LEFT Outer Join

The left outer join returns a resultset table with the matched data from the two tables and then
the remaining rows of the left table and null from the right table's columns.
Syntax for Left Outer Join is,
SELECT column-name-list FROM
table-name1 LEFT OUTER JOIN table-name2
ON table-name1.column-name = table-name2.column-name;

RIGHT Outer Join


The right outer join returns a resultset table with the matched data from the two tables being
joined, then the remaining rows of the right table and null for the remaining left table's columns.
Syntax for Right Outer Join is,
SELECT column-name-list FROM
table-name1 RIGHT OUTER JOIN table-name2
ON table-name1.column-name = table-name2.column-name;

Full Outer Join


The full outer join returns a resultset table with the matched data of two table then remaining
rows of both left table and then the right table.

Department of CS&E, SOE, PRESIDENCY UNIVERSITY 46


CSE 253 DBMS LAB MANUAL 2018-19

Syntax of Full Outer Join is,


SELECT column-name-list FROM
table-name1 FULL OUTER JOIN table-name2
ON table-name1.column-name = table-name2.column-name;
Illustration:
CREATE TABLE DEPARTMENT(DEPT_ID INT PRIMARY KEY, DEPT_NAME
VARCHAR(20));
CREATE TABLE EMPLOYEE(EMP_ID INT PRIMARY KEY, EMP_NAME VARCHAR(20),
DEPT_NUM INT, FOREIGN KEY(DEPT_NUM) REFERENCES DEPARTMENT(DEPT_ID)
ON DELETE CASCADE);

INSERT INTO DEPARTMENT VALUES(1,'Accounting');


INSERT INTO DEPARTMENT VALUES(2,'Sales');
INSERT INTO DEPARTMENT VALUES(3,'Marketing');

INSERT INTO EMPLOYEE VALUES(1,'Alice',NULL);


INSERT INTO EMPLOYEE VALUES(2,'Bob',1);
INSERT INTO EMPLOYEE VALUES(3,'Charles',2);
INSERT INTO EMPLOYEE VALUES(4,'Dan',1);

Department of CS&E, SOE, PRESIDENCY UNIVERSITY 47


CSE 253 DBMS LAB MANUAL 2018-19

1. EQUI JOIN OPERATION


SELECT EMP_NAME, DEPT_NAME
FROM EMPLOYEE E JOIN DEPARTMENT D ON E.DEPT_NUM=D.DEPT_ID;

2. JOIN WITH NOT EQUALITY OPERATOR(NON EQUI JOIN)


SELECT EMP_NAME, DEPT_NAME FROM EMPLOYEE E JOIN DEPARTMENT D ON
E.DEPT_NUM<>D.DEPT_ID;

Department of CS&E, SOE, PRESIDENCY UNIVERSITY 48


CSE 253 DBMS LAB MANUAL 2018-19

3. EQUI JOIN WITH SPECIFIED CONDITION


SELECT EMP_NAME, DEPT_NAME
FROM EMPLOYEE E JOIN DEPARTMENT D ON E.DEPT_NUM<>D.DEPT_ID WHERE
D.DEPT_NAME='MARKETING';

OUTER JOIN:
1. LEFT OUTER JOIN OR LEFT JOIN
SELECT *
FROM EMPLOYEE E LEFT JOIN DEPARTMENT D ON E.DEPT_NUM=D.DEPT_ID;

2. RIGHT OUTER JOIN OR RIGHT JOIN


SELECT * FROM
\EMPLOYEE E RIGHT JOIN DEPARTMENT D ON E.DEPT_NUM=D.DEPT_ID;

Department of CS&E, SOE, PRESIDENCY UNIVERSITY 49


CSE 253 DBMS LAB MANUAL 2018-19

3. COMBINATION OF SET AND JOIN OPERATIONS


SELECT *
FROM EMPLOYEE E LEFT JOIN DEPARTMENT D ON E.DEPT_NUM=D.DEPT_ID
UNION
SELECT *
FROM EMPLOYEE E RIGHT JOIN DEPARTMENT D ON E.DEPT_NUM=D.DEPT_ID;

4.NATURAL JOIN Operation:


NOTE: First rename the column
ALTER TABLE employee Change dept_num dept_id int;

Department of CS&E, SOE, PRESIDENCY UNIVERSITY 50


CSE 253 DBMS LAB MANUAL 2018-19

SELECT *
FROM DEPARTMENT NATURAL JOIN EMPLOYEE

Department of CS&E, SOE, PRESIDENCY UNIVERSITY 51


CSE 253 DBMS LAB MANUAL 2018-19

Experiment No.9: To study and implement Sub queries/Nested queries,


Correlated nested queries in SQL.
NESTING OF QUERIES

A complete SELECT query, called a nested query, can be specified within the WHERE-
clause of another query, called the outer query.
Syntax:
SELECT select_list
FROM table
WHERE expr operator
(SELECT select_list
FROM table);

Subqueries:
A subquery is a SELECT statement that is embedded in a clause of another SELECT statement.
They can be very useful when you need to select rows from a table with a condition that
depends on the data in the table itself.
You can place the subquery in a number of SQL clauses:
WHERE clause
HAVING clause
FROM clause

The comparison operator IN compares a value v with a set (or multi-set) of values V, and
evaluates to TRUE if v is one of the elements in V. The subquery (inner query) executes once
before the main query. The result of the subquery is used by the main query (outer query).

Single-Row Subqueries:
• Return only one row
• Use single-row comparison operators(=, >,<= ,>= ,< >)
Multiple-Row Subqueries:
• Return more than one row
• Use multiple-row comparison operators( IN, ANY, ALL)

Department of CS&E, SOE, PRESIDENCY UNIVERSITY 52


CSE 253 DBMS LAB MANUAL 2018-19

CORRELATED NESTED QUERIES:

If a condition in the WHERE-clause of a nested query references an attribute of a relation


declared in the outer query, the two queries are said to be correlated. The result of a
correlated nested query is different for each tuple (or combination of tuples) of the relation(s)
the outer query

An Example:
SCHEMA Diagram of Student Database:

Refer the database tables and values from experiment. No.5

1. Find the names of all Juniors (level = JR) who are enrolled in a Class taught by
Prof.Narasimha.

mysql> SELECT DISTINCT S.SNAME


-> FROM STUDENT S,CLASS C,ENROLLED E,FACULTY F
-> WHERE S.SNUM=E.SNUM AND E.CNAME=C.CNAME AND F.FID=C.FID

Department of CS&E, SOE, PRESIDENCY UNIVERSITY 53


CSE 253 DBMS LAB MANUAL 2018-19

-> AND F.FNAME='NARASIMHA' AND S.LEVEL='JR';

+----------+
| SNAME |
+----------+
| ABHI |
+----------+
1 row in set (0.00 sec)

2. Find the names of all Classes that either meet in room KG04 or have five or more
Students enrolled.
mysql> SELECT C.CNAME
-> FROM CLASS C
-> WHERE C.ROOM='KG04' OR C.CNAME IN
-> (SELECT E.CNAME
-> FROM ENROLLED E
-> GROUP BY E.CNAME
-> HAVING COUNT(*)>=5);
+------------+
| CNAME |
+------------+
| 4CSE10 |
+------------+
1 row in set (0.03 sec)

3. Find the names of all students who are enrolled in two classes that meet at the same time

mysql> SELECT DISTINCT S.*


-> FROM STUDENT S
-> WHERE S.SNUM IN
-> (SELECT E1.SNUM
-> FROM ENROLLED E1, ENROLLED E2, CLASS C1, CLASS C2
-> WHERE E1.SNUM = E2.SNUM AND E1.CNAME <> E2.CNAME AND
-> E1.CNAME = C1.CNAME AND E2.CNAME = C2.CNAME
-> AND C1.MEETS_AT = C2.MEETS_AT);
+---------+----------------+-----------+----------+------+
| SNUM | SNAME | MAJOR | LEVEL | AGE |
+---------+----------------+-----------+----------+------+
| 106 | JAYANTH | CSE | SR | 20 |
+---------+----------------+------------+----------+------+

Department of CS&E, SOE, PRESIDENCY UNIVERSITY 54


CSE 253 DBMS LAB MANUAL 2018-19

4. .Find the names of students enrolled in the maximum number of classes.


mysql> SELECT DISTINCT S.sname
-> FROM Student S
-> WHERE S.snum IN (SELECT E.snum
-> FROM Enrolled E
-> GROUP BY E.snum);
+---------------+
| sname |
+---------------+
| ABHI |
| ANIL |
| BHAVYA |
| CHETHAN |
| SURESH |
| JAYANTH |
+---------------+
6 rows in set (0.00 sec)

5. Find the names of faculty members for whom the combined enrolment of the courses
that they teach is less than five.

mysql> SELECT DISTINCT F.FNAME


-> FROM FACULTY F
-> WHERE F.FID IN
-> (SELECT C.FID FROM CLASS C, ENROLLED E
-> WHERE C.CNAME=E.CNAME
-> GROUP BY C.FID
-> HAVING COUNT(*)<5);

+--------------------+
| FNAME |
+--------------------+
| JAMES |
| SUNIL |
| SUKRUTH |
| NARASIMHA |
| AFROZ |
| JOHN |
| AHMED |
| SUNITHA |

Department of CS&E, SOE, PRESIDENCY UNIVERSITY 55


CSE 253 DBMS LAB MANUAL 2018-19

| SRIVINAY |
+-------------------+

Complex Queries from the BANK Database:

SCHEMA DIAGRAM:

SCHEMA DIAGRAM

BRANCH

BNAME CITY ASSETS

DEPOSITOR
ACCOUNT
CNAME ACCNO
ACCNO BNAME BALANCE

CUSTOMER

CNAME CSTREET CCITY

LOAN BORROWER

LNO BNAME AMOUNT CNAME LNO

1.Find the number of branches that currently DONT have loans.

SELECT COUNT(DISTINCT B.BR_NAME)


FROM BRANCH B, LOAN L
WHERE B.BR_NAME NOT IN(SELECT DISTINCT BR_NAME FROM LOAN );

Department of CS&E, SOE, PRESIDENCY UNIVERSITY 56


CSE 253 DBMS LAB MANUAL 2018-19

2.Find all the customers who have at least two accounts at the Main branch.

SELECT D.CUST_NAME
FROM DEPOSITOR D, ACCOUNT A
WHERE A.ACCNO=D.ACCNO AND A.BR_NAME= 'SADASHIVANAGAR'
GROUP BY D.CUST_NAME
HAVING COUNT (D.CUST_NAME) >=2;

3.Find all the customers who have an account at all the branches located in a specific city.

SELECT D.CUST_NAME
FROM BRANCH B, ACCOUNT A, DEPOSITOR D
WHERE B.BR_NAME=A.BR_NAME AND A.ACCNO=D.ACCNO AND
B.BR_CITY=‘BANGALORE’
GROUP BY D.CUST_NAME
HAVING COUNT (DISTINCT A.BR_NAME) =
(SELECT COUNT (*)
FROM BRANCH
WHERE BR_CITY=‘BANGALORE’);

4. Demonstrate how you delete all account tuples at every branch located in a specific city.

DELETE FROM ACCOUNT


WHERE BR_NAME IN
(SELECT BR_NAME
FROM BRANCH
WHERE BR_CITY= ‘HYDERABAD’);

Additional Queries to be executed:

1. Find all customers with more than one loan.


2. Find customers with an account but not a loan.
3. Find all cities with more than two customers living in the city.
4. Find the largest total account balance of any branch.

Department of CS&E, SOE, PRESIDENCY UNIVERSITY 57


CSE 253 DBMS LAB MANUAL 2018-19

Experiment 10: To Study and Implement Views in SQL

Views are relations, except that they are not physically stored.
Views are created for presenting different information to different users
A view is a “virtual table” or a “stored query” which takes the output of a query and treats it as a
table. The table upon which a view is created is called as base table.
A view is a logical table based on a table or another view. A view contains no data of its own but
is like a window through which data from tables can be viewed or changed. The tables on which
a view is based are called base tables.
The view is stored as a SELECT statement in the data dictionary

OBJECTIVE

 Views Helps to encapsulate complex query and make it reusable.


 Provides user security on each view - it depends on your data policy security.

SQL COMMANDS

Creating views:
Syntax:
Create view <view name>;
Description:
This command is used to create view by combining two tables.
Viewing single row of table:
Syntax:
Create view<view name> as select from <table name>;
Description:
This command is used to view a single row from a particular table.
Viewing all columns from a single table:
Syntax:
Create view<view name> as select * from <table name>;
Description :
This is used to create view which displays all columns from a single table.

Department of CS&E, SOE, PRESIDENCY UNIVERSITY 58


CSE 253 DBMS LAB MANUAL 2018-19

View specified column from a single table:


Syntax:
Create view<view table name> as select column1,column2 from <tablename>;
Description:
This command is used to create view which displays on a specified column from a single
table.
View specified column from a muliple table:
Syntax:
Create view<view table name> as select column1,column2,….columnn where ‘condition’;
Description:
This is used to create view to display specified columns from multiple tables.
View all column from a muliple table:

Syntax:
Create view<view table name> as select * from <table name> where ‘condition’;
Description:
This is used to create view which displays all the columns of a table.
Inserting into views:
Syntax:
Insert into <view name> values <’data1’,’data2’,……>;
Description:
This is used to do inserting of information or data into values.
Updating in view: is done by using query materialization and query modification.

Deleting a view:
Syntax:
Drop view <view name>;

Department of CS&E, SOE, PRESIDENCY UNIVERSITY 59


CSE 253 DBMS LAB MANUAL 2018-19

Illustration:
mysql> use studentdb;
Database changed
1.Create a simple view named as “Studentdetails”
Solution:
mysql> create view studentdetails as
-> select * from student;
Query OK, 0 rows affected (0.30 sec)
2.To retrieve all the data in the studentdetails view
Solution:

Query on a view.
3. Retieve the name and id student of ‘cse’ department(major).
mysql> select snum, sname from studentdetails where major='cse';
+------+-------+
| snum | SNAME |
+------+-------+
| 1003 | abhi |
| 1004 | aniv |
+------+-------+
2 rows in set (0.11 sec)

Department of CS&E, SOE, PRESIDENCY UNIVERSITY 60


CSE 253 DBMS LAB MANUAL 2018-19

Complex Views:

4.Writea Query view for each department retrieve the details like number of
students, major of the students.

Result of the query

5. Remove the view called studentdetails and studentcount

Department of CS&E, SOE, PRESIDENCY UNIVERSITY 61


CSE 253 DBMS LAB MANUAL 2018-19

Experiment No.11: To study and implement Functions and Procedures.

A stored procedure contains a sequence of SQL commands stored in the database catalog so that
it can be invoked later by a program
• Stored procedures are declared using the following syntax:
Create Procedure <proc-name>
(param_spec1, param_spec2, …, param_specn )
begin
-- execution code
end;
where each param_spec is of the form:
[in | out | inout] <param_name> <param_type>
• in mode: allows you to pass values into the procedure,
• out mode: allows you to pass value back from procedure to the calling program
An example consider the Employee and Department tables which are shown below.

Suppose we want to keep track of the total salaries of employees working for each
department

Department of CS&E, SOE, PRESIDENCY UNIVERSITY 62


CSE 253 DBMS LAB MANUAL 2018-19

Illustration Example:

Step 1: Change the delimiter (i.e., terminating character) of SQL statement from semicolon (;) to
something else (e.g., //) So that you can distinguish between the semicolon of the SQL
statements in the procedure and the terminating character of the procedure definition.

Example:

Step 2:

1. Define a procedure called updateSalary which takes as input a department number.


2. The body of the procedure is an SQL command to update the totalsalary column of the
deptsal table.
3. Terminate the procedure definition using the delimiter you had defined in step 1 (//)

Example:

Department of CS&E, SOE, PRESIDENCY UNIVERSITY 63


CSE 253 DBMS LAB MANUAL 2018-19

Step 3: Change the delimiter back to semicolon (;)

mysql> delimeter ;

Step 4: Call the procedure to update the totalsalary for each department

Example:

Step 5: Show the updated total salary in the deptsal table

• Use show procedure status to display the list of stored procedures you have created

Department of CS&E, SOE, PRESIDENCY UNIVERSITY 64


CSE 253 DBMS LAB MANUAL 2018-19

Stored Procedures in MySQL:

• You can declare variables in stored procedures


• You can use flow control statements (conditional IF-THEN-ELSE or loops such
as WHILE and REPEAT)
• MySQL also supports cursors in stored procedures.
• A cursor is used to iterate through a set of rows returned by a query so that we can
process each individual row.

Example using Cursors:

• The previous procedure updates one row in deptsal table based on input parameter
• Suppose we want to update all the rows in deptsal simultaneously
• First, let’s reset the totalsalary in deptsal to zero

Department of CS&E, SOE, PRESIDENCY UNIVERSITY 65


CSE 253 DBMS LAB MANUAL 2018-19

Department of CS&E, SOE, PRESIDENCY UNIVERSITY 66


CSE 253 DBMS LAB MANUAL 2018-19

An example illustration:

• Create a stored procedure to give a raise to all employees

Department of CS&E, SOE, PRESIDENCY UNIVERSITY 67


CSE 253 DBMS LAB MANUAL 2018-19

An Example:

Functions:

• Functions are declared using the following syntax:

Create function <function-name> (param_spec1, …, param_speck)


returns <return_type>
[not] deterministic
Begin
-- execution code
end;

where param_spec is:


[in | out | in out] <param_name> <param_type>

Department of CS&E, SOE, PRESIDENCY UNIVERSITY 68


CSE 253 DBMS LAB MANUAL 2018-19

Example of Functions:

Example of calling function in the SELECT clause:

Department of CS&E, SOE, PRESIDENCY UNIVERSITY 69


CSE 253 DBMS LAB MANUAL 2018-19

Experiment No.12: To study and implement SQL Triggers

To monitor a database and take a corrective action when a condition occurs

Triggers are nothing but the procedures/functions that involve actions and fired/executed
automatically whenever an event occurs such as an insert, delete, or update operation or pressing
a button or when mouse button is clicked.

Examples:
• Charge $10 overdraft fee if the balance of an account after a withdrawal
transaction is less than $500
• Limit the salary increase of an employee to no more than 5% raise
Syntax:

CREATE TRIGGER trigger-name


trigger-time trigger-event
ON table-name
FOR EACH ROW
trigger-action;
• trigger-time  {BEFORE, AFTER}
• trigger-event  {INSERT,DELETE,UPDATE}

SQL Triggers: An Example

Department of CS&E, SOE, PRESIDENCY UNIVERSITY 70


CSE 253 DBMS LAB MANUAL 2018-19

An example: We want to create a trigger to update the total salary of a department when a new
employee is hired

Problem Statemenet:

l Create a trigger to update the total salary of a department when a new employee is
hired:

The keyword “new” refers to the new row inserted

Department of CS&E, SOE, PRESIDENCY UNIVERSITY 71


CSE 253 DBMS LAB MANUAL 2018-19

2.Create a trigger to update the total salary of a department when an employee tuple is
modified:

Department of CS&E, SOE, PRESIDENCY UNIVERSITY 72


CSE 253 DBMS LAB MANUAL 2018-19

3.Create a trigger to update the total salary of a department when an employee tuple is
deleted:

SQL Triggers: An Example

Department of CS&E, SOE, PRESIDENCY UNIVERSITY 73


CSE 253 DBMS LAB MANUAL 2018-19

To list all the triggers you have created:

mysql> show triggers;

To drop a trigger or a trigger is no longer required.

mysql> drop trigger trigger_name;

Department of CS&E, SOE, PRESIDENCY UNIVERSITY 74


CSE 253 DBMS LAB MANUAL 2018-19

Experiment No. 13: Design and implementation of an AIRLINE database.


SCHEMA
• Flights (fno: integer, from: string, to: string, distance: integer, Departs: time, arrives:
time, price: real)
• Aircraft (aid: integer, aname: string, cruisingrange: integer)
• Certified (eid: integer, aid: integer)
• Employees (eid: integer, ename: string, salary: integer)
• Flys(eid:integer,fno:integer)

ER DIAGRAM

SCHEMA DIAGRAM

Department of CS&E, SOE, PRESIDENCY UNIVERSITY 75


CSE 253 DBMS LAB MANUAL 2018-19

CREATE ALL THE TABLES

FLIGHTS TABLE
CREATE TABLE FLIGHTS (FNO INT PRIMARY KEY, F_FROM VARCHAR(10) NOT NULL,
F_TO VARCHAR(10) NOT NULL, DISTANCE INT, DEPARTS TIME,
ARRIVES TIME, PRICE FLOAT);

AIRCRAFT TABLE
CREATE TABLE AIRCRAFT (AID INT PRIMARY KEY, ANAME VARCHAR(10),
CRUISINGRANGE INT);

EMPLOYEES TABLE
CREATE TABLE EMPLOYEES (EID INT PRIMARY KEY, ENAME VARCHAR(15),
SALARY FLOAT);

CERTIFIED TABLE

Department of CS&E, SOE, PRESIDENCY UNIVERSITY 76


CSE 253 DBMS LAB MANUAL 2018-19

CREATE TABLE CERTIFIED (EID INT, AID INT, PRIMARY KEY (EID, AID), FOREIGN KEY (EID)
REFERENCES EMPLOYEES (EID) ON DELETE CASCADE, FOREIGN KEY (AID) REFERENCES
AIRCRAFT (AID) ON DELETE CASCADE);
FLYS TABLE
CREATE TABLE FLYS(FNO INT, EID INT, PRIMARY KEY(FNO,EID), FOREIGN KEY (FNO)
REFERENCES FLIGHTS(FNO) ON DELETE CASCADE), FOREIGN KEY(EID) REFERENCES
EMPLOYEES(EID) ON DELETE CASCADE);

INSERT INTO TABLES


INSERT INTO FLIGHTS VALUES
(111,’BENGALURU’,’FRANKFURT’,7000,’21:30’,’07:30’,70000);
INSERT INTO FLIGHTS VALUES
(112,’BENGALURU’,’NEWDELHI’,2000,’06:00’,’08:30’,9000);
INSERT INTO FLIGHTS VALUES
(113,’BENGALURU’,’MUMBAI’,1000,’07:05’,’07:55’,8000);
INSERT INTO FLIGHTS VALUES
(114,’MUMBAI’,’NEWDELHI’,1000,’19:30’,’21:00’,7000);
INSERT INTO FLIGHTS VALUES
(115,’BENGALURU’,’NEWDELHI’,2000,’08:00’,’09:15’,4000);
INSERT INTO FLIGHTS VALUES
(116,’BENGALURU’,’PUNE’,800,’08:00’,’09:25’,5000);
INSERT INTO FLIGHTS VALUES
(117,’BENGALURU’,’FRANKFURT’,7000,’07:30’,’21:30’,70500);
INSERT INTO FLIGHTS VALUES (118,'NEWDELHI','LASVEGAS',5000,'22:00',
'20:00',65000);

INSERT INTO AIRCRAFT VALUES (11,’BOEING’,8000);


INSERT INTO AIRCRAFT VALUES (12,’AIRBUS’,6000);
INSERT INTO AIRCRAFT VALUES (13,’AIRINDIA’,5000);
INSERT INTO AIRCRAFT VALUES (14,’INDIGO’,900);
INSERT INTO AIRCRAFT VALUES (15,’SPICEJET’,800);

INSERT INTO EMPLOYEES VALUES (100,’ARJUN’,200000);


INSERT INTO EMPLOYEES VALUES (200,’NISHA’,150000);
INSERT INTO EMPLOYEES VALUES (300,’KAVYA’,200000);
INSERT INTO EMPLOYEES VALUES (400,’AKHILESH’,80000);
INSERT INTO EMPLOYEES VALUES (500,’PRIYA’,10000);
INSERT INTO EMPLOYEES VALUES (600,’RAJ’,200000);
INSERT INTO EMPLOYEES VALUES(700,'GIRISH',30000);
INSERT INTO EMPLOYEES VALUES(800,'DEEPIKA',50000);
INSERT INTO EMPLOYEES VALUES(900,'MITHUN',90000);

INSERT INTO CERTIFIED VALUES (100, 11);


INSERT INTO CERTIFIED VALUES (100, 12);

Department of CS&E, SOE, PRESIDENCY UNIVERSITY 77


CSE 253 DBMS LAB MANUAL 2018-19

INSERT INTO CERTIFIED VALUES (100, 13);


INSERT INTO CERTIFIED VALUES (200, 14);
INSERT INTO CERTIFIED VALUES (200, 15);
INSERT INTO CERTIFIED VALUES (200, 11);
INSERT INTO CERTIFIED VALUES (100, 15);
INSERT INTO CERTIFIED VALUES (400, 12);
INSERT INTO CERTIFIED VALUES (500, 14);
INSERT INTO CERTIFIED VALUES (600, 15);

INSERT INTO FLYS VALUES(111,100);


INSERT INTO FLYS VALUES(111,200);
INSERT INTO FLYS VALUES(111,300);
INSERT INTO FLYS VALUES(112,400);
INSERT INTO FLYS VALUES(113,500);
INSERT INTO FLYS VALUES(113,600);
INSERT INTO FLYS VALUES(114,700);
INSERT INTO FLYS VALUES(114,800);
INSERT INTO FLYS VALUES(115,900);

Write and Execute the SQL Queries for the following statements:
1. Display all the details of first four employees.

SELECT * FROM EMPLOYEES LIMIT 4;

2. Count the no. of flight between bengaluru and newdelhi.

SELECT COUNT(*) FROM FLIGHTS WHERE F_FROM='BENGALURU' AND


F_TO='NEWDELHI';

3. Display the flight no.s which have only one pilot.

SELECT FNO FROM FLYS GROUP BY FNO HAVING COUNT(*)=1;

4. Display the total cost of travel from bengaluru to newdelhi via mumbai.

SELECT SUM(PRICE) AS TOTAL_COST FROM


( SELECT PRICE FROM FLIGHTS WHERE F_FROM='BENGALURU' AND
F_TO='MUMBAI'
UNION ALL
SELECT PRICE FROM FLIGHTS WHERE F_FROM='MUMBAI' AND F_TO='NEWDELHI'
);

5. Display the second cheapest flight from bengaluru to newdelhi.

SELECT MIN(PRICE) AS SECOND_CHEAPEST


FROM FLIGHTS

Department of CS&E, SOE, PRESIDENCY UNIVERSITY 78


CSE 253 DBMS LAB MANUAL 2018-19

WHERE F_FROM='BENGALURU' AND F_TO='NEWDELHI' AND PRICE>(SELECT


MIN(PRICE) FROM FLIGHTS WHERE F_FROM='BENGALURU' AND
F_TO='NEWDELHI');

6. For each pilot who is certified for more than three aircrafts, find the eid and the
maximum cruisingrange of the aircraft for which she or he is certified.

SELECT C.EID, MAX(A.CRUISINGRANGE)


FROM CERTIFIED C, AIRCRAFT A
WHERE C.AID=A.AID
GROUP BY C.EID
HAVING COUNT(*)>3;

7. Find the names of pilots whose salary is less than the price of the cheapest route from
Bengaluru to Frankfurt.

SELECT DISTINCT E.ENAME


FROM EMPLOYEES E
WHERE E.SALARY<
(SELECT MIN(PRICE)
FROM FLIGHTS
WHERE F_FROM='BENGALURU' AND
F_TO='FRANKFURT');

8. For all aircraft with cruisingrange over 1000 Kms. find the name of the aircraft and the
average salary of all pilots certified for this aircraft.

SELECT A.AID, A.ANAME, AVG(E.SALARY)


FROM AIRCRAFT A, CERTIFIED C, EMPLOYEES E
WHERE A.AID=C.AID AND C.EID=E.EID AND
CRUISINGRANGE>1000
GROUP BY A.AID, A.ANAME;

Additional Queries to be executed:


1. Find the names of aircraft such that all pilots certified to operate them have salaries more
than Rs.80,000.
2. Find the names of pilots certified for some Boeing aircraft.
3. Find the aids of all aircraft that can be used on routes from Bengaluru to New Delhi.
4. Display the flight no.s which have more than one pilot.
5. Display the names of pilots who fly aircrafts from Bengaluru to Frankfurt.
6. Display the total cost of travel from Bengaluru to Lasvegas via New Delhi.

Department of CS&E, SOE, PRESIDENCY UNIVERSITY 79


CSE 253 DBMS LAB MANUAL 2018-19

Experiment No.14: Design and implementation of COMPANY database.

Consider the schema for COMPANY Database:

• EMPLOYEE (SSN, Name, Address, Salary, Sex)


• DEPARTMENT (DNo, DName, MgrSSN)
• PROJECT (PNo, PName, PLocation, DNo)
• WORKS_FOR(SSN,Dno)
• WORKS_ON (SSN, Pno, Hours)

SCHEMA DIAGRAM:

Department of CS&E, SOE, PRESIDENCY UNIVERSITY 80


CSE 253 DBMS LAB MANUAL 2018-19

ER DIAGRAM:

CREATE ALL TABLES:

CREATE TABLE EMPLOYEE(SSN INT PRIMARY KEY,ENAME VARCHAR(20),DOB


DATE,ADDRESS VARCHAR(40),SALARY REAL,SEX ENUM('MALE','FEMALE'));
CREATE TABLE DEPARTMENT(DNO INT PRIMARY KEY, DNAME VARCHAR(30),
MGR_SSN INT, FOREIGN KEY(MGR_SSN) REFERENCES EMPLOYEE(SSN));
CREATE TABLE PROJECT(PNO INT PRIMARY KEY, PNAME VARCHAR(40),
PLOCATION VARCHAR(30), DNO INT, FOREIGN KEY(DNO) REFERENCES
DEPARTMENT(DNO));
CREATE TABLE WORKS_FOR(SSN INT,DNO INT,PRIMARY KEY(SSN,DNO), FOREIGN
KEY(SSN) REFERENCES EMPLOYEE(SSN), FOREIGN KEY(DNO) REFERENCES
DEPARTMENT(DNO));
CREATE TABLE WORKS_ON(SSN INT, PNO INT, HOURS FLOAT, PRIMARY
KEY(SSN,PNO), FOREIGN KEY(SSN) REFERENCES EMPLOYEE(SSN), FOREIGN

Department of CS&E, SOE, PRESIDENCY UNIVERSITY 81


CSE 253 DBMS LAB MANUAL 2018-19

KEY(PNO) REFERENCES PROJECT(PNO));

INSERT INTO TABLES

INSERT INTO EMPLOYEE VALUES(101,’AMIT’, ‘2000-03-30’,’HEBBAL’,40000,


’MALE’);

INSERT INTO DEPARTMENT VALUES(1, ‘RESEARCH’, 103);

Department of CS&E, SOE, PRESIDENCY UNIVERSITY 82


CSE 253 DBMS LAB MANUAL 2018-19

INSERT INTO PROJECT VALUES(501,'DATA ANALYTICS','MUMBAI',1);

INSERT INTO WORKS_FOR VALUES(101,1);

Department of CS&E, SOE, PRESIDENCY UNIVERSITY 83


CSE 253 DBMS LAB MANUAL 2018-19

INSERT INTO WORKS_ON VALUES(101,501,4);

Write and Execute the SQL Queries for the following statements:

1. Make a list of all project numbers for projects that involve an employee whose last name
is ‘Ganesh’, either as a worker or as a manager of the department that controls the project.

(SELECT DISTINCT P.PNO FROM PROJECT P, DEPARTMENT D, EMPLOYEE E WHERE


P.DNO=D.DNO AND D.MGR_SSN=E.SSN AND E.ENAME='GANESH')
UNION
(SELECT DISTINCT P.PNO FROM PROJECT P, WORKS_ON W, EMPLOYEE E WHERE
P.PNO=W.PNO AND E.SSN=W.SSN AND E.ENAME='GANESH');

2. Show the resulting salaries if every employee working on the ‘IoT’ project is given a 10
percent raise.

SELECT E.ENAME, E.SALARY AS PRESENT_SAL,1.1 * E.SALARY AS


INCREASED_SAL FROM EMPLOYEE E, WORKS_ON W, PROJECT P WHERE
E.SSN=W.SSN AND W.PNO=P.PNO AND P.PNAME='IOT';

3. Find the sum of the salaries of all employees of the ‘Accounts’ department, as well as the
maximum salary, the minimum salary, and the average salary in this department

Department of CS&E, SOE, PRESIDENCY UNIVERSITY 84


CSE 253 DBMS LAB MANUAL 2018-19

SELECT SUM(E.SALARY), MAX(E.SALARY), MIN(E.SALARY), AVG(E.SALARY)


FROM EMPLOYEE E JOIN WORKS_FOR W ON(E.SSN=W.SSN) JOIN DEPARTMENT D
ON(W.DNO=D.DNO) WHERE D.DNAME='RESEARCH';

4. For each project on which more than ONE employee(s) work, retrieve the project
number, the project name, and the number of employees who work on the project.

SELECT P.PNO, P.PNAME, COUNT(*)


FROM PROJECT P, WORKS_ON W
WHERE W.PNO=P.PNO
GROUP BY P.PNO, P.PNAME
HAVING COUNT(*)>1;

5. For each project, retrieve the project number, the project name, and the number of
employees from department 3 who work on the project.

SELECT P.PNO, P.PNAME, COUNT(*)


FROM PROJECT P, WORKS_ON W, EMPLOYEE E
WHERE P.PNO=W.PNO AND W.SSN=E.SSN AND P.DNO=3
GROUP BY P.PNO, P.PNAME;

6. Count the number of Male & Female Employees in the COMPANY.

SELECT COUNT(IF (SEX='MALE',1,NULL)) AS MALE,


COUNT(IF (SEX='FEMALE',1,NULL)) AS FEMALE
FROM EMPLOYEE;

7. Display the count of Male and Female Employees working for Department 2.

SELECT (SELECT COUNT(*) FROM


EMPLOYEE E,WORKS_FOR W
WHERE E.SSN=W.SSN AND W.DNO=2 AND E.SEX='MALE') AS MALE, (SELECT
COUNT(*) AS MALE FROM EMPLOYEE E,WORKS_FOR W WHERE E.SSN=W.SSN
AND W.DNO=2 AND E.SEX='FEMALE') AS FEMALE;

8. Display the Average working hours for all the projects.

SELECT PNO,AVG(HOURS) AS AVG_TIME


FROM WORKS_ON
GROUP BY PNO
ORDER BY PNO;

9. Find the avg working hours of all female employees.

Department of CS&E, SOE, PRESIDENCY UNIVERSITY 85


CSE 253 DBMS LAB MANUAL 2018-19

SELECT (SELECT SUM(HOURS)


FROM EMPLOYEE E, WORKS_ON W
WHERE E.SSN=W.SSN AND E.SEX='FEMALE')/(SELECT COUNT(DISTINCT E.SSN)
FROM EMPLOYEE E, WORKS_ON W WHERE E.SSN=W.SSN AND E.SEX='FEMALE')
AS AVG_HOURS;

10. Display the list of employees of age above 25.

SELECT ENAME, DOB, TIMESTAMPDIFF(YEAR, DOB, CURDATE()) AS AGE FROM


EMPLOYEE
WHERE TIMESTAMPDIFF(YEAR, DOB, CURDATE())>25;

11. Display SSN, Name and Age of Employees working on Project 501.

SELECT SSN, ENAME, TIMESTAMPDIFF(YEAR,DOB,CURDATE()) AS AGE


FROM EMPLOYEE
WHERE SSN IN(SELECT SSN FROM WORKS_ON WHERE PNO=501);

12. Display SSN, Name and Age of Employees NOT working on Project 501.

SELECT SSN, ENAME, TIMESTAMPDIFF(YEAR,DOB,CURDATE()) AS AGE


FROM EMPLOYEE
WHERE SSN NOT IN(SELECT SSN FROM WORKS_ON WHERE PNO=501);

13. Display the Employee name and Address who work for ‘Research’ Department
(USING JOINS).
SELECT DISTINCT ENAME, ADDRESS FROM((EMPLOYEE E JOIN WORKS_FOR W ON
E.SSN=W.SSN) JOIN DEPARTMENT D ON W.DNO=D.DNO AND
D.DNAME='RESEARCH');

Use of Conditional Operators.

SELECT IF(1>3,'TRUE','FALSE');

14. Display SSN, Name and HE/SHE for all employees respectively.

SELECT SSN,ENAME,IF((SELECT SEX)='MALE','HE','SHE') AS GENDER FROM


EMPLOYEE;

15. Display SSN, Name and AGE as Major or Minor for all employees.

SELECT SSN,ENAME,IF((SELECT TIMESTAMPDIFF(YEAR,DOB, CURDATE()))>18,


'MAJOR','MINOR') AS AGE FROM EMPLOYEE;

Department of CS&E, SOE, PRESIDENCY UNIVERSITY 86


CSE 253 DBMS LAB MANUAL 2018-19

CREATING & USING VIEWS

16. Create Views for FEMALE employees to check Age>22 and Salary>25000

 CREATE VIEW CHECKSAL_F AS SELECT * FROM EMPLOYEE WHERE


TIMESTAMPDIFF(YEAR,DOB,CURDATE())>22 AND SEX='FEMALE' AND
SALARY>25000;

 SELECT * FROM CHECKSAL_F;

17. Create Views for MALE employees to check Age>22 and Salary>25000

 CREATE VIEW CHECKSAL_M AS SELECT * FROM EMPLOYEE WHERE


TIMESTAMPDIFF(YEAR,DOB,CURDATE())>22 AND SEX='MALE' AND
SALARY>25000;

 SELECT * FROM CHECKSAL_M;

USE OF TRIGGERS

DELIMITER //

CREATE TRIGGER SALCHECK BEFORE INSERT ON EMPLOYEE FOR EACH ROW IF


NEW.SALARY < 0 THEN SET NEW.SALARY =9999; END IF;//

DELIMITER ;

INSERT INTO EMPLOYEE VALUES(200,'NEHA','1995-09-12', 'BELLANDUR',-


100,'FEMALE');

SELECT * FROM EMPLOYEE;

Department of CS&E, SOE, PRESIDENCY UNIVERSITY 87


CSE 253 DBMS LAB MANUAL 2018-19

Experiment No.15: Design and implementation of MOVIE DATABASE.


Consider the schema for Movie Database:

ACTOR (Act_id, Act_Name, Act_Gender)


DIRECTOR (Dir_id, Dir_Name, Dir_Phone)
MOVIES (Mov_id, Mov_Title, Mov_Year, Mov_Lang, Dir_id)
MOVIE_CAST (Act_id, Mov_id, Role)
RATING (Mov_id, Rev_Stars)
Write SQL queries to
1. List the titles of all movies directed by ‘Hitchcock’.
2. Find the movie names where one or more actors acted in two or more movies.
3. List all actors who acted in a movie before 2000 and also in a movie
after 2015 (use JOIN operation).
4. Find the title of movies and number of stars for each movie that has at least one
rating and find the highest number of stars that movie received. Sort the result
by movie title.
5. Update rating of all movies directed by ‘Steven Spielberg’ to 5.

Solution:

Entity-Relationship Diagram

Dir_id Dir_Name
Act_id Act_Name

Dir_Phone
Act_Gender Actor Director

M
Has
Movie_Cast
N

Role

Rev_Stars
N Movies

Movie ID Year

Movie_Title MovieLang

Department of CS&E, SOE, PRESIDENCY UNIVERSITY 88


CSE 253 DBMS LAB MANUAL 2018-19

Schema Diagram
Actor
Act_id Act_Name Act_Gender

Director
Dir_id Dir_Name Dir_Phone

Movies
Mov_id Mov_Title Mov_Year Mov_Lang Dir_id

Movie_Cast
Act_id Mov_id Role

Rating
Mov_id Rev_Stars

Table Creation

CREATE TABLE ACTOR (


ACT_ID INTEGER (3),
ACT_NAME VARCHAR (20),
ACT_GENDER CHAR (1),
PRIMARY KEY (ACT_ID));

CREATE TABLE DIRECTOR (


DIR_ID INTEGER (3),
DIR_NAME VARCHAR (20),
DIR_PHONE VARCHAR (10),
PRIMARY KEY (DIR_ID));

CREATE TABLE MOVIES (


MOV_ID INTEGER (4),
MOV_TITLE VARCHAR (25),
MOV_YEAR INTEGER (4),
MOV_LANG VARCHAR (12),
DIR_ID INTEGER (3),
PRIMARY KEY (MOV_ID),
FOREIGN KEY (DIR_ID) REFERENCES DIRECTOR (DIR_ID));

Department of CS&E, SOE, PRESIDENCY UNIVERSITY 89


CSE 253 DBMS LAB MANUAL 2018-19

CREATE TABLE MOVIE_CAST (


ACT_ID INTEGER (3),
MOV_ID INTEGER (4),
ROLE VARCHAR (10),
PRIMARY KEY (ACT_ID, MOV_ID),
FOREIGN KEY (ACT_ID) REFERENCES ACTOR (ACT_ID),
FOREIGN KEY (MOV_ID) REFERENCES MOVIES (MOV_ID));

CREATE TABLE RATING (


MOV_ID INTEGER (4),
REV_STARS VARCHAR (25),
PRIMARY KEY (MOV_ID),
FOREIGN KEY (MOV_ID) REFERENCES MOVIES (MOV_ID));

Table Descriptions

mysql> DESC ACTOR;


+------------+-------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+------------+-------------+------+-----+---------+-------+
| ACT_ID | int(3) | NO | PRI | NULL | |
| ACT_NAME | varchar(20) | YES | | NULL | |
| ACT_GENDER | char(1) | YES | | NULL | |
+------------+-------------+------+-----+---------+-------+
3 rows in set (0.00 sec)

mysql> DESC DIRECTOR;


+-----------+-------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-----------+-------------+------+-----+---------+-------+
| DIR_ID | int(3) | NO | PRI | NULL | |
| DIR_NAME | varchar(20) | YES | | NULL | |
| DIR_PHONE | varchar(10) | YES | | NULL | |
+-----------+-------------+------+-----+---------+-------+
3 rows in set (0.07 sec)

mysql> DESC MOVIE_CAST;


+--------+-------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+--------+-------------+------+-----+---------+-------+
| ACT_ID | int(3) | NO | PRI | NULL | |
| MOV_ID | int(4) | NO | PRI | NULL | |
| ROLE | varchar(10) | YES | | NULL | |

Department of CS&E, SOE, PRESIDENCY UNIVERSITY 90


CSE 253 DBMS LAB MANUAL 2018-19

+--------+-------------+------+-----+---------+-------+
3 rows in set (0.00 sec)

mysql> DESC MOVIES;


+-----------+-------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-----------+-------------+------+-----+---------+-------+
| MOV_ID | int(4) | NO | PRI | NULL | |
| MOV_TITLE | varchar(25) | YES | | NULL |
| MOV_YEAR | int(4) | YES | | NULL | |
| MOV_LANG | varchar(12) | YES | | NULL |
| DIR_ID | int(3) | YES | MUL | NULL | |
+-----------+-------------+------+-----+---------+-------+
5 rows in set (0.00 sec)

mysql> DESC RATING;


+-----------+-------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-----------+-------------+------+-----+---------+-------+
| MOV_ID | int(4) | NO | PRI | NULL | |
| REV_STARS | varchar(25) | YES | | NULL |
+-----------+-------------+------+-----+---------+-------+
2 rows in set (0.00 sec)

Insertion of Values to Tables


INSERT INTO ACTOR VALUES (301,'ANUSHKA','F');
INSERT INTO ACTOR VALUES (302,'PRABHAS','M');
INSERT INTO ACTOR VALUES (303,'PUNITH','M');
INSERT INTO ACTOR VALUES (304,'JERMY','M');

INSERT INTO DIRECTOR VALUES (60,'RAJAMOULI', 8751611001);


INSERT INTO DIRECTOR VALUES (61,'HITCHCOCK', 7766138911);
INSERT INTO DIRECTOR VALUES (62,'FARAN', 9986776531);
INSERT INTO DIRECTOR VALUES (63,'STEVEN SPIELBERG', 8989776530);
INSERT INTO MOVIES VALUES (1001,'BAHUBALI-2', 2017, 'TELUGU', 60);
INSERT INTO MOVIES VALUES (1002,'BAHUBALI-1', 2015, 'TELUGU', 60);
INSERT INTO MOVIES VALUES (1003,'AKASH', 2008, 'KANNADA', 61);
INSERT INTO MOVIES VALUES (1004,'WAR HORSE', 2011, 'ENGLISH', 63);

INSERT INTO MOVIE_CAST VALUES (301, 1002, 'HEROINE');


INSERT INTO MOVIE_CAST VALUES (301, 1001, 'HEROINE');
INSERT INTO MOVIE_CAST VALUES (303, 1003, 'HERO');
INSERT INTO MOVIE_CAST VALUES (303, 1002, 'GUEST');

Department of CS&E, SOE, PRESIDENCY UNIVERSITY 91


CSE 253 DBMS LAB MANUAL 2018-19

INSERT INTO MOVIE_CAST VALUES (304, 1004, 'HERO');

INSERT INTO RATING VALUES (1001, 4);


INSERT INTO RATING VALUES (1002, 2);
INSERT INTO RATING VALUES (1003, 5);
INSERT INTO RATING VALUES (1004, 4);

Mysql> SELECT * FROM ACTOR;


+--------+----------+------------+
| ACT_ID | ACT_NAME | ACT_GENDER |
+--------+----------+------------+
| 301 | ANUSHKA |F |
| 302 | PRABHAS |M |
| 303 | PUNITH |M |
| 304 | JERMY |M |
+--------+----------+------------+
4 rows in set (0.00 sec)

mysql> SELECT * FROM DIRECTOR;


+--------+------------------+------------+
| DIR_ID | DIR_NAME | DIR_PHONE |
+--------+------------------+------------+
| 60 | RAJAMOULI | 8751611001 |
| 61 | HITCHCOCK | 7766138911 |
| 62 | FARAN | 9986776531 |
| 63 | STEVEN SPIELBERG | 8989776530 |
+--------+------------------+------------+
4 rows in set (0.00 sec)

mysql> SELECT * FROM MOVIES;


+--------+------------+----------+----------+--------+
| MOV_ID | MOV_TITLE | MOV_YEAR | MOV_LANG | DIR_ID |
+--------+------------+----------+----------+--------+
| 1001 | BAHUBALI-2 | 2017 | TELUGU | 60 |
| 1002 | BAHUBALI-1 | 2015 | TELUGU | 60 |
| 1003 | AKASH | 2008 | KANNADA | 61 |
| 1004 | WAR HORSE | 2011 | ENGLISH | 63 |
+--------+------------+----------+----------+--------+
4 rows in set (0.00 sec)

mysql> SELECT * FROM MOVIE_CAST;


+--------+--------+---------+
| ACT_ID | MOV_ID | ROLE |
+--------+--------+---------+

Department of CS&E, SOE, PRESIDENCY UNIVERSITY 92


CSE 253 DBMS LAB MANUAL 2018-19

| 301 | 1001 | HEROINE |


| 301 | 1002 | HEROINE |
| 303 | 1002 | GUEST |
| 303 | 1003 | HERO |
| 304 | 1004 | HERO |
+--------+--------+---------+
5 rows in set (0.00 sec)

mysql> SELECT * FROM RATING;


+--------+-----------+
| MOV_ID | REV_STARS |
+--------+-----------+
| 1001 | 4 |
| 1002 | 2 |
| 1003 | 5 |
| 1004 | 4 |
+--------+-----------+
4 rows in set (0.00 sec)

Queries:

1. List the titles of all movies directed by ‘Hitchcock’.

mysql> SELECT MOV_TITLE


-> FROM MOVIES
-> WHERE DIR_ID IN (SELECT DIR_ID
-> FROM DIRECTOR
-> WHERE DIR_NAME = 'HITCHCOCK');
+-----------+
| MOV_TITLE |
+-----------+
| AKASH |
+-----------+
1 row in set (0.00 sec)

2. Find the movie names where one or more actors acted in two or more movies.

mysql> SELECT MOV_TITLE


-> FROM MOVIES M, MOVIE_CAST MV
-> WHERE M.MOV_ID=MV.MOV_ID AND ACT_ID IN (
SELECT ACT_ID
FROM MOVIE_CAST GROUP BY ACT_ID HAVING
COUNT(ACT_ID)>1)
-> GROUP BY MOV_TITLE
-> HAVING COUNT(*)>1;

Department of CS&E, SOE, PRESIDENCY UNIVERSITY 93


CSE 253 DBMS LAB MANUAL 2018-19

+------------+
| MOV_TITLE |
+------------+
| BAHUBALI-1 |
+------------+
1 row in set (0.06 sec)

3. List all actors who acted in a movie before 2000 and also in a movie after 2015 (use
JOIN operation).

SELECT ACT_NAME, MOV_TITLE, MOV_YEAR


FROM ACTOR A
JOIN MOVIE_CAST C
ON A.ACT_ID=C.ACT_ID
JOIN MOVIES M
ON C.MOV_ID=M.MOV_ID
WHERE M.MOV_YEAR NOT BETWEEN 2000 AND 2015;
OR

SELECT A.ACT_NAME, C.MOV_TITLE, C.MOV_YEAR FROM


ACTOR A, MOVIE_CAST B, MOVIES C
WHERE A.ACT_ID=B.ACT_ID
AND B.MOV_ID=C.MOV_ID
AND C.MOV_YEAR NOT BETWEEN 2000 AND 2015;
+----------+------------+----------+
| ACT_NAME | MOV_TITLE | MOV_YEAR |
+----------+------------+----------+
| ANUSHKA | BAHUBALI-2 | 2017 |
+----------+------------+----------+
1 row in set (0.01 sec)

4. Find the title of movies and number of stars for each movie that has at least one
rating and find the highest number of stars that movie received. Sort the result by
movie title.

mysql> SELECT MOV_TITLE, MAX(REV_STARS)


-> FROM MOVIES
-> INNER JOIN RATING USING(MOV_ID)
-> GROUP BY MOV_TITLE
-> HAVING MAX(REV_STARS)>0
-> ORDER BY MOV_TITLE;
+------------+----------------+

Department of CS&E, SOE, PRESIDENCY UNIVERSITY 94


CSE 253 DBMS LAB MANUAL 2018-19

| MOV_TITLE | MAX(REV_STARS) |
+------------+----------------+
| AKASH |5 |
| BAHUBALI-1 | 2 |
| BAHUBALI-2 | 4 |
| WAR HORSE | 5 |
+------------+----------------+
4 rows in set (0.23 sec)

5. Update rating of all movies directed by ‘Steven Spielberg’ to 5.

mysql> UPDATE RATING


-> SET REV_STARS=5
-> WHERE MOV_ID IN (SELECT MOV_ID
FROM MOVIES
WHERE DIR_ID IN (SELECT DIR_ID
-> FROM DIRECTOR
-> WHERE DIR_NAME = 'STEVEN SPIELBERG'));

mysql> SELECT * FROM RATING;


+--------+-----------+
| MOV_ID | REV_STARS |
+--------+-----------+
| 1001 |4 |
| 1002 |2 |
| 1003 |5 |
| 1004 |5 |
+--------+-----------+
4 rows in set (0.00 sec)

Department of CS&E, SOE, PRESIDENCY UNIVERSITY 95


CSE 253 DBMS LAB MANUAL 2018-19

Viva Questions and Answers

1. What is SQL?
Structured Query Language is a non procedural language or a data sub language.
2. What is database?
A database is a logically coherent collection of data with some inherent meaning,
representing some aspect of real world and which is designed, built and populated with data
for a specific purpose.
3. What is DBMS?
It is a collection of programs that enables user to create and maintain a database. In other
words it is general-purpose software that provides the users with the processes of defining,
constructing and manipulating the database for various applications.
4. What is a Database system?
The database and DBMS software together is called as Database system.
5. Advantages of DBMS?

Redundancy is controlled.
Unauthorized access is restricted.
Providing multiple user interfaces.
Enforcing integrity constraints.
Providing backup and recovery.
6. Disadvantage in File Processing System?
Data redundancy & inconsistency.

Difficult in accessing data.

Data isolation.

Data integrity.

Concurrent access is not possible.

Security Problems.

Department of CS&E, SOE, PRESIDENCY UNIVERSITY 96


CSE 253 DBMS LAB MANUAL 2018-19

7. Describe the three levels of data abstraction?


There are three levels of abstraction:
Physical level: The lowest level of abstraction describes how data are stored.
Logical level: The next higher level of abstraction, describes what data are stored in database
and what relationship among those data.

View level:The highest level of abstraction describes only part of entire database.
7. Define the "integrity rules"
There are two Integrity rules.

Entity Integrity:States that ―Primary key cannot have NULL value‖


Referential Integrity:States that ―Foreign Key can be either a NULL value or should be
Primary Key value of other relation.
8. What is extension and intension?
Extension - It is the number of tuples present in a table at any instance. This is
timedependent.
Intension -It is a constant value that gives the name, structure of table and the constraints
laid on it.
10. What is Data Independence?
Data independence means that ―the application is independent of the storage structure
and access strategy of data‖. In other words, The ability to modify the schema definition in one
level should not affect the schema definition in the next higher level.
Two types of Data Independence:
Physical Data Independence: Modification in physical level should not affect the logical level.
Logical Data Independence: Modification in logical level should affect the view level.
NOTE: Logical Data Independence is more difficult to achieve
11. What is a view? How it is related to data independence?
A view may be thought of as a virtual table, that is, a table that does not really exist in
its own right but is instead derived from one or more underlying base table. In other words,
there is no stored file that direct represents the view instead a definition of view is stored in
data dictionary.
Growth and restructuring of base tables is not reflected in views. Thus the view can
insulate users from the effects of restructuring and growth in the database. Hence accounts for
logical data independence.

Department of CS&E, SOE, PRESIDENCY UNIVERSITY 97


CSE 253 DBMS LAB MANUAL 2018-19

12. What is Data Model?


A collection of conceptual tools for describing data, data relationships data semantics and
constraints.
13. What is E-R model?
This data model is based on real world that consists of basic objects called entities and of
relationship among these objects. Entities are described in a database by a set of attributes.
14. What is Object Oriented model?
This model is based on collection of objects. An object contains values stored in instance
variables within the object. An object also contains bodies of code that operate on the object.
These bodies of code are called methods. Objects that contain same types of values and the same
methods are grouped together into classes.
15. What is an Entity?
It is an 'object' in the real world with an independent existence.
16. What is an Entity type?
It is a collection (set) of entities that have same attributes.
17. What is an Entity set?
It is a collection of all entities of particular entity type in the database.
18. What is an Extension of entity type?
The collections of entities of a particular entity type are grouped together into an entity
set.
19. What is an attribute?
It is a particular property, which describes the entity.
20. What is a Relation Schema and a Relation?
A relation Schema denoted by R(A1, A2, …, An) is made up of the relation name
R and the list of attributes Ai that it contains. A relation is defined as a set of tuples. Let r
be the relation which contains set tuples (t1, t2, t3, ...,tn). Each tuple is an ordered list of n-
values t=(v1,v2, ..., vn).
21. What is degree of a Relation?
It is the number of attribute of its relation schema.
22. What is Relationship?
It is an association among two or more entities.

Department of CS&E, SOE, PRESIDENCY UNIVERSITY 98


CSE 253 DBMS LAB MANUAL 2018-19

23. What is Relationship set?


The collection (or set) of similar relationships.
24. What is Relationship type?
Relationship type defines a set of associations or a relationship set among a given set of
entity types.
25. What is degree of Relationship type?
It is the number of entity type participating.
26. What is DDL (Data Definition Language)?
A data base schema is specified by a set of definitions expressed by a special language
called DDL.
27. What is VDL (View Definition Language)?
It specifies user views and their mappings to the conceptual schema.
28. What is SDL (Storage Definition Language)?
This language is to specify the internal schema. This language may specify the mapping
between two schemas.
29. What is Data Storage - Definition Language?
The storage structures and access methods used by database system are specified by a set
of definition in a special type of DDL called data storage- definition language.
30. What is DML (Data Manipulation Language)?
This language that enable user to access or manipulate data as organized by appropriate
data model.
Procedural DML or Low level: DML requires a user to specify what data are needed and how to
get those data.
Non-Procedural DML or High level: DML requires a user to specify what data are needed
without specifying how to get those data.
30. What is DML Compiler?
It translates DML statements in a query language into low-level instruction that the
query evaluation engine can understand.
32. What is Relational Algebra?
It is a procedural query language. It consists of a set of operations that take one or
two relations as input and produce a new relation.
33. What is Relational Calculus?

Department of CS&E, SOE, PRESIDENCY UNIVERSITY 99


CSE 253 DBMS LAB MANUAL 2018-19

It is an applied predicate calculus specifically tailored for relational databases


proposed by E.F. Codd. E.g. of languages based on it are DSL, ALPHA, QUEL.
34. What is normalization?
It is a process of analyzing the given relation schemas based on their Functional
Dependencies (FDs) and primary key to achieve the properties

Minimizing redundancy
Minimizing insertion, deletion and update anomalies.
35. What is Functional Dependency?
A Functional dependency is denoted by XY between sets of attributes X and Y
that are subsets of R specifies a constraint on the possible tuple that can form a relation state
r of R. The constraint is for any two tuples t1 and t2 in r if t1[X] = t2[X] then they have
t1[Y] = t2[Y]. This means the value of X component of a tuple uniquely determines the
value of component Y.
36. When is a functional dependency F said to be minimal?
Every dependency in F has a single attribute for its right hand side.
We cannot replace any dependency X A in F dependency Y A where Y is a proper
subset of X and still have a set of dependency that is equivalent to F.
We cannot remove any dependency from F and still have set of dependency that is
equivalent to F.
36. What is Multivalued dependency?
Multivalued dependency denoted by X Y specified on relation schema R, where
X and Y are both subsets of R, specifies the following constraint on any relation r of R: if
two tuples t1 and t2 exist in r such that t1[X] = t2[X] then t3 and t4 should also exist in r
with the following properties
t3[x] = t4[X] = t1[X] = t2[X]
t3[Y] = t1[Y] and t4[Y] = t2[Y]
t3[Z] = t2[Z] and
t4[Z]=t1[Z]
where [Z = (R-(X U Y)) ]
38. What is Lossless join property?
It guarantees that the spurious tuple generation does not occur with respect to relation
schemas after decomposition.
39. What is 1 NF (Normal Form)?

Department of CS&E, SOE, PRESIDENCY UNIVERSITY 100


CSE 253 DBMS LAB MANUAL 2018-19

The domain of attribute must include only atomic (simple, indivisible) values.
40. What is Fully Functional dependency?
It is based on concept of full functional dependency. A functional dependency X Y is
fully functional dependency if removal of any attribute A from X means that the dependency
does not hold any more.
41. What is 2NF?
A relation schema R is in 2NF if it is in 1NF and every non-prime attribute A in R is
fully functionally dependent on primary key.
42. What is 3NF?
A relation schema R is in 3NF if it is in 2NF and for every FD X A either of the
following is true
X is a Super-key of R.
A is a prime attribute of R.
In other words, if every non prime attribute is non-transitively dependent on primary key.
43. What is BCNF (Boyce-Codd Normal Form)?
A relation schema R is in BCNF if it is in 3NF and satisfies additional constraints that
for every FD X A, X must be a candidate key.
44. What is 4NF?
A relation schema R is said to be in 4NF if for every Multivalued dependency X Y
that holds over R, one of following is true
X is subset or equal to (or) XY = R.
X is a super key.
45. What is 5NF?
A Relation schema R is said to be 5NF if for every join dependency {R1, R2, ...,Rn} that
holds R, one the following is true
Ri = R for some i.
The join dependency is implied by the set of FD, over R in which the left side is key of R.

46. What is Domain-Key Normal Form?


A relation is said to be in DKNF if all constraints and dependencies that should hold on the
constraint can be enforced by simply enforcing the domain constraint and key constraint on the
relation.

Department of CS&E, SOE, PRESIDENCY UNIVERSITY 101


CSE 253 DBMS LAB MANUAL 2018-19

47. What are partial, alternate,, artificial, compound and natural key?
Partial Key:
It is a set of attributes that can uniquely identify weak entities and that are related to same owner
entity. It is sometime called as Discriminator.
Alternate Key:All Candidate Keys excluding the Primary Key are known as Alternate Keys.

ArtificialKey:If no obvious key, either stand alone or compound is available, then the last
resort is to simply create a key, by assigning a unique number to each record or occurrence. Then
this is known as developing an artificial key.
CompoundKey: If no single data element uniquely identifies occurrences within a construct,
then
combining multiple elements to create a unique identifier for the construct is known as creating a
compound key.
NaturalKey: When one of the data elements stored within a construct is utilized as the primary
key, then it is called the natural key.
48. What is indexing and what are the different kinds of indexing?
Indexing is a technique for determining how quickly specific data can be
found.
Binary search style indexing
B-Tree indexing
Inverted list indexing
Memory resident table
Table indexing

49. What is system catalog or catalog relation? How is better known as?
A RDBMS maintains a description of all the data that it contains, information about
every relation and index that it contains. This information is stored in a collection of relations
maintained by the system called metadata. It is also called data dictionary.
50. What is meant by query optimization?
The phase that identifies an efficient execution plan for evaluating a query that has the
least estimated cost is referred to as query optimization.
51. What is join dependency and inclusion dependency?
JoinDependency:

Department of CS&E, SOE, PRESIDENCY UNIVERSITY 102


CSE 253 DBMS LAB MANUAL 2018-19

A Join dependency is generalization of Multivalued dependency.A JD {R1, R2, ...,Rn} is said to


hold over a relation R if R1, R2, R3, ..., Rn is a lossless-join decomposition of R . There is no
set of sound and complete inference rules for JD. InclusionDependency:
An Inclusion Dependency is a statement of the form that some columns of a relation are
contained in other columns. A foreign key constraint is an example of inclusion dependency.
52. What is durability in DBMS?
Once the DBMS informs the user that a transaction has successfully completed, its
effects should persist even if the system crashes before all its changes are reflected on disk. This
property is called durability.
53. What do you mean by atomicity and aggregation?
Atomicity:Either all actions are carried out or none are. Users should not have to worry about the
effect of incomplete transactions. DBMS ensures this by undoing the actions of incomplete
transactions.
Aggregation:A concept which is used to model a relationship between a collection of entities
and relationships. It is used when we need to express a relationship among relationships.

54. What is a Phantom Deadlock?


In distributed deadlock detection, the delay in propagating local information might cause
the deadlock detection algorithms to identify deadlocks that do not really exist. Such situations
are called phantom deadlocks and they lead to unnecessary aborts.

55. What is a checkpoint and when does it occur?


A Checkpoint is like a snapshot of the DBMS state. By taking checkpoints, the DBMS
can reduce the amount of work to be done during restart in the event of subsequent crashes.

56. What are the different phases of


transaction? Different phases are
Analysis phase
Redo Phase
Undo phase
57. What do you mean by flat file database?
It is a database in which there are no programs or user access languages. It has no cross-
file capabilities but is user-friendly and provides user-interface management.

Department of CS&E, SOE, PRESIDENCY UNIVERSITY 103


CSE 253 DBMS LAB MANUAL 2018-19

58. What is "transparent DBMS"?


It is one, which keeps its Physical Structure hidden from user.
59. Brief theory of Network, Hierarchical schemas and their properties
Network schema uses a graph data structure to organize records example for such a
database management system is CTCG while a hierarchical schema uses a tree data structure
example for such a system is IMS.
60. What is a query?
A query with respect to DBMS relates to user commands that are used to interact with a
data base. The query language can be classified into data definition language and data
manipulation language.
61. What do you mean by Correlated subquery?
Subqueries, or nested queries, are used to bring back a set of rows to be used by the
parent query. Depending on how the subquery is written, it can be executed once for the parent
query or it can be executed once for each row returned by the parent query. If the subquery is
executed for each row of the parent, this is called a correlated subquery.
A correlated subquery can be easily identified if it contains any references to the parent
subquery columns in its WHERE clause. Columns from the subquery cannot be referenced
anywhere else in the parent query. The following example demonstrates a non-correlated
subquery.
E.g. Select * From CUST Where '10/03/1990' IN (Select ODATE From ORDER Where
CUST.CNUM = ORDER.CNUM)
62. What are the primitive operations common to all record management
systems? Addition, deletion and modification.
63. Name the two schema change statements in SQL

ALTER and DROP

63. What are the unary operations in Relational


Algebra? PROJECTION and SELECTION.
64. Are the resulting relations of CARTESIAN PRODUCT and JOIN operation the same?
No.
PRODUCT: Concatenation of every row in one relation with every row in another.

Department of CS&E, SOE, PRESIDENCY UNIVERSITY 104


CSE 253 DBMS LAB MANUAL 2018-19

JOIN: Concatenation of rows from one relation and related rows from another.
66. What is RDBMS KERNEL?
Two important pieces of RDBMS architecture are the kernel, which is the software, and
the data dictionary, which consists of the system-level data structures used by the kernel to
manage the database
You might think of an RDBMS as an operating system (or set of subsystems), designed
specifically for controlling data access; its primary functions are storing, retrieving, and securing
data. An RDBMS maintains its own list of authorized users and their associated privileges;
manages memory caches and paging; controls locking for concurrent resource usage; dispatches
and schedules user requests; and manages space usage within its table-space structures.

67. Name the sub-systems of a RDBMS


I/O, Security, Language Processing, Process Control, Storage Management, Logging and
Recovery, Distribution Control, Transaction Control, Memory Management, Lock Management
68. Which part of the RDBMS takes care of the data dictionary? How
Data dictionary is a set of tables and database objects that is stored in a special area of
the database and maintained exclusively by the kernel.
69. What is the job of the information stored in data-dictionary?
The information in the data dictionary validates the existence of the objects, provides
access to them, and maps the actual physical storage location.
70. Not only RDBMS takes care of locating data it also Determines
an optimal access path to store or retrieve the data

Department of CS&E, SOE, PRESIDENCY UNIVERSITY 105

S-ar putea să vă placă și