You are on page 1of 47

Government Polytechnic College

Chelakkara

Department of Computer Engineering

Lab Manual

Semester 3
3136 - Database Management Systems Lab
(2021 - Scheme)
2 Database Management System Lab

Program : Diploma in Computer Engineering / Cyber Forensics and Information


Security / Robotic Process Automation

Course Code : 3136 Course Title: Database Management


Systems Lab

Semester : 3 Credits: 1.5

Course Category: Program Core

Periods per week: 3 (L:0 T:0 P:3) Periods per semester: 45

Course Objectives:
● Impart to design, develop and manage relational databases using SQL.
● Understand the design of databases with constraints for real world applications.

Course Prerequisites:
Topic Course Course name Semeste
code r

Basic programming concepts Introduction to IT systems Lab I

Programming concepts Problem Solving & II


Programming

Course Outcomes :

On completion of the course, the student will be able to:


COn Description Durati Cognitive
on Level
(Hours
)

CO1 Make use of DDL, DML commands to construct 12 Applying


and manage databases

CO2 Make use of aggregate functions, join 11 Applying

GPTC, Chelakkara Department of Computer Engineering


3 Database Management System Lab

operations, views and nested queries

CO3 Develop SQL programming using 12 Applying


functions, procedures, cursors and trigger

CO4 Design and develop databases for real 7 Applying


world applications

Lab Exam 3

CO – PO Mapping
Course PO1 PO2 PO3 PO4 PO5 PO6 PO7
Outcomes

CO1 3 3

CO2 3 3

CO3 3 3

CO4 3 3 3 3 3

3-Strongly mapped, 2-Moderately mapped, 1-Weakly mapped

Course Outline
Module Name of the Experiment Duration Cognitive
Outco (Hours) Level
mes

CO1 Make use of DDL, DML commands to construct and


manage databases

M1.01 Experiment with DDL 2 Applying


commands-CREATE, ALTER, DROP

M1.02 Apply integrity constraints - PRIMARY 2 Applying


KEY, NOT NULL, DEFAULT, CHECK,
UNIQUE, FOREIGN KEY

M1.03 Apply DML commands - INSERT, SELECT, 4 Applying

GPTC, Chelakkara Department of Computer Engineering


4 Database Management System Lab

UPDATE and DELETE to manipulate


databases

M1.04 Experiment with WHERE, DISTINCT, 4 Applying


BETWEEN, ORDER BY, IN, LIKE, set
operations in SELECT statements for
data retrieval from the databases

CO2 Make use of aggregate functions, join operations,


views and nested queries

M2.01 Identify aggregate functions -SUM, 3 Applying


AVG, COUNT, MIN, MAX - GROUP
BY and HAVING clause

M2.02 Develop nested queries 3 Applying

M2.03 Develop SQL queries for inner and outer joins. 3 Applying

M2.04 Construct various views of the table 2 Applying

Lab Exam – I 1.5

CO3 Develop SQL programming using functions, procedures, cursors


and trigger

M3.01 Experiment with stored procedures for 3 Applying


simple tasks

M3.02 Utilize stored functions for database 3 Applying


manipulations

M3.03 Experiment with cursors for database operations 3 Applying

M3.04 Develop SQL programs using triggers 3 Applying

CO4 Design and develop databases for real world applications

M4.01 Open Ended Experiments** 7 Applying

Lab Exam – II 1.5

GPTC, Chelakkara Department of Computer Engineering


5 Database Management System Lab

** - Sample Open Ended Experiments


(Not for End Semester Examination but compulsory to be included in Continuous Internal
Evaluation.) Students can-do open-ended experiments as a group of 2-3. There is no duplication
in experiments between groups.
Consider the following scenarios:

∙ Student information system

∙ Hostel management

∙ Library management

∙ Super market billing system


Students should gather the required information, draw the ER diagrams, map them to the
relative databases and normalize the tables.
Text / Reference
T/R Book Title/Author

T1 Elmasri, Navathe, Database Systems ,6th ed., Pearson,2011

R1 Sliberschatz A., H. F. Korth and S. Sudarshan, Database System Concepts, 6th


ed, McGraw Hill, 2011.

R2 ITL Education Solutions ltd, Introduction to Database Systems, Pearson,2011

Online Resources
Sl.No Website Link

1 https://www.w3schools.com/sql

2 https://www.tutorialspoint.com/sql

3 https://www.javatpoint.com/sql

4 https://www.guru99.com/sql

GPTC, Chelakkara Department of Computer Engineering


1 Database Management System Lab

EXPERIMENT NO: 1
DATA DEFINITION LANGUAGE (DDL) COMMANDS

Experiment Outcome:
M1.01 Experiment with DDL commands-CREATE, ALTER, DROP

AIM:
To execute and verify the Data Definition Language commands.

Apparatus
MySql server software and mysql client software

THEORY
The commands used are:
CREATE - It is used to create a table.
ALTER – The structure of a table can be modified by using the ALTER TABLE command. This
command is used to add a new column, modify the existing column definition and to include or
drop integrity constraints.
DROP - It will delete the table structure provided the table should be empty.
TRUNCATE - If there is no further use of records stored in a table and the structure has to be
retained, and then the records alone can be deleted.
DESC - This is used to view the structure of the table

PROCEDURE
CREATION OF TABLE:
SYNTAX:
create table<table name>(column1 data type,column2 datatype...);

ALTER TABLE
(a) To Add column to existing Table
Syntax:
alter table table-name add(column-name datatype );
(b)To Add Multiple columns to existing Table
Syntax:
alter table table-name add(column-name1 datatype1, column-name2
datatype2, column-name3 datatype3);
(c) Dropping a Column from a Table
Syntax:
ALTER TABLE <Table_name>DROP COLUMN <CoumnName>;
(d) Modifying Existing Columns

GPTC, Chelakkara Department of Computer Engineering


2 Database Management System Lab

Syntax:
ALTER TABLE <Table Name>MODIFY (<CoumnName><Newdata
type>(<size>));
EXAMPLE:
(e) To Rename a column
Using alter command we can rename an existing column
Syntax:
alter table table-name change old-column-name to column-name;

RENAMING TABLES
Syntax:
ALTER TABLE tablename RENAME to <new table>;

TRUNCATE TABLE .
Syntax:
TRUNCATE TABLE <TABLE NAME>;

DESTROYING TABLES
Syntax:
DROP TABLE <TABLE NAME>;

DESCRIBE TABLES
. Syntax:
DESC <TABLE NAME>;

Problems
1.Create the tables described below
Table Name : ORDER_DETAILS
Description : used to store order information
size
Column name Data type size
ORDERNO INT 6
PURCHACEAMOUNT DECIMAL 8,2
CUSTOMERID INT 4
SALESMANID INT 4

Table Name : CUSTOMER_MASTER


Description : used to store client information
Column name Data Type Size

GPTC, Chelakkara Department of Computer Engineering


3 Database Management System Lab

CUSTOMERID INT 6
CNAME VARCHAR 30
CITY VARCHAR 8
GRADE INT 3
SALESMAN_ID INT 10,2

Table Name : SALESMAN_MASTER


Description : used to store salesman information working for the company

Column name Data Type Size


SALESMAN_ID INT 4
SNAME VARCHAR 35
CITY VARCHAR 15
Comission DECIMAL 5,2

Table Name : STUDENT


Description : used to store student information
Column name Data Type Size
SNO INT 5
SNAME VARCHAR 20
AGE INT 5
SDOB DATE
SMARK1 INT 4,2
SMARK2 INT 4,2
SMARK3 INT 4,4

2. Insert the following data


SALESMAN_MASTER
salesman_id sname city commission
5001 James Hoog New York 0.15
5002 Nail Knite Paris 0.13
5005 Pit Alex London 0.11
5006 Mc Lyon Paris 0.14
5003 Lauson Hen San Jose 0.12
5007 Paul Adam Rome 0.13

ORDER_DETAILS

GPTC, Chelakkara Department of Computer Engineering


4 Database Management System Lab

ord_no purch_amount ord_date customer_id salesman_id


70001 150.5 2012-10-05 3005 5002
70009 270.65 2012-09-10 3001 5005
70002 65.26 2012-10-05 3002 5001
70004 110.5 2012-08-17 3009 5003
70007 948.5 2012-09-10 3005 5002
70005 2400.6 2012-07-27 3007 5001
70008 5760 2012-09-10 3002 5001
70010 1983.43 2012-10-10 3004 5006
70003 2480.4 2012-10-10 3009 5003
70012 250.45 2012-06-27 3008 5002
70011 75.29 2012-08-17 3003 5007
70013 3045.6 2012-04-25 3002 5001

CUSTOMER_MASTER
customer_id cust_name city grade salesman_id
3002 Nick Rimando New York 100 5001
3005 Graham Zusi California 200 5002
3001 Brad Guzan London 200 5005
3004 Fabian Johns Paris 300 5006
3007 Brad Davis New York 200 5001
3009 Geoff Camero Berlin 100 5003
3008 Julian Green London 300 5002
3003 Jozy Altidor Moscow 200 5007

3. Exercise on altering the table structure


(a) Add a column called ‘telephone’ of data type ‘number’ and size =’10’ to the Customer
_Master table.
(b)Change the size of purchase_amount column in ORDER_DETAILS to 10,2
(c) Add a new field orderdate after purchase amount in order_detail table
(d) Rename the field CNAME as ‘CUST_NAME’ in Customer_Master table.
(e) Delete the field telephone from customer_master

4. Exercise on deleting the table structure along with the data


(a)Destroy the table student along with its data

5. Exercise on renaming the table

GPTC, Chelakkara Department of Computer Engineering


5 Database Management System Lab

(a)Change the name of the Salesman_Master table to Employee_master

RESULT:
The DDL commands have been executed successfully

GPTC, Chelakkara Department of Computer Engineering


6 Database Management System Lab

EXPERIMENT NO:2
CONSTRAINTS

Experiment Outcome
M1.02 Apply integrity constraints - PRIMARY KEY, NOT NULL, DEFAULT, CHECK,
UNIQUE, FOREIGN KEY

AIM:
To implement Data Constraints.

THEORY
SQL constraints are used to specify rules for the data in a table. Constraints are used to limit the
type of data that can go into a table. This ensures the accuracy and reliability of the data in the
table. If there is any violation between the constraint and the data action, the action is aborted.
TYPES OF CONSTRAINTS: 1) Primary key 2) Foreign key/references 3) Check 4) Unique 5)
Not null 6) Null 7) Default

PROCEDURE
(a) The PRIMARY KEY

The PRIMARY KEY defined at column level

Syntax:
CREATE TABLE tablename (Columnname1 DATATYPE CONSTRAINT
<constraintname1> PRIMARY KEY,Columnname2 DATATYPE, columnname3
DATATYPE,.....);

The PRIMARY KEY defined at table level

Syntax:
CREATE TABLE tablename (Columnname1 DATATYPE, columnname2
DATATYPE, columnname3 DATATYPE, PRIMARY KEY (columnname1,
columnname2));

(b)CHECK CONSTRAINT

The CHECK Constraint defined at column level

Syntax:

GPTC, Chelakkara Department of Computer Engineering


7 Database Management System Lab

CREATE TABLE tablename (Columnname1 DATATYPE CHECK (logical


expression), columnname2 DATATYPE, columnname3 DATATYPE,...);

The CHECK Constraint defined at table level

Syntax:
CREATE TABLE tablename (Columnname1 DATATYPE, columnname2
DATATYPE, columnname3 DATATYPE, CHECK (logical expression1),
CHECK (logical expression2));

(c) UNIQUE CONSTRAINT

The UNIQUE Constraint defined at the column level

Syntax
CREATE TABLE tablename (Columnname1 DATATYPE UNIQUE, columnname2
DATATYPE UNIQUE, columnname3 DATATYPE ...);

The UNIQUE Constraint defined at the the table level

Syntax
CREATE TABLE tablename (Columnname1 DATATYPE, columnname2
DATATYPE, columnname3 DATATYPE, UNIQUE (columnname1));

(d) Not Null

Syntax
CREATE TABLE tablename(Columnname1 DATATYPE NOT NULL,
columnname2 DATATYPE NOT NULL,columnname3 DATATYPE,...);

Problems
1.Create the tables described below

Table Name : PRODUCT_MASTER

Description : used to store product information

GPTC, Chelakkara Department of Computer Engineering


8 Database Management System Lab

Column name Data type size


PRODUCTNO Varchar 6 'Primary key' Starts with ‘P’
DESCRIPTION Varchar 15 Not Null
PROFITPERCENT DECIMAL 4,2 Not Null
UNITMEASURE Varchar 10 Not Null
QTYONHAND INT 8 Not Null
REORDERLVL INT 8 Not Null
SELLPRICE DECIMAL 8,2 Not Null can not be zero
COSTPRICE DECIMAL 8,2 Not Null can not be zero

Table Name : CLIENT_MASTER

Description : used to store client information

Column name Data Type Size


CLIENTNO Varchar 6 Primary
key/first letter must start with ‘C’
NAME Varchar 20 Not Null

ADDRESS1 Varchar 30
ADDRESS2 Varchar 30
CITY Varchar 15
PINCODE INT 8
STATE Varchar 15
BALDUE DECIMAL 10,2

Table Name : SALESMAN_MASTER

Description : used to store salesman information working for the company

Column name Data Type Size

GPTC, Chelakkara Department of Computer Engineering


9 Database Management System Lab

SALESMANNO Varchar 6 Primary key/first letter must


start with ‘S’
SALESMANNAME Varchar 20 Not null
ADDRESS1 Varchar 30 Not null
ADDRESS2 Varchar 30
CITY Varchar 15
PINCODE INT 8
STATE Varchar 15
SALARY DECIMAL 8,2

2. Exercise to verify the constaints


a) Try to insert two records with the same PRODUCTNO to PRODUCTMASTER Table
b) Try to insert a record without specifing the UNIT MEASURE to PRODUCTMASTER Table
c) Try to insert a record without specifing the SELLPRICE and COSTPRICE to
PRODUCTMASTER Table
d) Try to insert two records with the same CLIENTNO to CLIENTMASTER Table
e) set 'Kerala' as the default value for STATE in SALESMAN_MASTER table
f) Try to insert a record without specifing the STATE to SALESMAN_MASTER Table
g) Add a field ADHARNO as UNIQUE field to SALESMAN_MASTER Table
h) Try to add two record with same Adharnumber

RESULT:
The DDL commands with constraints have been executed successfully

GPTC, Chelakkara Department of Computer Engineering


10 Database Management System Lab

EXPERIMENT NO 3
DATA MANIPULATION LANGUAGE
Experiment Outcomes
M1.03 Apply DML commands - INSERT, SELECT, UPDATE and DELETE to manipulate
databases
AIM:
To execute the Data Manipulation Language (DML) commands in RDBMS.

OBJECTIVES
To understand Data Manipulation Language (DML) commands

THEORY
DML commands are the most frequently used SQL commands and are used to query and
manipulate the existing database objects. Some of the commands are
1. INSERT
This is used to add one or more rows to a table. The values are separated by commas and
the data types char and date are enclosed in apostrophes. The values must be entered in the same
order as they are defined.
2. SELECT
It is used to retrieve information from the table.it is generally referred to as querying the
table. We can either display all columns in a table or only specify columns from the table.
3. UPDATE
It is used to alter the column values in a table. A single column may be updated or more
than one column could be updated.
4. DELETE
After inserting rows in a table we can also delete them if required. The delete command
consists of a from clause followed by an optional where clause

PROCEDURE
INSERT COMMAND
(a) Inserting a single row into a table:
Syntax:
insert into <table name> values (<expression1>,<expression2>)
(b) Inserting more than one record using a single insert commands:
Syntax:
insert into <table name> values(<expression1>,<expression2>
...), (<expression1>,<expression2> ...)
( c) Skipping the fields while inserting:
Insert into <tablename>(<column name1>,<column name3>)> values
(<expression1>,<expression3>);

GPTC, Chelakkara Department of Computer Engineering


11 Database Management System Lab

Another way is to give null while passing the values.


SELECT COMMAND
(a) view all rows and all columns
Syntax:
Select * from table_name;
(b)Selected Columns And All Rows
Syntax:
Select <column1>,<column2> from tablename;
(c) Selected Columns And selected Rows
Syntax:
SELECT <column1>, <column2> FROM <tablename> WHERE
<condition> ;
(c)Eliminating duplicate rows
Syntax:
SELECT DISTINCT <column1>, <column2> FROM <tablename>
UPDATE COMMAND
(b)updating all rows
Syntax:
update tablename set columnname1> = <exprssion1>, <columnname2>
= <exprssion2>;
(b)updating records conditionally
Syntax:
update tablename set field=values where condition;
DELETE COMMAND
(b)Removal of all rows
Syntax:
Delete from <table name> ;
(b)removal of specific rows
Syntax:
Delete from <table name> where <condition>;
Problems
1. Insert the following data into their respective tables.
Data for CLIENT_MASTER table
ClientNo Name Address1 Address2 City Pincode State BalDue
C00001 Ivan ABC Gandi Mumbai 400054 Maharashtra 15000
Nivas Nagar
C00002 Ashwini X1/234 Gandi Chennai 780001 TamilNadu 0
Sreet
C00003 Joshi JOSI SIVAJI Mangalore 560001 Karnataka 5000
Bavan NAGAR

GPTC, Chelakkara Department of Computer Engineering


12 Database Management System Lab

C00004 Deepak DD Indira Chennai 780001 TamilNadu 0


NIVAS Nagar
C00005 Sharma SS Bavan Jothis Mumbai 400054 Maharashtra 2000
Road

Data for PRODUCT_MASTER table


Product Description Profit Unit qtyonhand ReorderLvl sellprice costprice
No Percent Measure
P00001 Tshirt 5 Piece 200 10 350 250
P00065 Shirt 6 Piece 150 15 500 350
P00032 Jeans 5 Piece 100 5 600 450
P00324 Skirts 4 Piece 120 10 750 500
P02345 CottonJeans 3 Piece 80 5 850 550

3. Data for SALESMAN_MASTER table


Salesmanno Salesman Address1 Address2 city Pincode State Salary
Name
S00001 Aman A/4 Parapahalli Mangalore 400002 Karnataka 4500
S00002 Omkar 65 Nariman Mumbai 400001 Maharashtra 3000
S00003 Raj P-7 Tnagar Chennai 400032 Thamilnadu 6000
S00004 Ashish A/5 Juhu Mumbai 400044 Maharashtra 3500

4. Exercise on retrieving records from a table


a. Find out the names of all clients
b. Retrieve the entire contents of the Client _master table
c. Retrieve the list of names,city and the state of all the clients
d. List the various products available from the Product _Master table
e. List all the clients who are located in Mumbai
f. Find the names of salesmen who have a salary equal to Rs.3000
5. Exercise on updating the records on a table
a. Change the city of ClientNo’C00005’ to ‘Bangaluru’.
b. Change the BalDue of ClientNo’C00001’ to Rs.1000.
c. Change the costprice of ‘Shirt ‘ to Rs.450.
d. Change the city of salesmen to Pune.
6. Exercise on deleting the records in a table
a. Delete all salesmen from the Salesman_master whose salaries are equal to Rs.3500.
b. Delete all sproducts from the Product_master where quantity on hand is equal to 100
c. Delete from the Client_master where the column state holds the value ‘Tamilnadu’.
RESULT
The DML commands are executed successfully.

GPTC, Chelakkara Department of Computer Engineering


13 Database Management System Lab

EXPERIMENT NO 4
SELECT COMMAND WITH WHERE, DISTINCT, BETWEEN, ORDER BY, IN, LIKE
Experiment Outcomes
M1.04 Experiment with WHERE, DISTINCT, BETWEEN, ORDER BY, IN, LIKE, set
operations in SELECT statements for data retrieval from the databases

AIM:
To experiment different clauses using SELECT SQL Command.
OBJECTIVES
To understand SELECT Command clauses.
THEORY
Simple SELECT Syntax
The SELECT statement allows you to retrive data records from one or more tables. To write a
SELECT statement in MySQL, you use this syntax:
SELECT select_list FROM table_name;
Where select_list is multiple columns, you need to separate them by a comma.
Second, specify the name of the table from which you want to select data after the
FROM keyword.
There is a list of clauses used with the SELECT clause, such as DISTINCT, ORDER BY,
WHERE, UNION, INTERSECT, MINUS etc. We also use some operator with WHERE clause
of SELECT statement such as IN, LIKE and BETWEEN
SELECT Statement with more clauses :
SELECT [ ALL | DISTINCT ]
Filed_List
FROM tables
[WHERE conditions]
[GROUP BY expressions]
[HAVING condition]
[ORDER BY expression [ ASC | DESC ]]

PROCEDURE
SELECT DISTINCT
When querying data from a table, you may get duplicate rows. To remove these duplicate
rows, you use the DISTINCT clause in the SELECT statement. the syntax of the DISTINCT
clause:
SELECT DISTINCT select_list FROM table_name;
ORDER BY
To sort the rows in the result set of SELECT Command, you add the ORDER BY clause to the
SELECT statement.
The following illustrates the syntax of the ORDER BY clause:

GPTC, Chelakkara Department of Computer Engineering


14 Database Management System Lab

SELECT
select_list
FROM
table_name
ORDER BY
column1 [ASC|DESC],
column2 [ASC|DESC],
...;
BETWEEEN
The BETWEEN operator is a logical operator that specifies whether a value is in a range
or not. Here’s the syntax of the BETWEEN operator:
SELECT select_list FROM table_name WHERE fieldname BETWEEN low AND
high;
NOT BETWEEN
To negate the BETWEEN operator, you use the NOT operator:
SELECT select_list FROM table_name WHERE fieldname NOT BETWEEN low AND high
IN Operator
The IN operator allows you to determine if a value matches any value in a list of values.
Here’s the syntax of the IN operator:
SELECT select_list FROM table_name WHERE fieldname IN (value1, value2, value3,...)
The IN operator returns 1 (true) if the value equals any value in the list (value1, value2,
value3,…). Otherwise, it returns 0.
LIKE
The LIKE operator is a logical operator that tests whether a string contains a specified
pattern or not.
Here’s the syntax of the LIKE operator:
expression LIKE pattern ESCAPE escape_character
In this syntax, if the expression matches the pattern, the LIKE operator returns 1. Otherwise, it
returns 0.
MySQL provides two wildcard characters for constructing patterns: percentage % and
underscore _
The percentage ( % ) wildcard matches any string of zero or more characters.
The underscore ( _ ) wildcard matches any single character.
Use the NOT operator to negate the LIKE operator.
Typically, you’ll use the LIKE,IN and BETWEEN operator in the WHERE clause of the
SELECT , DELETE, and UPDATE statement.
SET OPERATIONS - UNION, INTERSECT and MINUS
To combine result set of two or more queries using the SET operators, these are the basic rules
that you must follow:

GPTC, Chelakkara Department of Computer Engineering


15 Database Management System Lab

First, the number and the orders of columns that appear in all SELECT statements must be the
same.
Second, the data types of columns must be the same or compatible.
By default, the SET operators removes duplicate rows even if you don’t specify the DISTINCT
operator explicitly.

UNION
MySQL UNION operator allows you to combine two or more result sets of queries into a single
result set. The following illustrates the syntax of the UNION operator:
SELECT column_list
UNION [DISTINCT | ALL]
SELECT column_list
UNION [DISTINCT | ALL]
SELECT column_list
INTERSECT
An INTERSECT query returns the intersection of 2 or more datasets. If a record exists in both
data sets, it will be included in the INTERSECT results. However, if a record exists in one data
set and not in the other, it will be omitted from the INTERSECT results.
The following illustrates the syntax of the INTERSECT operator.
(SELECT column_list
FROM table_1)
INTERSECT
(SELECT column_list
FROM table_2);
MINUS
The MINUS compares the results of two queries and returns distinct rows from the result set of
the first query that does not appear in the result set of the second query.
The following illustrates the syntax of the MINUS operator:
SELECT select_list1
FROM table_name1
MINUS
SELECT select_list2
FROM table_name2;

Problems
1. Insert the following data into their respective tables.
Data for CLIENT_MASTER table
ClientNo Name Address1 Address2 City Pincode State BalDue
C00001 Ivan ABC Gandi Mumbai 400054 Maharashtra 15000
Nivas Nagar

GPTC, Chelakkara Department of Computer Engineering


16 Database Management System Lab

C00002 Ashwini X1/234 Gandi Chennai 780001 TamilNadu 0


Sreet
C00003 Joshi JOSI SIVAJI Mangalore 560001 Karnataka 5000
Bavan NAGAR
C00004 Deepak DD Indira Chennai 780001 TamilNadu 0
NIVAS Nagar
C00005 Sharma SS Bavan Jothis Mumbai 400054 Maharashtra 2000
Road
C0006 Arun Nair Puthuman MG Road COchin 6743343 Kerala 1000
a

Data for PRODUCT_MASTER table


Product Description Profit Unit qtyonhand ReorderLvl sellprice costprice
No Percent Measure
P00001 Tshirt 5 Piece 200 10 350 250
P00065 Shirt 6 Piece 150 15 500 350
P00032 Jeans 5 Piece 100 5 600 450
P00324 Skirts 4 Piece 120 10 750 500
P02345 CottonJeans 3 Piece 80 5 850 550

3. Data for SALESMAN_MASTER table


Salesmanno Salesman Address1 Address2 city Pincode State Salary
Name
S00001 Aman A/4 Parpahalli Mangalore 400002 Karnataka 4500
S00002 Omkar 65 Nariman Mumbai 400001 Maharashtra 3000
S00003 Raj P-7 Tnager Chennai 400032 Thamilnadu 6000
S00004 Ashish A/5 Juhu Mumbai 400044 Maharashtra 3500

4. Exercise on retrieving records from a table


a. List all Cities of Salesman's without duplicate values.
b. List products which in stock between the quantity 100 and 200
c. List salesman’s man name who have salary between 3000 and 5000
d. List all Clients from Mumbai and Chennai
e. List Salesman’s details who are not from Karnataka and Tamilnadu
f. List all Salesman’s details whose name starts with letter “A”
g. List all Clients whose name ends with letter “I”
h. List all Salesmans details whose State name’s Second letter is “A”
j. List all Slasesman’s and Clients Names
k. List all Clients and Salesmen city names who are from the same city.
l. List Client States from where no salesman is in the Shop.

GPTC, Chelakkara Department of Computer Engineering


17 Database Management System Lab

m. List all salesman Details in the ascending order of their salary


n. List all Client Details in the descending order of their balance due.

RESULT
The SELECT command with its different clauses executed successfully.

GPTC, Chelakkara Department of Computer Engineering


18 Database Management System Lab

EXPERIMENT NO:5
Aggregate Functions and GROUP by clause
AIM:
M2.01 Identify aggregate functions -SUM, AVG, COUNT, MIN, MAX - GROUP BY and
HAVING clause

OBJECTIVES
To understand aggregation done on data of the given table with built in functions and summarize
the data using GROUP BY clause

THEORY
The SQL 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 GROUP BY clause is used in the
SELECT statement .Optionally it is used in conjunction with aggregate functions to produce
summary reports from the database. The queries that contain the GROUP BY clause are called
grouped queries and only return a single row for every grouped item. We often use aggregate
functions with the GROUP BY and HAVING clauses of the SELECT statement.
The ORDER BY Clause can be used along with the SELECT statement to sort the data of
specific fields in an ordered way. It is used to sort the result-set in ascending or descending order.

PROCEDURE
The basic syntax of the Order By clause is –

GROUP BY Syntax
SELECT statements... GROUP BY column_name1[,column_name2,...] [HAVING condition];
"GROUP BY column_name1" is the clause that performs the grouping based on olumn_name1.
"[,column_name2,...]" is optional; it represents other column names when the grouping is done
on more than one column. [HAVING condition]is optional; it is used to restrict the rows affected
by the GROUP BY clause. It is similar to the WHERE clause.
Group Functions/Aggregate functions A group function returns a result based on a group of
rows. Aggregate Functions are all about Performing calculations on multiple rows of a single
column of a table and returning a single value.
The following are the most commonly used SQL aggregate functions:
AVG – calculates the average of a set of values.
COUNT – counts rows in a specified table or view.
MIN – gets the minimum value in a set of values.
MAX – gets the maximum value in a set of values.
SUM – calculates the sum of values.
PROBLEM

GPTC, Chelakkara Department of Computer Engineering


19 Database Management System Lab

1.Write SQL statements to perform the following computations on table


data. a) List the name of Clients in ascending order
b) Find the average balance due of client from each city
c) Find the maximum balance due of clients from Mumbai
d) Find the number of clients from Tamil Nadu
e) Find the number of products in the store
f) Find the maximum, minimum and average cost price of Products
g) Find the average profit percentage of products
h) List the name and address of Salesman in descending order of their salary
i) Find the average salary of employee from each pincode
j) Find the maximum salary of employee from mumbai
k) Find the number of Salesman from Bandra
l) Find the average salary of salesman whose name starts with the letter ‘a’

Result
The GROUP BY clause and aggregate functions implemented successfully

GPTC, Chelakkara Department of Computer Engineering


20 Database Management System Lab

EXPERIMENT NO:6
Nested Queries
Experiment Outcome
M2.02 Develop nested queries

AIM:
To implement different ways of joining database tables

THEORY
a)Nested/Sub QUERIES:
A subquery is a SQL query nested inside a larger query.
A subquery may occur in:
- A SELECT clause
- A FROM clause
- A WHERE clause
In MySQL subquery can be nested inside a SELECT, INSERT, UPDATE, DELETE, SET, or
DO statement or inside another subquery. A subquery is usually added within the WHERE
Clause of another SQL SELECT statement.
You can use the comparison operators, such as >, <, or =. The comparison operator can also be
a multiple-row operator, such as IN, ANY, SOME, or ALL.
A subquery can be treated as an inner query, which is a SQL query placed as a part of another
query called an outer query.
The inner query executes first before its parent query so that the results of the inner query can be
passed to the outer query

Procedure
Mainly two types of subqueries : single row subquery & multiple row or multiset subquery
Syntax :
SELECT <fieldlist> FROM <tablename> WHERE < attribute LIKE / = / IN / ALL / ANY
subquery >

Problems
Exercise : Practice the given subqueries by considering the following employee
table & department table.
Empid Empname Dept Desig Gender Basicpay

101 Anil 2001 Manager M 30000

102 Latha 2003 Accountant F 25000

GPTC, Chelakkara Department of Computer Engineering


21 Database Management System Lab

103 Venu 2001 Engineer M 28000

104 Kiran 2002 Salesman M 10000

105 Karthika 2003 Clerk F 10000

106 Rema 2001 Engineer F 29000

107 Jaya 2003 Clerk F 11000

108 Pranav 2002 Sales manager M 40000

109 Geetha 2003 Purchase Manager F 42000

DeptID Deptname mgrID

2001 Administration 101

2002 Sales 108

2003 Purchase 109

Q1: Display the name & salary of employees whose salary is greater than the the salary of
employee with empid = 105
Q2: Display the name, salary, department number, designation of employees whose designation
is same as the designation of empid 105.
Q3: Display the name and salary of highest salaried employee
Q4: Display departments whose average salary is below the average salary of the entire
organization
Q5: Write a query to find the highest earning employee in each department
Q6: Write a query to list the departments which do not have employees at all

RESULT : Nested queries are executed successfully

GPTC, Chelakkara Department of Computer Engineering


22 Database Management System Lab

EXPERIMENT NO:7
Joins
Experiment Outcome
M2.03 Develop SQL queries for inner and outer joins.

AIM:
To implement different ways of joining database tables

THEORY
SQL allows us to join rows from two or more tables based on the value of one or more
common fields . A JOIN condition on the common field is evaluated for selecting the
matching rows.
Syntax of SELECT command with JOIN clause

SELECT <field list>


FROM < table 1 > JOIN <table 2>
ON <join condition> ;
Foreign Key
A foreign key is a field in a table that matches another field of another table. A foreign key
places constraints on data in the related tables, which enables it to maintain referential integrity.

PROCEDURE
Different types of JOIN
1. INNER JOIN ( JOIN ) :- This is the default type of JOIN. In inner join operation, a tuple
from table-1 is included in the result only if a matching or related tuple exists in table-2
The syntax for the INNER JOIN in MySQL is:
SELECT columns
FROM table1
INNER JOIN table2
ON table1.column = table2.column;
2. OUTER JOIN :- Outer joins are used when the user wants to keep all the tuples in table 1,
or all those in table 2, or all tuples in both relations in the result of JOIN, regardless of whether
or not they have matching tuples in the other relation.
There are three types of OUTER JOIN :
i. LEFT OUTER JOIN : Here every tuple from the left table must appear in the result.If it
does not have a matching tuple, it is padded with NULL values for the attributes in the right
table
The syntax for the LEFT OUTER JOIN in MySQL is:

GPTC, Chelakkara Department of Computer Engineering


23 Database Management System Lab

SELECT columns
FROM table1
LEFT [OUTER] JOIN table2
ON table1.column = table2.column;
ii. RIGHT OUTER JOIN : Every tuple from the right table must appear in the result.
The syntax for the RIGHT OUTER JOIN in MySQL is:
SELECT columns
FROM table1
RIGHT [OUTER] JOIN table2
ON table1.column = table2.column;
iii. FULL OUTER JOIN : All tuples from both tables will appear and NULL values will be
filled for attributes of other table which does not have matching tuple
SELECT columns
FROM table1
LEFT [OUTER] JOIN table2
ON table1.column = table2.column UNION
SELECT columns
FROM table1
RIGHT [OUTER] JOIN table2
ON table1.column = table2.column;
Natural Join
Natural Join in MYSQL is a Join operation used in the SELECT query, to retrieve rows from
two or more tables with a common column name. We need to make sure the common column
has the same data type, in both the tables.
The syntax of natural join is
SELECT columns
FROM table1
NATURAL JOIN table2;
The essential syntax for a foreign key constraint definition in a CREATE TABLE or ALTER
TABLE statement is
[CONSTRAINT [symbol]] FOREIGN KEY
[index_name] (col_name, ...)
REFERENCES tbl_name (col_name,...)
[ON DELETE reference_option]
[ON UPDATE reference_option]

Problem
Consider an Institution database with tables a) student( adno numeric(4), studname

GPTC, Chelakkara Department of Computer Engineering


24 Database Management System Lab

vaarchar(15), courseid numeric(2)) b) courses ( courseid numeric(2), coursetitle archar(15))


A sample database state is given below:
Student
Adno Studname Courseid

101 Sunil 10

102 Vidya 10

103 Renuka NULL

104 Varghese 40

105 Mohammed 30

106 Fatima 40
107 Lawrence 60

Courses
CourseI Coursetitle Category Fees
D

10 C-Programming SW 2000

20 OOP-Java SW 5000

30 DBMS-mySql SW 3500

40 Python SW 5000

50 Assembling HW 2500
60 Networking HW 6000

Write appropriate queries for the following questions by joining the tables student & course
Q1: List details of students who are joined for a course along with their
coursetitle
Q2: List details of all students even if they are not joined for a course
Q3: Retrieve details of all courses even if no one has enrolled for the
course
Q4: Count number of students enrolled for each course

GPTC, Chelakkara Department of Computer Engineering


25 Database Management System Lab

Q5: List all records in both tables regardless of any match


Q6: Display CourseID, CourseTitle, Category, Fees and student names for Software courses
with Fees less than 5000

RESULT : Queries for joining tables are executed successfully

GPTC, Chelakkara Department of Computer Engineering


26 Database Management System Lab

EXPERIMENT NO:8
VIEWS
AIM:
To create and drop View on the given table.

OBJECTIVES
To implement views

THEORY
A view is the tailored presentation of data contained in one or more tables and can also
be said as a restricted view to the data‟s in the tables. 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 a 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 .
Advantages of a view:
a. Additional level of table security.
b. Hides data complexity.
c. Simplifies the usage by combining multiple tables into a single table

Pocedure
To create or replace a view the CREATE OR REPLACE view statement is used.
Syntax:
Create or replace view view_name AS
SELECT column_name(s)
FROM table_name
WHERE condition
Drop view <view name>;

A view is deleted with the DROP VIEW command.


SQL DROP VIEW Syntax
DROP VIEW view_name;

Problem
1. Create a view with order number, customer name and purchase amount
2. Create a view with Order number, salesman name and purchase amount for the month of
october
3. Create a view with Order number, orderdate, customer name, salesman name and purchase
amount for the orders which purchase amount greater than 1000

GPTC, Chelakkara Department of Computer Engineering


27 Database Management System Lab

4. list all item from the views


5. Delete the first created view

Result
Thus the view creation commands are executed successfully

GPTC, Chelakkara Department of Computer Engineering


28 Database Management System Lab

EXPERIMENT NO:9
STORED PROCEDURE

Experiment outcomes
M3.01 Experiment with stored procedures for simple tasks

AIM:
To practice how to create procedures DBMS

OBJECTIVES
To write and understand stored procedures in SQL.

THEORY
Stored PROCEDURE
A stored procedure is a segment of declarative SQL statements stored inside the database
catalog. A stored procedure can be invoked by triggers, other stored procedures, and applications
such as Java, Python, PHP.

PROCEDURE

Syntax of CREATE PROCEDURE


CREATE
PROCEDURE sp_name ([proc_parameter[,...]])
routine_body

proc_parameter: [ IN | OUT | INOUT ] param_name type


type: Any valid MySQL data type
routine_body:
Valid SQL routine statement

To declare a variable inside a stored procedure, you use the DECLARE statement as follows:
DECLARE variable_name datatype(size) DEFAULT default_value;
To initialize a value while declaring DEFAULT is used and assign a variable another value, you
use the SET statement, for example:
DECLARE total_count INT DEFAULT 0;
SET total_count = 10;

IF statement allows you to execute a set of SQL statements based on a certain condition or value
of an expression.
IF expression THEN

GPTC, Chelakkara Department of Computer Engineering


29 Database Management System Lab

statements;
ELSEIF elseif-expression THEN
elseif-statements;
...
ELSE
else-statements;
END IF;
Different loop statements are

The syntax of the WHILEstatement is as follows:

WHILE expression DO
statements
END WHILE

The syntax of the REPEAT loop statement is as follows:

REPEAT
statements;
UNTIL expression
END REPEAT

LOOP, LEAVE and ITERATE statements


The LEAVEstatement allows you to exit the loop immediately without waiting for checking the
condition. The ITERATEstatement allows you to skip the entire code under it and start a new
iteration. MySQL also gives you a LOOPstatement that executes a block of code repeatedly with
an additional flexibility of using a loop label.

Problems
1) procedure to find whether a given number is odd or even

GPTC, Chelakkara Department of Computer Engineering


30 Database Management System Lab

2) procedure to display 1-10 using while

4) Procedure to List contents of Product Master Table

GPTC, Chelakkara Department of Computer Engineering


31 Database Management System Lab

Result
Stored Procedures Created and executed

GPTC, Chelakkara Department of Computer Engineering


32 Database Management System Lab

EXPERIMENT NO:10
STORED FUNCTIONS
Experiment outcomes
M3.01 Experiment with stored functions for simple tasks

AIM:
To practice how to create functions in DBMS

OBJECTIVES
To write and understand Functions in SQL.

THEORY
Stored FUNCTION
Stored function is a special kind of stored program that returns a single value. You use stored
functions to encapsulate common formulas or business rules that are reusable among SQL
statements or stored programs. Different from a stored procedure, you can use a stored function
in SQL statements wherever an expression is used. This helps improve the readability and
maintainability of the procedural code.

PROCEDURE

Syntax of CREATE FUNCTION

CREATE FUNCTION function_name(func_parameter1, func_parameter2, ..)


RETURN datatype
func_body
To declare a variable inside a stored procedure, you use the DECLARE statement as follows:
DECLARE variable_name datatype(size) DEFAULT default_value;
To initialize a value while declaring DEFAULT is used and assign a variable another value, you
use the SET statement, for example:
DECLARE total_count INT DEFAULT 0;
SET total_count = 10;

IF statement allows you to execute a set of SQL statements based on a certain condition or value
of an expression.
IF expression THEN
statements;
ELSEIF elseif-expression THEN
elseif-statements;
...

GPTC, Chelakkara Department of Computer Engineering


33 Database Management System Lab

ELSE
else-statements;
END IF;
Different loop statements are

The syntax of the WHILEstatement is as follows:

WHILE expression DO
statements
END WHILE

The syntax of the REPEAT loop statement is as follows:

REPEAT
statements;
UNTIL expression
END REPEAT

LOOP, LEAVE and ITERATE statements


The LEAVEstatement allows you to exit the loop immediately without waiting for checking the
condition. The ITERATEstatement allows you to skip the entire code under it and start a new
iteration. MySQL also gives you a LOOPstatement that executes a block of code repeatedly with
an additional flexibility of using a loop label.

Problems
1) Function to find Factorial of a number

GPTC, Chelakkara Department of Computer Engineering


34 Database Management System Lab

2) function to find average mark of a student whose roll number is given

GPTC, Chelakkara Department of Computer Engineering


35 Database Management System Lab

Result
Stored function created and tested successfully

GPTC, Chelakkara Department of Computer Engineering


36 Database Management System Lab

EXPERIMENT NO: 11
CURSOR

Experiment outcomes
M3.03 Experiment with cursors for database operations

AIM
To retrieve all students who have registered for Diploma and store their details into another table
called diploma (id,name) using cursors.

OBJECTIVES
To implement cursor

THEORY
A cursor allows you to iterate a set of rows returned by a query and process each row
accordingly. MySQL cursor is read-only, non-scrollable and asensitive.

PROCEDURE
To declare a cursor by using the DECLARE statement:
DECLARE cursor_name CURSOR FOR SELECT_statement;
open the cursor by using the OPEN statement. The OPEN statement initializes the result set for
the cursor, therefore, you must call the OPEN statement before fetching rows from the result set.
OPEN cursor_name;
Then, you use the FETCH statement to retrieve the next row pointed by the cursor and move the
cursor to the next row in the result set.
FETCH cursor_name INTO variables list;
Finally, you call the CLOSE statement to deactivate the cursor
CLOSE cursor_name;

PROBLEMS
1) Create Table Students(sid,sname, science, mathematics, language) and one table to store total
mark totalmark(sid,total)
Write a Stored Procedure using cursors to calculate the total mark of each student and insert a
record in the totalmark table as well.

GPTC, Chelakkara Department of Computer Engineering


37 Database Management System Lab

2) Create students table


name programme
rohan diploma
anu MA

GPTC, Chelakkara Department of Computer Engineering


38 Database Management System Lab

robert diploma
tom btech
sunny diploma

To retrieve all students who have registered for Diploma and store their details into another table
called diploma (id,name) using cursors.

GPTC, Chelakkara Department of Computer Engineering


39 Database Management System Lab

RESULT
The procedure with the cursor has been executed successfully.

GPTC, Chelakkara Department of Computer Engineering


40 Database Management System Lab

EXPERIMENT NO: 12
TRIGGER

AIM
To develop and execute SQL Trigger

OBJECTIVES
To develop and execute a Trigger for Before and After update/Delete/Insert
operations on a table

THEORY.
A SQL trigger is a set of SQL statements stored in the database catalog. A SQL trigger is
executed or fired whenever an event associated with a table occurs e.g., insert, update or delete.
A SQL trigger is a special type of stored procedure, it is not called directly like a stored
procedure. The main difference between a trigger and a stored procedure is that a trigger is called
automatically when a data modification event is made against a table whereas a stored procedure
must be called explicitly.

PROCEDURE
In order to create a new trigger, you use the CREATE TRIGGER statement.
CREATE TRIGGER trigger_name trigger_time trigger_event
ON table_name
FOR EACH ROW
BEGIN
...
END;
We can define maximum six triggers for each table.
BEFORE INSERT – activated before data is inserted into the table.
AFTER INSERT – activated after data is inserted into the table.
BEFORE UPDATE – activated before data in the table is updated.
AFTER UPDATE – activated after data in the table is updated.
BEFORE DELETE – activated before data is removed from the table.
AFTER DELETE – activated after data is removed from the table.
Problems

1. STUDENTS
Field Type
SID INT(4) PRIMARY KEY

GPTC, Chelakkara Department of Computer Engineering


41 Database Management System Lab

SNAME VARCHAR(30)
PROGRAM VARCHAR(30)
SCIENCE INT(3)
MATEMATICSS INT(3)
LANGUAGE INT(3)

AUDIT_STUDENTS
Field Type
ID INT(4) AUTO_INCREMENT PRIMARY KEY
SID INT(4)
CHANGEDATE DATE
Write a trigger that stores the details of CT students when the data get updated

2. Write a trigger to validate the marks field such that mark should be less than or equal to 100
while insert into the Students table.

GPTC, Chelakkara Department of Computer Engineering


42 Database Management System Lab

RESULT:
Triggers created and tested successfully

GPTC, Chelakkara Department of Computer Engineering

You might also like