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

DBMS LAB MANUAL

The document outlines the CS2207PC Database Management Systems Lab course for B.Tech. II Year II Sem, detailing its objectives, outcomes, and experiments. It covers fundamental concepts like database design, normalization, and SQL commands, along with a list of practical experiments and textbooks. The course aims to equip students with skills in database schema design and SQL for data manipulation.

Uploaded by

truparanicse
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views

DBMS LAB MANUAL

The document outlines the CS2207PC Database Management Systems Lab course for B.Tech. II Year II Sem, detailing its objectives, outcomes, and experiments. It covers fundamental concepts like database design, normalization, and SQL commands, along with a list of practical experiments and textbooks. The course aims to equip students with skills in database schema design and SQL for data manipulation.

Uploaded by

truparanicse
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 51

CS2207PC:DATABASEMANAGEMENT SYSTEMSLAB

B.Tech. II Year II Sem.


Course Hours /
Categery Credits Maxumum Marks
Code Week
L T P C CIA SEE Total
Core
0 0 3 1.5 25 75 100
Contact
Tutorial Classes : NIL Practical classes : 45 Total Classes :45
classes: NIL
Co-requisites:
• Co-requisiteofcourse“DatabaseManagementSystems”

Course Overview:
The purpose of this course is to provide a clear understanding of fundamentals with emphasis on their
applications to create and manage large data sets. It highlights on technical overview of database software to retrieve
data from n database. The course includes database design principles, normalization, concurrent transaction
processing,, security, recovery and file organization techniques.

CourseObjectives:
• IntroduceERdatamodel,database designandnormalization
• LearnSQL basicsfordata definition and datamanipulation

CourseOutcomes:
• Designdatabaseschemafor agivenapplicationandapply normalization
• Acquireskillsinusing SQLcommandsfordata definitionand datamanipulation.
• Developsolutionsfordatabaseapplicationsusingprocedures,cursorsandtriggers

ListofExperiments:
1. ConceptdesignwithE-RModel
2. Relational Model
3. Normalization
4. PracticingDDLcommands
5. PracticingDMLcommands
6. Querying(usingANY,ALL,IN,Exists,NOTEXISTS,UNION,INTERSECT,Constraintsetc.)
7. QueriesusingAggregatefunctions,GROUPBY,HAVINGandCreationanddroppingofViews.
8. Triggers(Creationof inserttrigger,deletetrigger,updatetrigger)
9. Procedures
10. UsageofCursors

TEXTBOOKS:
1. DatabaseManagementSystems,RaghuramaKrishnan,JohannesGehrke,TataMcGrawHill,3rd Edition
2. DatabaseSystemConcepts,Silberschatz,Korth,McGrawHill,Vedition.

REFERENCESBOOKS:
1. DatabaseSystemsdesign,Implementation,andManagement,PeterRob&CarlosCoronel7thEdition.
2. FundamentalsofDatabaseSystems,ElmasriNavrate,PearsonEducation
3. IntroductiontoDatabaseSystems, C.J.Date,PearsonEducation
4. OracleforProfessionals,The XTeam,S.Shah andV.Shah,SPD.
5. DatabaseSystemsUsingOracle:ASimplifiedguide toSQLandPL/SQL,Shah,PHI.
6. FundamentalsofDatabaseManagementSystems, M.L. Gillenson,WileyStudentEdition.

NRCM-CSE Mohd Nawazuddin-Asst Prof


week - 1

EXPERIMENT- 1
CONCEPT DESIGN WITH E-R MODEL
AIM: To Relate the entities appropriately. Apply cardinalities for each relationship. Identify
strong and weak entities. Indicate the type of relationships (total/partial). Incorporate
generalization, aggregation and specialization etc wherever required.

E-R Model

Student (Entity)

Last_
First Nam
_Na e Ci St
me Stud
Na ent t at
m id Ady ePin
e cod
dre e
Stu ss
den
t
Pho
ne D A
no O g
B e
Faculty : (Entity)

Last_N
First_N ame
ame
Facul
Na ty id
me
Depart
ment

F
a
c
Phon
e no u
Sal
l
ary
t
y

NRCM-CSE Mohd Nawazuddin-Asst Prof


Course : (Entity)

Course_Nam Course_id
e

Department

Course

Department : (Entity)

Department_id
Department_Name

Department

Subjects : (Entity)
Subject_id
Subject_Name

Subjects

Exams : (Entity)
Exam_code
Room_no
Time

Date

Exams
NRCM-CSE Mohd Nawazuddin-Asst Prof
Hostel : (Entity)

Hostel_name
Hostel_id

No_of_seats

Hostel

CONCEPT DESIGN WITH E-R MODEL

NRCM-CSE Mohd Nawazuddin-Asst Prof


WEEK - 2
EXPERIMENT – 2
RELATIONAL MODEL

AIM: To Represent all the entities (Strong, Weak) in tabular fashion. Represent relationships in
a tabular fashion.

Student: student(S_ID : INTEGER,S_NAME : STRING, ADDRESS:STRING)


Column Name DataType Constraints Type of
Attributes
S_ID INTEGER PRIMARY Single value
KEY
S_NAME VARCHAR(20) Multi value
D.O.B DATE
AGE INT Single value
ADDRESS VARCHAR (255) Multi value

SCHEMA:
Mysql>create table student(Student_Id integer primary
key,First_Name Varchar(20) not null,Last_Name varchar(20) not
null,DOB date,Age int,phone_number int,city varchar(20),state
varchar(20),pincode int);

Mysql>desc student;

NRCM-CSE Mohd Nawazuddin-Asst Prof


FACULTY:

Column Name DataType Constraints Type of


Attributes
FACULTY_ID INTEGER PRIMARY Single value
KEY
FACULTY_NAME VARCHAR(20) Multi value
DEPARTMENT VARCHAR(10) Single value
PHONE NO INT Multi value
SALARY INT Single value

SCHEMA:

mysql> create table faculty(Faculty_id int primary key,First_Name


varchar(20) not null,Last_Name varchar(20) not null,Department
varchar(10),phone_no int,salary int);

Mysql>desc faculty;

NRCM-CSE Mohd Nawazuddin-Asst Prof


COURSE:

Column Name DataType Constraints Type of


Attributes
COURSE_ID INTEGER PRIMARY Single value
KEY
COURSE_NAME VARCHAR(10) Single value
DEPARTMENT VARCHAR(20) Single value

SCHEMA:

mysql> create table course(course_id int primary key,course_name


varchar(10) not null,Department varchar(20));

mysql>desc course;

DEPARTMENT:

Column Name DataType


Constraints Type of
Attributes
DEPARTMENT_ID INTEGER PRIMARY Single
KEY value
DEPARTMENT_NAME VARCHAR(20) Single
value

SCHEMA:

mysql> create table Department(Department_Id int primary


key,Department_Name varchar(20));

NRCM-CSE Mohd Nawazuddin-Asst Prof


mysql>desc Department;

SUBJECT:

Column Name DataType Constraints Type of


Attributes
SUBJECT_ID INTEGER PRIMARY Single value
KEY
SUBJECT_NAME VARCHAR(20) NOT Single value
NULL

SCHEMA:

mysql> create table Subject(Subject_Id int primary


key,Subject_Name varchar(20) not null);

EXAMS:

Column Name DataType Constraints Type of


Attributes
EXAM_CODE INTEGER UNIQUE Single value
ROOM_NO INTEGER NOT NULL Single value
TIME DATE Single value
DATE DATE

NRCM-CSE Mohd Nawazuddin-Asst Prof


SCHEMA:

mysql> create table Exams(Exam_code int unique,Room_no int not


null,Time date, Date date);

HOSTEL:

Column Name DataType Constraints Type of


Attributes
HOSTEL_ID INTEGER UNIQUE Single value
HOSTEL_NAME VARCHAR(20) NOT NULL Single value
NO_OF_SEATS INT Single value

SCHEMA:

mysql> create table Hostel(Hostel_Id int unique,Hostel_Name


varchar(20) not null,No_of_seats int);

NRCM-CSE Mohd Nawazuddin-Asst Prof


EXPERIMENT - 3

NORMALIZATION
AIM: Apply the database Normalization techniques for designing relational database tables to minimize
duplication of information like 1NF, 2NF, 3NF, BCNF.

Normalization is a process of converting a relation to be standard form by decomposition a larger relation into
smaller efficient relation that depicts a good database design.

1NF: A Relation scheme is said to be in 1NF if the attribute values in the relation are atomic .i.e., Mutlivalued
attributes are not permitted.

2NF: A Relation scheme is said to be in 2NF,iff and every Non-key attribute is fully functionally dependent on
primary Key.

3NF: A Relation scheme is said to be in 3NF,iff and does not have transitivity dependencies. A Relation is said
to be 3NF if every determinant is a key for each & every functional dependency.

BCNF: A Relation scheme is said to be BCNF if the following statements are true for eacg FD P->Q in set F of
FDs that holds for each FD. P->Q in set F of FD’s that holds over R. Here P is the subset of attributes of R & Q
is a single attribute of R.
The given FD is a trival
P is a super key.

1. Exercise 1: 1st Normal Form (1NF)

Consider the Faculty table, with the primary key underlined, and the following data:

Faculty:
Faculty_Id Faculty_Name Skills

1 Sri C,C++

2 Ram Java

3 Abhi C,Java

a) Is the Faculty table in 1NF? Why?

A. No it is not in 1NF,As skills attribute in above table has multi value attributes. In 1NF only atomic i.e.
single value are allowed.

NRCM-CSE Mohd Nawazuddin-Asst Prof


b) If the Faculty table is not in 1NF, redesign the tables such that all the information currently in the
Faculty table is found in the resulting tables, and the resulting tables are in 1NF. For each of the resulting
tables, give the table name, column names, primary keys.

A. So solution to bring table to 1NF, here we need to decompose the table as following.

2. Exercise 2: 2ND Normal Form (2NF)

Consider the Students table, with the primary key underlined, and the following data:
Students:
Student_Id Student_Name Student_Address Course_Name Date of completion

1001 John Hyd C 20/4/2022


1002 Abhi Chennai C++ 15/4/2022
1003 Alex Hyd Java 25/04/2022
1004 Bob Bangalore DBMS 16/04/2022

a) Is the Students table in 2 NF? If yes Why? If No Why not?

A. The above given table is in 1NF but not in 2NF. Because STUDENT_NAME, STUDENT_ADDRESS
depends on STUDENT_ID but not on COURSE_NAME that makes a partial dependency and partial
dependency are not allowed in 2NF .

NRCM-CSE Mohd Nawazuddin-Asst Prof


b) If the Students table is not in 2NF, redesign or decompose the tables such that all the information
currently in the Students table is found in the resulting tables, and the resulting tables are in 2 NF. For
each of the resulting tables, give the table name, column names, primary keys, and foreign keys.

A. The solution for this is to decompose the table into 2 tables.as

STUDENT_ID STUDENT_NAME STUDENT_ADDRESS COURSE_NAME DATEOFCOMPLETION

STUDENT1 STUDENT_ID STUDENT_NAME STUDENT_ADDRESS

COURSE STUDENT_ID COURSE_NAME DATEOFCOMPLETION

NRCM-CSE Mohd Nawazuddin-Asst Prof


3. Exercise 3 : 3rd Normal Form (3NF)

Consider the Employee table, with the primary key underlined, and the following data:

Employee:
Emp_no Emp_Name Address Salary Company_Name Location

101 Sri TS 35000 C1 Hyd


102 Ram KA 40000 C2 Bangalore
103 Abhi TS 48000 C3 Hyd
104 Hari TS 50000 C1 Hyd

a) Is the Employee table in 3 NF? If yes Why? If No Why not?

A. NO it is not in 3NF, it is in 1NF and also in 2NF.


Here "Location" attribute depends on "Company_name" attribute which makes transitive dependency.
Transitive dependency are not allowed in 3NF.

b) If the Employee table is not in 3NF, redesign or decompose the tables such that all the information
currently in the Employee table is found in the resulting tables, and the resulting tables are in 3 NF. For
each of the resulting tables, give the table name, column names, primary keys, and foreign keys.
A. To covert relation to 3NF,we should decompose as following.

COMPANY COMPANY_NAME LOCATION

NRCM-CSE Mohd Nawazuddin-Asst Prof


EMPLOYEE1 EMPNO EMP_NAME ADDRESS SALARY COMPANY_NAME

4. Exercise 4 : Boyce-Codd Normal Form (BCNF)

Student_Id Course Teacher

101 DBMS MR.A


101 JAVA MR.B
102 DBMS MR.C
103 C++ MR.D
104 DBMS MR.A

a) Is the Above table in BCNF? If yes Why? If No Why not?

A. NO It is not in BCNF.Here {student_id,course}determines Teacher

and teacher(non key attribute) ------- > course(key attribute)

The determinant attribute(here Teacher) has to be a super key.But here Teacher is not a superkey.

NRCM-CSE Mohd Nawazuddin-Asst Prof


b) If the above table is not in BCNF, redesign or decompose the tables such that all the
information currently in the above table is found in the resulting tables, and the resulting
tables are in BCNF. For eachof the resulting tables, give the table name, column names,
primary keys, and foreign keys.

A. So we can get it into BCNF by decomposing as

following t ables.TEACHER COURSE


TEACHER

STUDENTSTUDENT_ID TEACHER

NRCM-CSE Mohd Nawazuddin-Asst Prof


P is a super key.

NRCM-CSE Mohd Nawazuddin-Asst Prof


EXPERIMENT- 4
PRACTICING DDL COMMANDS

AIM: To Implement DDL commands

DDL Commands:

DDL means Data Definition Language. It is used to create an object, alter the structure of an
object and also drop already created object.

The Data Definition Languages used for table definition can be classified into following:

• Create table command

• Alter table command

• Truncate table command

• Drop table command

• Rename

Data Definition Language


COMMAND DESCRIPTION
CREATE Create an object. means, create a database, table, triggers,index,
functions, stored procedures, etc.
ALTER Used to alter the existing database or its object structures.i.e.,
tables
DROP This SQL DDL command helps to delete objects. Forexample,
delete tables, delete a database, etc.
TRUNCATE This SQL DDL command removes records from tables
RENAME Renaming the database objects

NRCM-CSE Mohd Nawazuddin-Asst Prof


1.CREATION OF TABLES:

SQL - CREATE TABLE: Table is a primary object of database, used to store data in form of
rows and columns.

It is created using following command:

Syntax:
CREATE TABLE tablename (column_name data_ type constraints, …)

Example:
MYSQL > CREATE TABLE STUDENTS ((SID INT PRIMARY KEY, SNAME VARCHAR
(10), BRANCH VARCHAR (10), AGE INT );

Table Created.

Desc command
The DESCRIBE command is used to view the structure of a table as follows.

MYSQL>DESC STUDENTS;

EXERCISE:

1. Create an FACULTY table with fields (FACULTY_ID , FACULTY_NAME ,


HIREDATE,SUBJECT) and display using DESCRIBE command..
Sol:

2. Create an STUDENTMARKS table with fields (STUDENT_ID , STUDENT_NAME ,


OS,JAVA,DBMS,DM,BEFA,TOTAL) and display using DESCRIBE command..

NRCM-CSE Mohd Nawazuddin-Asst Prof


NRCM-CSE Mohd Nawazuddin-Asst Prof
3. Create an EMPLOYEE table with field
(ENO,ENAME,JOB,MGRID,HIREDATE,SALARY,COMMISION,DAPRTMENTNO)
Sol:

2. ALTER TABLE :

To ADD a column:

SYNTAX: ALTER TABLE <TBLE_NAME> ADD (<NEW_COLUMN_NAME>


<DATATYPE> (<SIZE>) .................);
EXERCISE:
1. Add A Column 'Department' To FACULTY Table.
Sol:

2. Add a column "Average" to STUDENTMARKS Table.


Sol:

NRCM-CSE Mohd Nawazuddin-Asst Prof


NRCM-CSE Mohd Nawazuddin-Asst Prof
To DROP a column:

SYNTAX: ALTER TABLE <TABLE_NAME>DROP COLUMN<COLUMN_NAME> ;.


EXERCISE:
1. Drop Column 'HIREDATE' From FACULTY Table.

2. Drop column 'AGE' from STUDENTS Table.

Sol:

NRCM-CSE Mohd Nawazuddin-Asst Prof


To MODIFY a column:

SYNTAX: ALTER TABLE <TABLE_NAME>MODIFY


COLUMN<COLUMN_NAME><NEW_DATATYPE> (<NEWSIZE>);
EXERCISE:
1. Modify Column 'SALARY' DATATYPE of EMPLOYEE Table From INT to FLOAT.

2. Modify column 'BRANCH' DATATYPE of STUDENTS Table from VARCHAR TO


CHAR with different size.

NRCM-CSE Mohd Nawazuddin-Asst Prof


3. RENAME A TABLE

Rename command is used to give new names for existing tables.

SYNTAX:
MYSQL> RENAME table oldtablename TO newtablename;

EXERCISE:
1. PRACTICE THE COMMAND BY RENAMING THE ALREADY CREATED TABLES

4. TRUNCATE A TABLE

Truncate command is used to delete all records from a table.

SYNTAX:
MYSQL> TRUNCATE TABLE tablename;

NRCM-CSE Mohd Nawazuddin-Asst Prof


EXERCISE:
1. PRACTICE THE COMMAND ON THE ALREADY CREATED TABLES

5. DROP A TABLE

Drop command is used to remove an existing table permanently from database.

SYNTAX:
MYSQL> DROP TABLE tablename;

EXERCISE:
1. PRACTICE THE COMMAND BY DROPING THE ALREADY CREATED TABLES

NRCM-CSE Mohd Nawazuddin-Asst Prof


EXPERIMENT- 5
PRACTICING DML COMMANDS

AIM: To Implement DML commands

DML: Data Manipulation Language (DML) statements are used for managing data within
schema objects and to manipulate data of a database objects.

DML Commands: Insert, Update, Delete, Select

INSERT - insert data into a table

UPDATE - updates existing data within a table

DELETE - deletes all records from a table, the space for the records remain

SELECT - retrieve data from the a database

1. Insert: Inserting data into tables.

Syntax: INSERT INTO TABLE_NAME (column1, column2, column3,...columnN)


VALUES (value1, value2, value3,...valueN);

OR
INSERT INTO TABLE_NAME VALUES(value1, value2, value3,...valueN);

Exercise:
Insert any five records into the tables STUDENTS, FACULTY, EMPLOYEE.

STUDENTS
+ + + + +
| SID | SNAME | BRANCH | AGE |
+ + + + +
| 101 | RAHUL | CSE | 19 |
| 102 | AJAY | CSE | 20 |
| 103 | VINAY | ECE | 18 |
| 104 | VICKY | ME | 20 |
| 105 | VIJAY | EEE | 20 |
+ + + + +

NRCM-CSE Mohd Nawazuddin-Asst Prof


EMPLOYEE

2. Update: Updating the column details of tables

Syntax: UPDATE table_name


SET column1 = value1, column2 = value2. .. , columnN = valueN
WHERE [condition];

Exercise:
1. Update the job = trainee of employee with empno=12005.

2. Update the age = 19 of student vicky.

NRCM-CSE Mohd Nawazuddin-Asst Prof


3. Update the subject = C++ of faculty with facultyid=1002.

4. Update the salary = 30000 of employee with empno=12003.

3. DELETE:Deleting records from tables

Syntax: DELETE FROM table_name WHERE condition;


Example: Delete from Employee where Empno=12004;

Exercise:
practice the delete command on previous created table.

NRCM-CSE Mohd Nawazuddin-Asst Prof


4. SELECT:

Syntax: SELECT column1, column2, ... FROM table_name;


or
SELECT * FROM table_name;
Exercise:
1.Display sid,sname and age from students table;

2.Dispaly Ename,job,mgrid,departmentno from Employee table.

3.Dispaly Facultyname and subject from Faculty table.

NRCM-CSE Mohd Nawazuddin-Asst Prof


VIVA QUESTIONS:

1. What is the full form of DML?

A. DML is an abbreviation of Data Manipulation Language.

2. Why is DML provided?

A. Data Manipulation Language which deals with data manipulation and it is used to store,
modify, retrieve, delete and update data in a database.

3. What are the 3 DML commands?

A. DML commands include SELECT, INSERT, UPDATE, and DELETE.

4. Difference between DDL and DML?

A. DDL is Data Definition Language which is used to define data structures. For example:
create table, alter table are instructions in MYSQL.

DML is Data Manipulation Language which is used to manipulate data itself. For example:
insert, update, delete are instructions in MYSQL.

5. What is the syntax for Update command?

AUPDATE table_name
SET column1 = value1, column2 = value2. .. , columnN = valueN
WHERE [condition];

6. What happens when we give delete command on table?

A. It deletes the record from given table name with help of where condition.

7.Update command are used along with which conditions?

A. Update command are used along with SET and WHERE conditions.

8.Which is the most commonly used Dml command?

A.SELECT.

9. For what Insert command is used for?

A. To Insert the new data into the table.

10. What is the difference between Delete and drop command?

A. DELETE is a Data Manipulation Language command, DML command and is used to remove
tuple /records from a relation/table. Whereas DROP is a Data Definition Language, DDL
command and is used to remove named elements of schema like relations/table, constraints or
entire schema

NRCM-CSE Mohd Nawazuddin-Asst Prof


EXPERIMENT – 6
Querying (using ANY, ALL, IN, Exists, NOT EXISTS, UNION, Constraints etc.)
Aim: Practice the following Queries:
ANY SYNTAX:
SELECT column_name(s) FROM table_name WHERE column_name operator ANY (SELECT column_name
FROM table_name WHERE condition);
ALL SYNTAX WITH SELECT:
SELECT column_name(s) FROM table_name WHERE column_name operator ALL (SELECT column_name
FROM table_name WHERE condition);
IN SYNTAX
SELECT column_name(s) FROM table_name WHERE column_name IN (value1, value2, ...);
EXISTS SYNTAX:
SELECT column_names FROM table_name WHERE EXISTS (SELECT column_names FROM table_name WHERE
condition);
NOT EXISTS SYNTAX:
SELECT col1, col2, ... FROM tablename WHERE NOT EXISTS (SELECT col1 FROM tablename WHERE
condition);
UNION SYNTAX:
SELECT column_name(s) FROM table1 UNION SELECT column_name(s) FROM table2;
INTERSECT SYNTAX:
SELECT column_name(s) FROM table1 INTERSECT SELECT column_name(s) FROM table2;
P.K
EID FIRSTNAME LASTNAME JOB SALARY ADDRESS
E01 SRI RAVI MANAGER 55000 CHANDIGARH
E02 ABHI VARUN ADMIN 20000 DELHI
E03 K NITIN ASSOCIATE 28000 PUNE
E04 PETER ROBIN ASSOCIATE 28000 BANGALORE
E05 JOSEPHINE AMMY DEVELOPER 38000 HYDERABAD

F.K P.K
EID PID PNAME LOCATION
E01 P1 IOT BANGALORE
E03 P3 BIG DATA DELHI
E04 P4 RETAIL MUMBAI
E05 P2 ANDROID HYDERABAD
1.Find the detail of the employees who is working on at least one project.
SELECT EID, FIRSTNAME, LASTNAME FROM EMPLOYEE WHERE EID = ANY
(SELECT EID FROM PROJECT);

NRCM-CSE Mohd Nawazuddin-Asst Prof


2.Find the detail of the employees who is working on project IOT.
SELECT EID, FIRSTNAME, LASTNAME FROM EMPLOYEE WHERE EID = ALL
(SELECT EID FROM PROJECT WHERE PNAME = ‘BIGDATA’);

3.Find the details of the employees belonging to Delhi or Hyderabad.


SELECT * FROM EMPLOYEE WHERE ADDRESS IN ('DELHI', 'HYDERABAD');

4. Find the details of all Employees apart from location Hyderabad.


SELECT * FROM EMPLOYEE WHERE ADDRESS NOT IN ('HYDERABAD');

5. Find the detail of the employees who is working on at least one project.
SELECT EID, FIRSTNAME, LASTNAME FROM EMPLOYEE WHERE EXISTS
(SELECT EID FROM PROJECT WHERE EMPLOYEE.EID = PROJECT.EID );

NRCM-CSE Mohd Nawazuddin-Asst Prof


6. Find the detail of the employees who is not working on any project.
SELECT EID, FIRSTNAME, LASTNAME FROM EMPLOYEE WHERE NOT EXISTS
(SELECT EID FROM PROJECT WHERE EMPLOYEE.EID = PROJECT.EID );
SID SNAME AGE ADDRESS
100 Raj 19 Hyd
101 Rajesh 19 Hyd
102 Ramesh 20 Hyd
103 Anvesh 20 Hyd
104 Abhinav 20 tn
104 Rahul 20 Bangalore
105 Rahul 20 Bangalore

SID SNAME AGE ADDRESS


201 Rahul 18 Bangalore
202 John 19 Bangalore
203 Joe 20 Hyd TABLE:
204 Alex 20 Che STUDENT1

TABLE: STUDENT2

1.UNION:
SELECT SNAME FROM STUDENT1 UNION SELECT SNAME FROM STUDENT2;
SELECT SNAME FROM STUDENT1 UNION ALL SELECT SNAME FROM STUDENT2;
By giving union we won’t get any duplicate values in result. while with union all it gives duplicate values also in
results.

NRCM-CSE Mohd Nawazuddin-Asst Prof


2.CONSTRAINTS: Add Check constraints to student1 table for column Age.
CHECK CONSTRAINT:
ALTER TABLE STUDENT1
ADD CONSTRAINT CHK_PersonAge CHECK (Age>=18);

Now try to insert age less than 18 i.e.,17 in student1 table. It won’t allow user to enter age of student less than 18

EXPERIMENT – 7
Queries using Aggregate functions, GROUP BY, HAVING and Creation and dropping of
Views.
Aim: To Practice Queries using Aggregate functions for the following

MySQL supports the following aggregate functions:


Function Description
AVG() Returns the average of the values in the selected column
COUNT() Returns the number of rows returned for a selection
MAX() Returns the maximum value for a column
MIN() Returns the minimum value of a column
SUM() Returns the sum of the values in a specified column

TABLE: EMPINFO
EID EMPLOYEENAME JOB MGR HIREDATE SALARY COMMISSION DEPTNO
ID
1001 ANIL MANAGER NULL 03/03/2010 35000 NULL 10
1002 AKHIL CLERK 1001 02/04/2015 25000 NULL 10
NRCM-CSE Mohd Nawazuddin-Asst Prof
1003 VINOD SALES 1001 05/06/2016 18000 1800 10
1004 VIKAS SALES 1001 06/07/2016 16000 1600 10
1005 SUNIL MANAGER NULL 03/04/2011 30000 NULL 20
1006 KIRAN CLERK 1005 05/06/2016 20000 NULL 20
1007 AREEB SALES 1005 10/05/2016 15000 1500 20

AGGREGRATE FUNCTIONS:
1.Write a query to get total number of employees working in organization.

2.Write a query to get total of salary paid to all employees.

3.Write a query to get the average of the salary paid.

4.Write a query to get details of employee whose salary is maximum amongst all employees.

5.Write a query to get details of employee whose salary is minimum amongst all employees.

ORDERBY, GROUPBY, HAVING CLAUSES:


ORDERBY:

NRCM-CSE Mohd Nawazuddin-Asst Prof


1.WAQ to get salary in ascending order:(Min to Max).

2.WAQ to get employee names in Alphabetic order.

3.WAQ to get salary in ascending order for the employees belonging to department number 10.

4.WAQ to create duplicate table and store the records based on salary wise.

GROUPBY, HAVING:
1.WAQ to get count of employees from each department.

NRCM-CSE Mohd Nawazuddin-Asst Prof


2.WAQ to get highest salary from each department.

3. WAQ to get highest salary from each job.

4.WAQ to get a count of employees with department number 10.

5.WAQ to get count of employees from each department only when the count is greater than 3.

CREATION AND DROPPING OF VIEWS:


SYNTAX FOR CREATION: SYNTAX FOR DELETION:
CREATE VIEW view_name AS DROP VIEW view_name;
SELECT column1, column2, ...
FROM table_name
WHERE condition;
1.Create
views as

GOODSTUDENTS whose grade is ‘A’ and view as average AVGSTUDENTS whose grade is
‘B’.

NRCM-CSE Mohd Nawazuddin-Asst Prof


2. Practice drop view command on already created views

EXPERIMENT – 8
TRIGGERS
Aim: Creation of insert trigger, delete trigger and update trigger.
A trigger is a procedure that is automatically invoked by the DBMS in response to specified changes to the database.
Six types of actions or events in the form of triggers:
• Before Insert: It is activated before the insertion of data into the table.
• After Insert: It is activated after the insertion of data into the table.
• Before Update: It is activated before the update of data in the table.
• After Update: It is activated after the update of the data in the table.
• Before Delete: It is activated before the data is removed from the table.

NRCM-CSE Mohd Nawazuddin-Asst Prof


• After Delete: It is activated after the deletion of data from the table.

Syntax of Creating a Trigger in MySQL:


CREATE TRIGGER trigger_name
(AFTER | BEFORE) (INSERT | UPDATE | DELETE) /*Event/
ON table_name FOR EACH ROW
BEGIN /*Action/
--variable declarations
--trigger code
END;

TABLE: EMPINFO
PK
EID EMPLOYEENAME JOB MGR HIREDATE SALARY COMMISSION DEPTNO
ID
1001 ANIL MANAGER NULL 03/03/2010 35000 NULL 10
1002 AKHIL CLERK 1001 02/04/2015 25000 NULL 10
1003 VINOD SALES 1001 05/06/2016 18000 1800 10
1004 VIKAS SALES 1001 06/07/2016 16000 1600 10
1005 SUNIL MANAGER NULL 03/04/2011 30000 NULL 20
1006 KIRAN CLERK 1005 05/06/2016 20000 NULL 20
1007 AREEB SALES 1005 10/05/2016 15000 1500 20

BEFORE INSERT: Creating a trigger not to allow any insertion in EMPINFO table:

Now check whether the trigger is invoked or not by inserting values in EMPINFO table

DROP THE TRIGGER TO PERFORM OTHER OPERATIONS

----------------------------------------------------------------------------------------------------------------------------- ------------------
-------------------------------------------------------------------------------------------
AFTER INSERT: creating a trigger FOR any insertion in EMPINFO table copies the data to another table
EMPINFOAUDIT.
CREATE A TABLE EMPINFOAUDIT:

NRCM-CSE Mohd Nawazuddin-Asst Prof


NOW CREATE A TRIGGER:

Now check whether the trigger is invoked or not by inserting values in EMPINFO table

----------------------------------------------------------------------------------------------------------------------------- ------------------
-------------------------------------------------------------------------------------------
BEFORE UPDATE: creating a trigger that not allows to modify manager or clerk details:

Now check whether the trigger is invoked or not by updating values in EMPINFO table

NRCM-CSE Mohd Nawazuddin-Asst Prof


----------------------------------------------------------------------------------------------------------------------------- ------------------
-------------------------------------------------------------------------------------------
AFTER UPDATE: creating a trigger FOR any updating in EMPINFO table copies the data to another table
EMPINFOAUDIT.

Now check whether the trigger is invoked or not by updating values in EMPINFO table

-----------------------------------------------------------------------------------------------------------------------------------------------
-------------------------------------------------------------------------------------------
BEFORE DELETE: creating trigger which not allows to delete more than one row from table.

Now check whether the trigger is invoked or not by deleting multiple rows in EMPINFO table

Now check by deleting single row.it should delete a single row as we written trigger for multiple rows i.e., more than 1
row.

NRCM-CSE Mohd Nawazuddin-Asst Prof


-----------------------------------------------------------------------------------------------------------------------------------------------
-------------------------------------------------------------------------------------------
AFTER DELETE: creating a trigger for deleting any row in EMPINFO table copies the data to another table
EMPINFOAUDIT.

Now check whether the trigger is invoked or not by deleting rows in EMPINFO table and also check the
EMPINFOAUDIT table to check whether it copied the deleted row.

EXPERIMENT – 9
PROCEDURES
Aim: Creation of stored Procedures and Execution of Procedures and Modification of
Procedures.
NRCM-CSE Mohd Nawazuddin-Asst Prof
1.Create a procedure to print sum of two values.

2.Create a procedure to accept EID and display info of Employee from EMPINFO table.

3.Create a procedure to add records in EMPINFO table.

CHECK THE TABLE

NRCM-CSE Mohd Nawazuddin-Asst Prof


4.Create a procedure to accept EID and update the SALARY in EMPINFO Table.

CHECK THE TABLE

5.Create a procedure to accept EID and delete the record from EMPINFO Table.

CHECK THE TABLE

6.Create a procedure to check duplicate EID while ADDING Record in EMPINFO Table.
NRCM-CSE Mohd Nawazuddin-Asst Prof
NRCM-CSE Mohd Nawazuddin-Asst Prof
EXPERIMENT – 10
CURSORS
Aim: Declare a cursor that defines a result set. Open the cursor to establish the result set. Fetch the data into local
variables as needed from the cursor, one row at a time. Close the cursor when done.

MySQL Cursor
 Declare Cursor. A cursor is a select statement, defined in the declaration section in MySQL.
 Open Cursor. After declaring the cursor, the next step is to open the cursor using open statement.
 Fetch Cursor. After declaring and opening the cursor, the next step is to fetch the cursor. ...
 Close Cursor. The final step is to close the cursor.

The following diagram illustrates how MySQL cursor works.

Declare Cursor
Syntax
DECLARE cursor_name CURSOR FOR Select statement;

Open Cursor
Syntax
Open cursor_name;

Fetch Cursor
Syntax
FETCH <cursor_name> INTO <variable_list>;
Close Cursor
Syntax
Close cursor_name;

1.Create a CURSOR to display records i.e., Empname and salary from EMPINFO table.

NRCM-CSE Mohd Nawazuddin-Asst Prof


2. Create procedure with cursor to accept deptno and display the employee names in that department.(USE
EMPINFO TABLE)

Now call the procedure to execute the cursor

NRCM-CSE Mohd Nawazuddin-Asst Prof


3.Create a cursor to copy the EMPINFO table data into another table.

First create an empty table as EMPBACKUP in which you want to copy data.

Now create a procedure with cursor

Now check the table EMPBACKUP


NRCM-CSE Mohd Nawazuddin-Asst Prof
4.Create a CURSOR to increment the salary based on Designation (here JOB).
If job = manager; If job = clerk; If job = sales;
Increment by20000 Increment by 10000 Increment by 5000

NRCM-CSE Mohd Nawazuddin-Asst Prof


5.Create a procedure with CURSOR to accept a deptno and display the employee’s names as list belongs to that
department.

Now call the procedure

NRCM-CSE Mohd Nawazuddin-Asst Prof


NRCM-CSE Mohd Nawazuddin-Asst Prof

You might also like