SlideShare a Scribd company logo
1 of 56
Download to read offline
Database Management System (KCS-551) Lab Manual
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
Vandana Tripathi A. P (BBDITM C. S. E) Page 1 of 56
DATABASE MANAGEMENT SYSTEM
(KCS-551)
LABORATORY MANUAL
B.TECH, 3rd
Year, Semester - V
COMPUTER SCIENCE
&
ENGINEERING
Database Management System (KCS-551) Lab Manual
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
Vandana Tripathi A. P (BBDITM C. S. E) Page 2 of 56
MANUAL CONTENTS
This manual is intended for the 3rd
year students of Computer Science & Engineering in
the subject of Database Management System (Using MySQL). This manual typically
contains practical/lab sessions related Database Management System implemented using
MySQL covering various aspects related the subject to enhanced understanding.
Students are advised to thoroughly go through this manual rather than only topics
mentioned in the syllabus as practical aspects are the key to understanding and conceptual
visualization of theoretical aspects covered in the books.
Good Luck for your Enjoyable Laboratory Sessions
HOD, CSE
Database Management System (KCS-551) Lab Manual
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
Vandana Tripathi A. P (BBDITM C. S. E) Page 3 of 56
PREFACE
This manual is designed in accordance to the new syllabus (2022-23) prescribed by
A.K.T.U. for the Fifth Semester Database Management System Laboratory.
This practical manual will be helpful for students of Computer Science & Engineering for
understanding the course from the point of view of applied aspects. Though all the efforts
have been made to make this manual error free, yet some errors might have crept in
inadvertently. Suggestions from the readers for the improvement of the manual are most
welcomed.
Vision of the Institute
“To become a leading institute of providing professionally competent and socially responsive
technocrats with high moral values."
Mission of the Institute
M1. To create an eco-system for the dissemination of technical knowledge, to achieve
academic excellence.
M2. To develop technocrats with creative skills and leadership qualities, to solve local and
global challenges.
M3. To impart human values and ethics in students, to make them socially and eco-friendly
responsible.
Database Management System (KCS-551) Lab Manual
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
Vandana Tripathi A. P (BBDITM C. S. E) Page 4 of 56
Vision of the Department
“To produce globally competent professionals having social values and commitment to serve
the global needs with the ability to work in an interdisciplinary environment."
Mission of the Department
M1. "To impart quality education to the students to enhance their ethical, professional and
leadership qualities to make them globally competitive."
M2. "To create a conducive environment in which students can explore computational
problems and analyze them to identify the optimal solutions."
M3. "To strive for continual enhancement of technical knowledge & innovation through
industry interface to accomplish global needs."
Program Educational Objectives (PEOs)
PEO1: Students must be able to apply software engineering principles to analyze complex
computing problems and identify their solutions.
PEO2: Students must be able to analyze, design, and implement the latest technology-driven
projects.
PEO3: Students must be able to work in a collaborative environment and understand the
ethical, social, and economic impact of their work.
Program Outcomes (POs)
PO’s An Engineering Graduate of the Department of Computer Science and Engineering
Program will be able to demonstrate:
PO1 ENGINEERING KNOWLEDGE: Apply the knowledge of mathematics, including
discrete mathematics, probability, statistics and fundamentals of various engineering disciplines
like computer science and engineering, electronic engineering and Electrical engineering in the
core information technologies.
PO2 PROBLEM ANALYSIS: Analyze a problem and identify the computing requirements
appropriate to its solution.
Database Management System (KCS-551) Lab Manual
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
Vandana Tripathi A. P (BBDITM C. S. E) Page 5 of 56
PO3 DESIGN/DEVELOPMENT OF SOLUTIONS: Design and implement hardware and
software systems, components, process or program to meet the desired needs within reasonable
economic, environmental, social, political, ethical, health and safety, manufacturability, and
sustainability constraints.
PO4 CONDUCT INVESTIGATIONS OF COMPLEX PROBLEMS: Reassess literature and
indulge in research to use research-based knowledge and methods to design and conduct new
experiments, as well as to organize, analyze and interpret data to produce draw valid
Conclusions and recommendations.
PO5 MODERN TOOL USAGE: Use appropriate techniques, resources, and modern
engineering and IT tools necessary for computer engineering practice.
PO6 THE ENGINEER AND SOCIETY: Show the understanding of local and global impact
of computing on individuals, organizations and society.
PO7 ENVIRONMENT AND SUSTAINABILITY: Integrate IT-based solutions in
environmental contexts, and demonstrate the knowledge of need for sustainable development.
PO8 ETHICS: Demonstrate the knowledge of professional and ethical responsibilities along
with the norms of the engineering practice.
PO9 INDIVIDUAL AND TEAM WORK: Demonstrate leadership and an ability to work as a
member with responsibility to function on multi-disciplinary teams to accomplish a common
goal.
PO10 COMMUNICATION: Demonstrate effectively communicate skills in both oral and
written form with a range of audiences.
PO11 PROJECT MANAGEMENT AND FINANCE: Apply the knowledge and understanding
of engineering and management principles to design, planned budget and propose IT project for
an identified need within a specific scope.
PO12 LIFE-LONG LEARNING: Developed confidence to acquire new knowledge in the
computing discipline and to engage in life-long learning.
Program Specific Outcomes (PSOs)
PSO 1: Able to design and implement the data structures and algorithms to deliver quality
software products.
PSO 2: Able to apply Artificial Intelligence and Machine Learning concepts to solve society-
related needs.
Database Management System (KCS-551) Lab Manual
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
Vandana Tripathi A. P (BBDITM C. S. E) Page 6 of 56
Course Outcomes (COs)
CO’s Statement
Bloom’s
Knowledge
Level (KL)
CO1 To implement ER diagram and different types of DDL, DML and DCL
queries.
L3
CO2 To implement different Normalization forms NF1, NF2, etc. L3
CO 3 To implement programs using different procedures, functions, packages,
cursor etc.
L3
CO 4 To design and implement payroll processing system, library information
system.
L4
CO 5 To design and implement a procedure which generate all the prime numbers
and mini project.
L4
Database Management System (KCS-551) Lab Manual
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
Vandana Tripathi A. P (BBDITM C. S. E) Page 7 of 56
INDEX
S. No. Name of the Experiment CO BTL
Virtual Lab Link/ Source for
Conduction of Experiment*
1.
Installing MySQL/Oracle and creating
Entity-Relationship Diagram.
1 L4
https://www.youtube.com/watch?v=EHF
bk_6ThAQ
https://www.youtube.com/watch?v=2fPP
_u_Nzyw
2.
WrWrite the queries for Data Definition and
Data Manipulation Language.
2 L3
http://vlabs.iitb.ac.in/vlabs-
dev/labs/dblab/labs/exp3/index.php
3.
Write SQL queries using SQL operators
and logical operations (=,<,>,etc) 2 L3
http://vlabs.iitb.ac.in/vlabs-
dev/labs/dblab/labs/exp3/index.php
4.
Write SQL queries using Aggregate
Functions 2 L3
http://vlabs.iitb.ac.in/vlabs-
dev/labs/dblab/labs/exp3/index.php
5.
a.riWrite SQL queries for relational algebra.
b.Write SQL queries for extracting data
from more than one table.
2 L4
https://www.youtube.com/watch?v=o7Np
5bHtc2w
http://vlabs.iitb.ac.in/vlabs-
dev/labs/dblab/labs/exp3/index.php
6.
Write SQL queries for sub queries, nested
queries.
3 L5
https://www.youtube.com/watch?v=miT
O-dCgJpo
7.
Write program by the use of PL/SQL. 3 L4
https://www.youtube.com/watch?v=J5wjI
f4gdq4&list=PLWPirh4EWFpHj0kKqqY
udPNOrGEa0fFIr
Database Management System (KCS-551) Lab Manual
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
Vandana Tripathi A. P (BBDITM C. S. E) Page 8 of 56
8.
Concepts for ROLL BACK, COMMIT &
CHECK POINTS.
4 L4
https://www.youtube.com/watch?v=Li6B
jT_W8W8
9.
Creating Procedure and Functions in
Oracle. 5 L4
https://www.youtube.com/watch?v=Pxlj5
bZW3xw
10.
Creating Cursor and Trigger in Oracle. 5 L4
https://www.youtube.com/watch?v=KGE
y1j-CzaY
https://www.youtube.com/watch?v=nfpe
N0_SPmM
Database Management System (KCS-551) Lab Manual
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
Vandana Tripathi A. P (BBDITM C. S. E) Page 9 of 56
INTRODUCTION
Aims
The aim of this course is to design database using data modelling techniques and its logical
implementation using MySQL , which encourages a different solve real problems that are
suited to this style. Practical experimentation with the language is strongly encouraged.
Course Objectives
At the end of the course, students will be able to:
1 To Explain basic database concepts, applications, data models, schemas and instances.
2 To Demonstrate the use of constraints and relational algebra operations. IV. Describe the
basbasics of SQL and construct queries using SQL
3 To emphasize the importance of normalization in databases.
Database Management System (KCS-551) Lab Manual
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
Vandana Tripathi A. P (BBDITM C. S. E) Page 10 of 56
Aim - Installing MySQL/Oracle and creating Entity-Relationship Diagram.
Content: Installation steps for MySQL:
• Download MySQL from https://dev.mysql.com/downloads/mysql/
Installing MySQL on Windows: Your downloaded MySQL is neatly packaged with an
installer. Download the installer package, unzip it anywhere and run setup.exe. By default,
this process will install everything under C:mysql
Verify MySQL installation:
Step 1 : Open from start
Step 2 : enter the password you have set during installation .
Babu Banarasi Das Institute of Technology & Management, Lucknow
LAB MANUAL
Course Name: Database Management System Lab Experiment No. 1
Course Code: KCS 551 Branch: CSE Semester: V
Database Management System (KCS-551) Lab Manual
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
Vandana Tripathi A. P (BBDITM C. S. E) Page 11 of 56
• Step-3 : if you already have created data bases then use them else create new database.
•
Creating Entity-Relationship Diagram
Consider following databases and draw ER diagram and convert entities and relationships to
relation table for a given scenario.
1. COLLEGE DATABASE: STUDENT (USN, SName, Address, Phone, Gender) SEMSEC
(SSID, Sem, Sec) CLASS (USN, SSID) SUBJECT (Subcode, Title, Sem, Credits)
IAMARKS (USN, Subcode, SSID, Test1, Test2, Test3, FinalIA)
2. COMPANY DATABASE: EMPLOYEE (SSN, Name, Address, Sex, Salary, SuperSSN,
DNo) DEPARTMENT (DNo, DName, MgrSSN, MgrStartDate) DLOCATION (DNo,DLoc)
PROJECT (PNo, PName, PLocation, DNo) WORKS_ON (SSN, PNo, Hours)
Database Management System (KCS-551) Lab Manual
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
Vandana Tripathi A. P (BBDITM C. S. E) Page 12 of 56
College Database: E-R Diagram
Database Management System (KCS-551) Lab Manual
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
Vandana Tripathi A. P (BBDITM C. S. E) Page 13 of 56
COMPANY DATABASE:
Database Management System (KCS-551) Lab Manual
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
Vandana Tripathi A. P (BBDITM C. S. E) Page 14 of 56
Database Management System (KCS-551) Lab Manual
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
Vandana Tripathi A. P (BBDITM C. S. E) Page 15 of 56
Aim: Write the queries for Data Definition and Data Manipulation Language.
Types of SQL Commands
There are five types of SQL commands: DDL, DML, DCL, TCL, and DQL.
1. Data Definition Language (DDL)
o DDL changes the structure of the table like creating a table, deleting a table, altering a
table, etc.
o All the command of DDL are auto-committed that means it permanently save all the
changes in the database.
Here are some commands that come under DDL:
o CREATE
o ALTER
o DROP
o TRUNCATE
a. CREATE It is used to create a new table in the database.
Syntax:
1. CREATE TABLE TABLE_NAME (COLUMN_NAME DATATYPES[,....]);
Example:
1. CREATE TABLE EMPLOYEE(Name VARCHAR2(20), Email VARCHAR2(100), DOB D
ATE);
b. DROP: It is used to delete both the structure and record stored in the table.
Syntax
Babu Banarasi Das Institute of Technology & Management, Lucknow
LAB MANUAL
Course Name: Database Management System Lab Experiment No. 2
Course Code: KCS 551 Branch: CSE Semester: V
Database Management System (KCS-551) Lab Manual
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
Vandana Tripathi A. P (BBDITM C. S. E) Page 16 of 56
1. DROP TABLE table_name;
Example
1. DROP TABLE EMPLOYEE;
c. ALTER: It is used to alter the structure of the database. This change could be either to
modify the characteristics of an existing attribute or probably to add a new attribute.
Syntax:
To add a new column in the table
1. ALTER TABLE table_name ADD column_name COLUMN-definition;
To modify existing column in the table:
1. ALTER TABLE table_name MODIFY(column_definitions....);
EXAMPLE
1. ALTER TABLE STU_DETAILS ADD(ADDRESS VARCHAR2(20));
2. ALTER TABLE STU_DETAILS MODIFY (NAME VARCHAR2(20));
d. TRUNCATE: It is used to delete all the rows from the table and free the space containing
the table.
Syntax:
1. TRUNCATE TABLE table_name;
Example:TRUNCATE TABLE EMPLOYEE;
2. Data Manipulation Language
o DML commands are used to modify the database. It is responsible for all form of
changes in the database.
o The command of DML is not auto-committed that means it can't permanently save all
the changes in the database. They can be rollback.
Database Management System (KCS-551) Lab Manual
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
Vandana Tripathi A. P (BBDITM C. S. E) Page 17 of 56
o INSERT
o UPDATE
o DELETE
a. INSERT: The INSERT statement is a SQL query. It is used to insert data into the row of a
table.
Syntax:
1. INSERT INTO TABLE_NAME
2. (col1, col2, col3,.... col N)
3. VALUES (value1, value2, value3, .... valueN);
For example:
1. INSERT INTO javatpoint (Author, Subject) VALUES ("Sonoo", "DBMS");
b. UPDATE: This command is used to update or modify the value of a column in the table.
Syntax:
1. UPDATE table_name SET [column_name1= value1,...column_nameN = valueN] [WHERE
CONDITION]
For example:
1. UPDATE students
2. SET User_Name = 'Sonoo'
3. WHERE Student_Id = '3'
c. DELETE: It is used to remove one or more row from a table.
Syntax:
1. DELETE FROM table_name [WHERE condition];
For example:
1. DELETE FROM javatpoint
2. WHERE Author="Sonoo";
Database Management System (KCS-551) Lab Manual
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
Vandana Tripathi A. P (BBDITM C. S. E) Page 18 of 56
Aim - Write SQL queries using SQL operators and logical operations (=,<,>,etc)
Content - SQL Arithmetic Operators:
SQL Bitwise Operators
Operator Description
& Bitwise AND
| Bitwise OR
^ Bitwise exclusive OR
SQL Comparison Operators
Operator Description
Babu Banarasi Das Institute of Technology & Management, Lucknow
LAB MANUAL
Course Name: Database Management System Lab Experiment No. 3
Course Code: KCS 551 Branch: CSE Semester: V
Database Management System (KCS-551) Lab Manual
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
Vandana Tripathi A. P (BBDITM C. S. E) Page 19 of 56
= Equal to
> Greater than
< Less than
>= Greater than or equal to
<= Less than or equal to
<> Not equal to
SQL Logical Operators
Operator Description Example
ALL TRUE if all of the subquery values meet the condition
AND TRUE if all the conditions separated by AND is TRUE
Database Management System (KCS-551) Lab Manual
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
Vandana Tripathi A. P (BBDITM C. S. E) Page 20 of 56
ANY TRUE if any of the subquery values meet the condition
BETWEEN TRUE if the operand is within the range of comparisons
EXISTS TRUE if the subquery returns one or more records
IN TRUE if the operand is equal to one of a list of
expressions
LIKE TRUE if the operand matches a pattern
NOT Displays a record if the condition(s) is NOT TRUE
OR TRUE if any of the conditions separated by OR is TRUE
SOME TRUE if any of the subquery values meet the condition
Database Management System (KCS-551) Lab Manual
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
Vandana Tripathi A. P (BBDITM C. S. E) Page 21 of 56
Aim - Write SQL query using character, number, date and group functions
Content - Character functions accept character inputs and can return either characters
or number values as output. SQL provides a number of different character datatypes which
includes – CHAR, VARCHAR, VARCHAR2, LONG, RAW, and LONG RAW. The
various datatypes are categorized into three different datatypes :
1. VARCHAR2 – A variable-length character datatype whose data is converted by the
RDBMS.
2. CHAR – The fixed-length datatype.
3. RAW – A variable-length datatype whose data is not converted by the RDBMS, but left
in “raw” form.
Character Functions
SQL provides a rich set of character functions that allow you to get information
about strings and modify the contents of those strings in multiple ways. Character
functions are of the following two types:
1. Case-Manipulative Functions (LOWER, UPPER and INITCAP)
2. Character-Manipulative Functions (CONCAT, LENGTH, SUBSTR, INSTR,
LPAD, RPAD, TRIM and REPLACE)
Case-Manipulative Functions
1. LOWER : This function converts alpha character values to lowercase. LOWER will
actually return a fixed-length string if the incoming string is fixed-length. LOWER will
not change any characters in the string that are not letters, since case is irrelevant for
numbers and special characters, such as the dollar sign ( $ ) or modulus ( % ).
Syntax:
LOWER(SQL course)
Input1: SELECT LOWER('GEEKSFORGEEKS') FROM DUAL;
Output1: geeksforgeeks
Input2: SELECT LOWER('DATABASE@456') FROM DUAL;
Output2: database@456
2. UPPER : This function converts alpha character values to uppercase. Also UPPER
function too, will actually return a fixed-length string if the incoming string is fixed-
length. UPPER will not change any characters in the string that are not letters, since
case is irrelevant for numbers and special characters, such as the dollar sign ( $ ) or
modulus ( % ).
Syntax:
Babu Banarasi Das Institute of Technology & Management, Lucknow
LAB MANUAL
Course Name: Database Management System Lab Experiment No. 4
Course Code: KCS 551 Branch: CSE Semester: V
Database Management System (KCS-551) Lab Manual
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
Vandana Tripathi A. P (BBDITM C. S. E) Page 22 of 56
UPPER(SQL course)
Input1: SELECT UPPER('geeksforgeeks') FROM DUAL;
Output1: GEEKSFORGEEKS
Input2: SELECT UPPER('dbms$508%7') FROM DUAL;
Output2: DBMS$508%7
3. INITCAP : This function converts alpha character values to uppercase for the first
letter of each word and all others in lowercase. The words in the string is must be
separated by either # or _ or space.
Syntax:
INITCAP(SQL course)
Input1: SELECT INITCAP('geeksforgeeks is a computer science portal for geeks')
FROM DUAL;
Output1: Geeksforgeeks Is A Computer Science Portal For Geeks
Input2: SELECT INITCAP('PRACTICE_CODING_FOR_EFFICIENCY') FROM
DUAL;
Output2: Practice_Coding_For_Efficiency
Character-Manipulative Functions
1. CONCAT : This function always appends ( concatenates ) string2 to the end of string1.
If either of the string is NULL, CONCAT function returns the non-NULL argument. If
both strings are NULL, CONCAT returns NULL.
Syntax:
CONCAT('String1', 'String2')
Input1: SELECT CONCAT('computer' ,'science') FROM DUAL;
Output1: computerscience
Input2: SELECT CONCAT( NULL ,'Android') FROM DUAL;
Output2: Android
Input3: SELECT CONCAT( NULL ,NULL ) FROM DUAL;
Output3: -
2. LENGTH : This function returns the length of the input string. If the input string is
NULL, then LENGTH function returns NULL and not Zero. Also, if the input string
contains extra spaces at the start, or in between or at the end of the string, then the
LENGTH function includes the extra spaces too and returns the complete length of the
string.
Syntax:
LENGTH(Column|Expression)
Input1: SELECT LENGTH('Learning Is Fun') FROM DUAL;
Output1: 15
Database Management System (KCS-551) Lab Manual
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
Vandana Tripathi A. P (BBDITM C. S. E) Page 23 of 56
Input2: SELECT LENGTH(' Write an Interview Experience ') FROM DUAL;
Output2: 34
Input3: SELECT LENGTH('') FROM DUAL; or SELECT LENGTH( NULL ) FROM
DUAL;
Output3: -
3. SUBSTR : This function returns a portion of a string from a given start point to an end
point. If a substring length is not given, then SUBSTR returns all the characters till the
end of string (from the starting position specified).
Syntax:
SUBSTR('String',start-index,length_of_extracted_string)
Input1: SELECT SUBSTR('Database Management System', 9) FROM DUAL;
Output1: Management System
Input2: SELECT SUBSTR('Database Management System', 9, 7) FROM DUAL;
Output2: Manage
4. INSTR : This function returns numeric position of a character or a string in a given
string. Optionally, you can provide a position m to start searching, and the
occurrence n of string. Also, if the starting position is not given, then it starts search
from index 1, by default. If after searching in the string, no match is found then, INSTR
function returns 0.
Syntax: INSTR(Column|Expression, 'String', [,m], [n])
Input: SELECT INSTR('Google apps are great applications','app',1,2) FROM DUAL;
Output: 23
5. LPAD and RPAD : These functions return the strings padded to the left or right ( as
per the use ) ; hence the “L” in “LPAD” and the “R” in “RPAD” ; to a specified length,
and with a specified pad string. If the pad string is not specified, then the given string is
padded on the left or right ( as per the use ) with spaces.
Syntax:
6. LPAD(Column|Expression, n, 'String')
Syntax: RPAD(Column|Expression, n, 'String')
LPAD Input1: SELECT LPAD('100',5,'*') FROM DUAL;
LPAD Output1: **100
LPAD Input2: SELECT LPAD('hello', 21, 'geek') FROM DUAL;
LPAD Output2: geekgeekgeekgeekhello
RPAD Input1: SELECT RPAD('5000',7,'*') FROM DUAL;
RPAD Output1: 5000***
RPAD Input1: SELECT RPAD('earn', 19, 'money') FROM DUAL;
RPAD Output1: earnmoneymoneymoney
Database Management System (KCS-551) Lab Manual
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
Vandana Tripathi A. P (BBDITM C. S. E) Page 24 of 56
7. TRIM : This function trims the string input from the start or end (or both). If no string
or char is specified to be trimmed from the string and there exists some extra space at
start or end of the string, then those extra spaces are trimmed off.
Syntax:
TRIM(Leading|Trailing|Both, trim_character FROM trim_source)
Input1: SELECT TRIM('G' FROM 'GEEKS') FROM DUAL;
Output1: EEKS
Input2: SELECT TRIM(' geeksforgeeks ') FROM DUAL;
Output2:geeksforgeeks
8. REPLACE : This function searches for a character string and, if found, replaces it with
a given replacement string at all the occurrences of the string. REPLACE is useful for
searching patterns of characters and then changing all instances of that pattern in a
single function call.
If a replacement string is not given, then REPLACE function removes all the
occurrences of that character string in the input string. If neither a match string nor a
replacement string is specified, then REPLACE returns NULL.
Syntax:
REPLACE(Text, search_string, replacement_string)
Input1: SELECT REPLACE('DATA MANAGEMENT', 'DATA','DATABASE')
FROM DUAL;
Output1: DATABASE MANAGEMENT
Input2: SELECT REPLACE('abcdeabcccabdddeeabcc', 'abc') FROM DUAL;
Output2: deccabdddeec
Database Management System (KCS-551) Lab Manual
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
Vandana Tripathi A. P (BBDITM C. S. E) Page 25 of 56
Aim – a. Write SQL queries for relational algebra.
b.Write SQL queries for extracting data from more than one table.
Content - SQL JOIN
A JOIN clause is used to combine rows from two or more tables, based on a related column
between them.
Let's look at a selection from the "Orders" table:
OrderID CustomerID OrderDate
10308 2 1996-09-18
10309 37 1996-09-19
10310 77 1996-09-20
Babu Banarasi Das Institute of Technology & Management, Lucknow
LAB MANUAL
Course Name: Database Management System Lab Experiment No. 5
Course Code: KCS 551 Branch: CSE Semester: V
Database Management System (KCS-551) Lab Manual
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
Vandana Tripathi A. P (BBDITM C. S. E) Page 26 of 56
Then, look at a selection from the "Customers" table:
CustomerID CustomerName ContactName Country
1 Alfreds Futterkiste Maria Anders Germany
2 Ana Trujillo Emparedados y helados Ana Trujillo Mexico
3 Antonio Moreno Taquería Antonio Moreno Mexico
Notice that the "CustomerID" column in the "Orders" table refers to the "CustomerID" in the
"Customers" table. The relationship between the two tables above is the "CustomerID"
column.
Then, we can create the following SQL statement (that contains an INNER JOIN), that
selects records that have matching values in both tables:
Example
SELECT Orders.OrderID, Customers.CustomerName, Orders.OrderDate
FROM Orders
INNER JOIN Customers ON Orders.CustomerID=Customers.CustomerID;
Output-
OrderID CustomerName OrderDate
10308 Ana Trujillo Emparedados y
helados
9/18/1996
Database Management System (KCS-551) Lab Manual
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
Vandana Tripathi A. P (BBDITM C. S. E) Page 27 of 56
10365 Antonio Moreno Taquería 11/27/1996
10383 Around the Horn 12/16/1996
10355 Around the Horn 11/15/1996
10278 Berglunds snabbköp 8/12/1996
Different Types of SQL JOINs
Here are the different types of the JOINs in SQL:
• (INNER) JOIN: Returns records that have matching values in both tables
• LEFT (OUTER) JOIN: Returns all records from the left table, and the matched
records from the right table
• RIGHT (OUTER) JOIN: Returns all records from the right table, and the matched
records from the left table
• FULL (OUTER) JOIN: Returns all records when there is a match in either left or right
table
Database Management System (KCS-551) Lab Manual
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
Vandana Tripathi A. P (BBDITM C. S. E) Page 28 of 56
Database Management System (KCS-551) Lab Manual
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
Vandana Tripathi A. P (BBDITM C. S. E) Page 29 of 56
Aim - Write SQL queries for extracting data from more than one table and for sub queries,
nested queries.
Content –
Creating a subquery to retrieve data from more than one table
When you need to include in your WHERE clause selection criteria that only exists in
another table, you can add subqueries to a SQL statement to retrieve the values that satisfy
the condition. A subquery is a complete query that appears in the WHERE or HAVING
clause of an SQL statement.
Rules for creating a subquery
• Enclose the subquery in parentheses.
• Specify only one column or expression in a subquery unless you are using IN, ANY,
ALL, or EXISTS.
• A subquery cannot contain a BETWEEN or LIKE clause.
• A subquery cannot contain an ORDER BY clause.
• A subquery in an UPDATE statement cannot retrieve data from the same table in
which data is to be updated.
• A subquery in a DELETE statement cannot retrieve data from the same table in which
data is to be deleted.
The following query displays the names and IDs of employees who work in Boston. The
subquery (in parentheses) finds the department number for the location of BOSTON in the
Q.ORG table. Then the main query selects the names of the employees in that department
from the Q.STAFF table.
SELECT NAME, ID
FROM Q.STAFF
WHERE DEPT=(SELECT DEPTNUMB
FROM Q.ORG
WHERE LOCATION='BOSTON')
In the next example, the subquery and main query retrieve data from the same table. The
subquery calculates the average salary for all the employees in the Q.STAFF table. Then, the
Babu Banarasi Das Institute of Technology & Management, Lucknow
LAB MANUAL
Course Name: Database Management System Lab Experiment No. 6
Course Code: KCS 551 Branch: CSE Semester: V
Database Management System (KCS-551) Lab Manual
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
Vandana Tripathi A. P (BBDITM C. S. E) Page 30 of 56
main query selects the salespeople whose salaries are equal to or greater than the average
salary.
SELECT ID, NAME, SALARY
FROM Q.STAFF
WHERE JOB = 'SALES' AND
SALARY >= (SELECT AVG(SALARY)
FROM Q.STAFF)
Retrieving more than one value with a subquery
Usually a subquery selects only one column and returns only one value to the query.
However, you can create a subquery that uses the ANY or ALL keywords with comparison
operators (=, ¬=, >, >=, <, or <=) to return a particular set of values. In addition, just as you
use the IN keyword in place of multiple OR statements in a query, you can also use IN in
place of the ANY keyword in a subquery.
The query in the following figure selects any employee who works in the Eastern division.
The subquery finds the department numbers in the Eastern division, and then the main query
selects the employees who work in any of these departments.
Use the ANY keyword for this query, because it is likely that the subquery will find more
than one department in the Eastern division. If you use the ALL keyword instead of the ANY
keyword, no data is selected because no employee works in all departments of the Eastern
division.
This SQL query contains a subquery that uses the ANY keyword.
SELECT NAME, ID
FROM Q.STAFF
WHERE DEPT = ANY
(SELECT DEPTNUMB
FROM Q.ORG
WHERE DIVISION='EASTERN')
The query in the following figure selects the department with the highest average salary. The
subquery finds the average salary for each department, and then the main query selects the
department with the highest average salary.
Use the ALL keyword for this subquery. The department selected by the query must have an
average salary greater than or equal to all the average salaries of the other departments.
. This SQL query contains a subquery using the ALL keyword.
Database Management System (KCS-551) Lab Manual
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
Vandana Tripathi A. P (BBDITM C. S. E) Page 31 of 56
SELECT DEPT, AVG(SALARY)
FROM Q.STAFF
GROUP BY DEPT
HAVING AVG(SALARY) >= ALL
(SELECT AVG(SALARY)
FROM Q.STAFF
GROUP BY DEPT)
The query in following figure selects all salespeople (and their salaries) who work for
managers earning more than $20,000 a year. The subquery finds the managers who earn more
than $20,000 a year, and the main query selects the salespeople who work for those
managers.
Use the IN keyword for this subquery because you need to find values from more than one
department.
This SQL query contains a subquery using the IN keyword.
SELECT ID, NAME, SALARY
FROM Q.STAFF
WHERE JOB = 'SALES'
AND DEPT IN
(SELECT DISTINCT DEPT
FROM Q.STAFF
WHERE JOB = 'MGR'
AND SALARY > 20000)
You can also specify NOT IN in a subquery to select information from one table when
corresponding information does not exist in the other table.
Checking for rows that satisfy a condition
Not only can you use a subquery to return a value to the query, you can also use a WHERE
EXISTS clause in a subquery to check for rows that satisfy a certain row condition.
The query in the following figure selects employees from the Q.STAFF table who have a
salary of less than $14,000 and who work in a department where at least one other employee
with the same job earns a salary greater than $14,000. (The subquery checks for other
employees in the department with the same job, but who earn a salary greater than $14,000
This subquery checks for rows that satisfy a condition.
SELECT NAME, DEPT, JOB, SALARY
Database Management System (KCS-551) Lab Manual
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
Vandana Tripathi A. P (BBDITM C. S. E) Page 32 of 56
FROM Q.STAFF S
WHERE S.SALARY < 14000 AND
EXISTS (SELECT * FROM Q.STAFF
WHERE S.DEPT=DEPT AND SALARY >14000
AND S.JOB=JOB)
ORDER BY S.DEPT
Specifying a correlation name in a subquery
You can specify a correlation name in a subquery to use a condition to evaluate every row
retrieved by the main query.
The query in the following figure selects the department, name, and salary of the employees
who have the highest salary in their departments. The subquery calculates the maximum
salary for each department that is selected by the main query. The correlation name, Y,
compares each row that is selected by the query to the maximum salary that is calculated for
the department in the subquery.
This subquery specifies a correlation name.
SELECT DEPT, NAME, SALARY
FROM Q.STAFF Y
WHERE SALARY = (SELECT MAX (SALARY)
FROM Q.STAFF
WHERE DEPT = Y.DEPT)
Database Management System (KCS-551) Lab Manual
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
Vandana Tripathi A. P (BBDITM C. S. E) Page 33 of 56
Aim - Write program by the use of PL/SQL.
Content –
PL/SQL
PL/SQL is a block structured language. The programs of PL/SQL are logical blocks that can
contain any number of nested sub-blocks. Pl/SQL stands for "Procedural Language extension
of SQL" that is used in Oracle. PL/SQL is integrated with Oracle database (since version 7).
The functionalities of PL/SQL usually extended after each release of Oracle database.
Although PL/SQL is closely integrated with SQL language, yet it adds some programming
constraints that are not available in SQL.
PL/SQL Functionalities
PL/SQL includes procedural language elements like conditions and loops. It allows
declaration of constants and variables, procedures and functions, types and variable of those
types and triggers. It can support Array and handle exceptions (runtime errors). After the
implementation of version 8 of Oracle database have included features associated with object
orientation. You can create PL/SQL units like procedures, functions, packages, types and
triggers, etc. which are stored in the database for reuse by applications.
With PL/SQL, you can use SQL statements to manipulate Oracle data and flow of control
statements to process the data.
The PL/SQL is known for its combination of data manipulating power of SQL with data
processing power of procedural languages. It inherits the robustness, security, and portability
of the Oracle Database.
PL/SQL is not case sensitive so you are free to use lower case letters or upper case letters
except within string and character literals. A line of PL/SQL text contains groups of
characters known as lexical units. It can be classified as follows:
o Delimeters
o Identifiers
o Literals
o Comment
Babu Banarasi Das Institute of Technology & Management, Lucknow
LAB MANUAL
Course Name: Database Management System Lab Experiment No. 7
Course Code: KCS 551 Branch: CSE Semester: V
Database Management System (KCS-551) Lab Manual
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
Vandana Tripathi A. P (BBDITM C. S. E) Page 34 of 56
PL/SQL - Arrays
In this chapter, we will discuss arrays in PL/SQL. The PL/SQL programming language
provides a data structure called the VARRAY, which can store a fixed-size sequential
collection of elements of the same type. A varray is used to store an ordered collection of
data, however it is often better to think of an array as a collection of variables of the same
type.
All varrays consist of contiguous memory locations. The lowest address corresponds to the
first element and the highest address to the last element.
An array is a part of collection type data and it stands for variable-size arrays. We will study
other collection types in a later chapter 'PL/SQL Collections'.
Each element in a varray has an index associated with it. It also has a maximum size that can
be changed dynamically.
Creating a Varray Type
A varray type is created with the CREATE TYPE statement. You must specify the
maximum size and the type of elements stored in the varray.
The basic syntax for creating a VARRAY type at the schema level is −
CREATE OR REPLACE TYPE varray_type_name IS VARRAY(n) of <element_type>
Where,
• varray_type_name is a valid attribute name,
• n is the number of elements (maximum) in the varray,
• element_type is the data type of the elements of the array.
Maximum size of a varray can be changed using the ALTER TYPE statement.
For example,
CREATE Or REPLACE TYPE namearray AS VARRAY(3) OF VARCHAR2(10);
/
Type created.
Database Management System (KCS-551) Lab Manual
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
Vandana Tripathi A. P (BBDITM C. S. E) Page 35 of 56
The basic syntax for creating a VARRAY type within a PL/SQL block is −
TYPE varray_type_name IS VARRAY(n) of <element_type>
For example −
TYPE namearray IS VARRAY(5) OF VARCHAR2(10);
Type grades IS VARRAY(5) OF INTEGER;
Let us now work out on a few examples to understand the concept −
Example 1
The following program illustrates the use of varrays −
DECLARE
type namesarray IS VARRAY(5) OF VARCHAR2(10);
type grades IS VARRAY(5) OF INTEGER;
names namesarray;
marks grades;
total integer;
BEGIN
names := namesarray('Kavita', 'Pritam', 'Ayan', 'Rishav', 'Aziz');
marks:= grades(98, 97, 78, 87, 92);
total := names.count;
dbms_output.put_line('Total '|| total || ' Students');
FOR i in 1 .. total LOOP
dbms_output.put_line('Student: ' || names(i) || '
Marks: ' || marks(i));
END LOOP;
END;
/
When the above code is executed at the SQL prompt, it produces the following result −
Total 5 Students
Student: Kavita Marks: 98
Student: Pritam Marks: 97
Student: Ayan Marks: 78
Student: Rishav Marks: 87
Student: Aziz Marks: 92
Database Management System (KCS-551) Lab Manual
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
Vandana Tripathi A. P (BBDITM C. S. E) Page 36 of 56
Aim - Concepts for ROLL BACK, COMMIT & CHECK POINTS.
Content –
SQL - Transactions
A transaction is a unit of work that is performed against a database. Transactions are units or
sequences of work accomplished in a logical order, whether in a manual fashion by a user or
automatically by some sort of a database program.
A transaction is the propagation of one or more changes to the database. For example, if you
are creating a record or updating a record or deleting a record from the table, then you are
performing a transaction on that table. It is important to control these transactions to ensure
the data integrity and to handle database errors.
Practically, you will club many SQL queries into a group and you will execute all of them
together as a part of a transaction.
Properties of Transactions
Transactions have the following four standard properties, usually referred to by the
acronym ACID.
• Atomicity − ensures that all operations within the work unit are completed
successfully. Otherwise, the transaction is aborted at the point of failure and all the
previous operations are rolled back to their former state.
• Consistency − ensures that the database properly changes states upon a successfully
committed transaction.
• Isolation − enables transactions to operate independently of and transparent to each
other.
• Durability − ensures that the result or effect of a committed transaction persists in
case of a system failure.
Transaction Control
The following commands are used to control transactions.
• COMMIT − to save the changes.
• ROLLBACK − to roll back the changes.
Babu Banarasi Das Institute of Technology & Management, Lucknow
LAB MANUAL
Course Name: Database Management System Lab Experiment No. 8
Course Code: KCS 551 Branch: CSE Semester: V
Database Management System (KCS-551) Lab Manual
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
Vandana Tripathi A. P (BBDITM C. S. E) Page 37 of 56
• SAVEPOINT − creates points within the groups of transactions in which to
ROLLBACK.
• SET TRANSACTION − Places a name on a transaction.
Transactional Control Commands
Transactional control commands are only used with the DML Commands such as -
INSERT, UPDATE and DELETE only. They cannot be used while creating tables or
dropping them because these operations are automatically committed in the database.
The COMMIT Command
The COMMIT command is the transactional command used to save changes invoked by a
transaction to the database.
The COMMIT command is the transactional command used to save changes invoked by a
transaction to the database. The COMMIT command saves all the transactions to the database
since the last COMMIT or ROLLBACK command.
The syntax for the COMMIT command is as follows.
COMMIT;
Example
Consider the CUSTOMERS table having the following records −
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+-----------+----------+
Following is an example which would delete those records from the table which have age =
25 and then COMMIT the changes in the database.
SQL> DELETE FROM CUSTOMERS
WHERE AGE = 25;
SQL> COMMIT;
Database Management System (KCS-551) Lab Manual
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
Vandana Tripathi A. P (BBDITM C. S. E) Page 38 of 56
Thus, two rows from the table would be deleted and the SELECT statement would produce
the following result.
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+-----------+----------+
The ROLLBACK Command
The ROLLBACK command is the transactional command used to undo transactions that have
not already been saved to the database. This command can only be used to undo transactions
since the last COMMIT or ROLLBACK command was issued.
The syntax for a ROLLBACK command is as follows −
ROLLBACK;
Example
Consider the CUSTOMERS table having the following records −
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+-----------+----------+
Following is an example, which would delete those records from the table which have the age
= 25 and then ROLLBACK the changes in the database.
SQL> DELETE FROM CUSTOMERS
WHERE AGE = 25;
SQL> ROLLBACK;
Thus, the delete operation would not impact the table and the SELECT statement would
produce the following result.
Database Management System (KCS-551) Lab Manual
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
Vandana Tripathi A. P (BBDITM C. S. E) Page 39 of 56
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+-----------+----------+
The SAVEPOINT Command
A SAVEPOINT is a point in a transaction when you can roll the transaction back to a certain
point without rolling back the entire transaction.
The syntax for a SAVEPOINT command is as shown below.
SAVEPOINT SAVEPOINT_NAME;
This command serves only in the creation of a SAVEPOINT among all the transactional
statements. The ROLLBACK command is used to undo a group of transactions.
The syntax for rolling back to a SAVEPOINT is as shown below.
ROLLBACK TO SAVEPOINT_NAME;
Following is an example where you plan to delete the three different records from the
CUSTOMERS table. You want to create a SAVEPOINT before each delete, so that you can
ROLLBACK to any SAVEPOINT at any time to return the appropriate data to its original
state.
Example
Consider the CUSTOMERS table having the following records.
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+-----------+----------+
Database Management System (KCS-551) Lab Manual
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
Vandana Tripathi A. P (BBDITM C. S. E) Page 40 of 56
The following code block contains the series of operations.
SQL> SAVEPOINT SP1;
Savepoint created.
SQL> DELETE FROM CUSTOMERS WHERE ID=1;
1 row deleted.
SQL> SAVEPOINT SP2;
Savepoint created.
SQL> DELETE FROM CUSTOMERS WHERE ID=2;
1 row deleted.
SQL> SAVEPOINT SP3;
Savepoint created.
SQL> DELETE FROM CUSTOMERS WHERE ID=3;
1 row deleted.
Now that the three deletions have taken place, let us assume that you have changed your
mind and decided to ROLLBACK to the SAVEPOINT that you identified as SP2. Because
SP2 was created after the first deletion, the last two deletions are undone −
SQL> ROLLBACK TO SP2;
Rollback complete.
Notice that only the first deletion took place since you rolled back to SP2.
SQL> SELECT * FROM CUSTOMERS;
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+-----------+----------+
6 rows selected.
The RELEASE SAVEPOINT Command
The RELEASE SAVEPOINT command is used to remove a SAVEPOINT that you have
created.
The syntax for a RELEASE SAVEPOINT command is as follows.
RELEASE SAVEPOINT SAVEPOINT_NAME;
Database Management System (KCS-551) Lab Manual
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
Vandana Tripathi A. P (BBDITM C. S. E) Page 41 of 56
Once a SAVEPOINT has been released, you can no longer use the ROLLBACK command to
undo transactions performed since the last SAVEPOINT.
The SET TRANSACTION Command
The SET TRANSACTION command can be used to initiate a database transaction. This
command is used to specify characteristics for the transaction that follows. For example, you
can specify a transaction to be read only or read write.
The syntax for a SET TRANSACTION command is as follows.
SET TRANSACTION [ READ WRITE | READ ONLY ];
Database Management System (KCS-551) Lab Manual
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
Vandana Tripathi A. P (BBDITM C. S. E) Page 42 of 56
Aim - Creating Procedure and Functions in MySQL/Oracle
Content -
A stored procedure is a prepared SQL code that you can save, so the code can be reused over
and over again.
So if you have an SQL query that you write over and over again, save it as a stored
procedure, and then just call it to execute it.
You can also pass parameters to a stored procedure, so that the stored procedure can act
based on the parameter value(s) that is passed.
Stored Procedure Syntax
CREATE PROCEDURE procedure_name
AS
sql_statement
GO;
Execute a Stored Procedure
EXEC procedure_name;
The procedure syntax has the following parameters:
MySQL procedure parameter has one of three modes:
IN parameter
It is the default mode. It takes a parameter as input, such as an attribute. When we define it,
the calling program has to pass an argument to the stored procedure. This parameter's value is
always protected.
OUT parameters
Babu Banarasi Das Institute of Technology & Management, Lucknow
LAB MANUAL
Course Name: Database Management System Lab Experiment No. 9
Course Code: KCS 551 Branch: CSE Semester: V
Database Management System (KCS-551) Lab Manual
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
Vandana Tripathi A. P (BBDITM C. S. E) Page 43 of 56
It is used to pass a parameter as output. Its value can be changed inside the stored procedure, and the
changed (new) value is passed back to the calling program. It is noted that a procedure cannot access
the OUT parameter's initial value when it starts.
NOUT parameters
It is a combination of IN and OUT parameters. It means the calling program can pass the argument,
and the procedure can modify the INOUT parameter, and then passes the new value back to the calling
program.
Call a stored procedure:
We can use the CALL statement to call a stored procedure. This statement returns the values to
its caller through its parameters (IN, OUT, or INOUT).
The following syntax is used to call the stored procedure in MySQL:
1. CALL procedure_name ( parameter(s))
Example
Let us understand how to create a procedure in MySQL through example. First, we need to
select a database that will store the newly created procedure. We can select the database
using the below statement:
1. mysql> USE database_name;
Suppose this database has a table named student_info that contains the following data:
Database Management System (KCS-551) Lab Manual
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
Vandana Tripathi A. P (BBDITM C. S. E) Page 44 of 56
Procedure without Parameter
Suppose we want to display all records of this table whose marks are greater than 70 and
count all the table rows. The following code creates a procedure named get_merit_students:
1. DELIMITER &&
2. CREATE PROCEDURE get_merit_student ()
3. BEGIN
4. SELECT * FROM student_info WHERE marks > 70;
5. SELECT COUNT(stud_code) AS Total_Student FROM student_info;
6. END &&
7. DELIMITER ;
If this code executed successfully, we would get the below output:
Database Management System (KCS-551) Lab Manual
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
Vandana Tripathi A. P (BBDITM C. S. E) Page 45 of 56
Let us call the procedure to verify the output:
1. mysql> CALL get_merit_student();
It will give the output as follows:
Procedures with IN Parameter
In this procedure, we have used the IN parameter as 'var1' of integer type to accept a number
from users. Its body part fetches the records from the table using a SELECT statement and
returns only those rows that will be supplied by the user. It also returns the total number of
rows of the specified table. See the procedure code:
volume is gedempt
Database Management System (KCS-551) Lab Manual
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
Vandana Tripathi A. P (BBDITM C. S. E) Page 46 of 56
1. DELIMITER &&
2. CREATE PROCEDURE get_student (IN var1 INT)
3. BEGIN
4. SELECT * FROM student_info LIMIT var1;
5. SELECT COUNT(stud_code) AS Total_Student FROM student_info;
6. END &&
7. DELIMITER ;
After successful execution, we can call the procedure as follows:
1. mysql> CALL get_student(4);
We will get the below output:
Procedures with OUT Parameter
In this procedure, we have used the OUT parameter as the 'highestmark' of integer type. Its body part
fetches the maximum marks from the table using a MAX() function. See the procedure code:
1. DELIMITER &&
2. CREATE PROCEDURE display_max_mark (OUT highestmark INT)
3. BEGIN
4. SELECT MAX(marks) INTO highestmark FROM student_info;
5. END &&
6. DELIMITER ;
Database Management System (KCS-551) Lab Manual
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
Vandana Tripathi A. P (BBDITM C. S. E) Page 47 of 56
This procedure's parameter will get the highest marks from the student_info table. When
we call the procedure, the OUT parameter tells the database systems that its value goes out
from the procedures. Now, we will pass its value to a session variable @M in the CALL
statement as follows:
1. mysql> CALL display_max_mark(@M);
2. mysql> SELECT @M;
Here is the output:
Procedures with INOUT Parameter
In this procedure, we have used the INOUT parameter as 'var1' of integer type. Its body part
first fetches the marks from the table with the specified id and then stores it into the same
variable var1. The var1 first acts as the IN parameter and then OUT parameter.
Therefore, we can call it the INOUT parameter mode. See the procedure code:
1. DELIMITER &&
2. CREATE PROCEDURE display_marks (INOUT var1 INT)
3. BEGIN
4. SELECT marks INTO var1 FROM student_info WHERE stud_id = var1;
Database Management System (KCS-551) Lab Manual
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
Vandana Tripathi A. P (BBDITM C. S. E) Page 48 of 56
5. END &&
6. DELIMITER ;
After successful execution, we can call the procedure as follows:
1. mysql> SET @M = '3';
2. mysql> CALL display_marks(@M);
3. mysql> SELECT @M;
We will get the below output:
Show or list stored procedures in MySQL
When we have several procedures in the MySQL server, it is very important to list all
procedures. It is because sometimes the procedure names are the same in many databases.
In that case, this query is very useful. We can list all procedure stored on the current MySQL server
as follows:
. SHOW PROCEDURE STATUS [LIKE 'pattern' | WHERE search_condition]
This statement displays all stored procedure names, including their characteristics.
Database Management System (KCS-551) Lab Manual
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
Vandana Tripathi A. P (BBDITM C. S. E) Page 49 of 56
If we want to display procedures in a particular database, we need to use the WHERE clause.
In case we want to list stored procedures with a specific word, we need to use the LIKE clause.
We can list all stored procedure in the MySQL mystudentsb database using the below statement:
1. mysql> SHOW PROCEDURE STATUS WHERE db = 'mystudentdb';
It will give the below output where we can see that the mystudentdb database contains
four stored procedures:
Delete/drop stored procedures in MySQL
MySQL also allows a command to drop the procedure. When the procedure is dropped,
it is removed from the database server also. The following statement is used to drop a
stored procedure in MySQL:
1. DROP PROCEDURE [ IF EXISTS ] procedure_name;
Database Management System (KCS-551) Lab Manual
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
Vandana Tripathi A. P (BBDITM C. S. E) Page 50 of 56
Suppose we want to remove the procedure named display_marks from the mystudentdb database.
We can do this by first selecting the database and then use the syntax as follows to remove
the procedure:
1. mysql> DROP PROCEDURE display_marks;
We can verify it by listing the procedure in the specified database using the
SHOW PROCEDURE STATUS command. See the below output:
Alter the procedure in MySQL
MySQL does not allow any command to alter the procedure in MySQL.
However,it provides a command that is used to change the characteristics of a stored procedure.
This command may alter more than one change in the procedure but does not
modify the stored procedure's parameters or body. If we want to make such changes,
we must drop and re-create the procedure using the DROP PROCEDURE and
Database Management System (KCS-551) Lab Manual
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
Vandana Tripathi A. P (BBDITM C. S. E) Page 51 of 56
CREATE PROCEDURE statement.
The below statement is used to change the characteristics of a procedure but not the
actual procedure:
1. ALTER PROCEDURE procedure_name [characteristics ...]
2.
3. characteristics: {
4. COMMENT 'string'
5. | LANGUAGE SQL
6. | { CONTAINS SQL | NO SQL | READS SQL DATA | MODIFIES SQL DATA }
7. | SQL SECURITY { DEFINER | INVOKER }
8. }
Suppose we want to add a comment to the existing procedure. In such a case, we can use
the ALTER statement as follows to accomplish this task:
1. mysql> ALTER PROCEDURE get_merit_student
2. COMMENT 'It displays all records';
After executing this statement, we can verify it by using the below statement:
1. mysql> SHOW CREATE PROCEDURE get_merit_student G;
It will display the below output where we can see that the comment is added successfully.
Database Management System (KCS-551) Lab Manual
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
Vandana Tripathi A. P (BBDITM C. S. E) Page 52 of 56
Database Management System (KCS-551) Lab Manual
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
Vandana Tripathi A. P (BBDITM C. S. E) Page 53 of 56
Aim - Creating Cursor and Trigger in MySQL/Oracle.
Content –
Triggers in PL/SQL. Triggers are stored programs, which are automatically executed or fired
when some events occur. Triggers are, in fact, written to be executed in response to any of the
following events −
• A database manipulation (DML) statement (DELETE, INSERT, or UPDATE)
• A database definition (DDL) statement (CREATE, ALTER, or DROP).
• A database operation (SERVERERROR, LOGON, LOGOFF, STARTUP, or
SHUTDOWN).
Triggers can be defined on the table, view, schema, or database with which the event is
associated.
Benefits of Triggers
Triggers can be written for the following purposes −
• Generating some derived column values automatically
• Enforcing referential integrity
• Event logging and storing information on table access
• Auditing
• Synchronous replication of tables
• Imposing security authorizations
• Preventing invalid transactions
Creating Triggers
The syntax for creating a trigger is −
CREATE [OR REPLACE ] TRIGGER trigger_name
{BEFORE | AFTER | INSTEAD OF }
{INSERT [OR] | UPDATE [OR] | DELETE}
[OF col_name]
ON table_name
[REFERENCING OLD AS o NEW AS n]
[FOR EACH ROW]
WHEN (condition)
DECLARE
Declaration-statements
Babu Banarasi Das Institute of Technology & Management, Lucknow
LAB MANUAL
Course Name: Database Management System Lab Experiment No. 10
Course Code: KCS 551 Branch: CSE Semester: V
Database Management System (KCS-551) Lab Manual
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
Vandana Tripathi A. P (BBDITM C. S. E) Page 54 of 56
BEGIN
Executable-statements
EXCEPTION
Exception-handling-statements
END;
Where,
• CREATE [OR REPLACE] TRIGGER trigger_name − Creates or replaces an existing
trigger with the trigger_name.
• {BEFORE | AFTER | INSTEAD OF} − This specifies when the trigger will be
executed. The INSTEAD OF clause is used for creating trigger on a view.
• {INSERT [OR] | UPDATE [OR] | DELETE} − This specifies the DML operation.
• [OF col_name] − This specifies the column name that will be updated.
• [ON table_name] − This specifies the name of the table associated with the trigger.
• [REFERENCING OLD AS o NEW AS n] − This allows you to refer new and old
values for various DML statements, such as INSERT, UPDATE, and DELETE.
• [FOR EACH ROW] − This specifies a row-level trigger, i.e., the trigger will be
executed for each row being affected. Otherwise the trigger will execute just once
when the SQL statement is executed, which is called a table level trigger.
• WHEN (condition) − This provides a condition for rows for which the trigger would
fire. This clause is valid only for row-level triggers.
Example
To start with, we will be using the CUSTOMERS table we had created and used in the
previous chapters −
Select * from customers;
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
+----+----------+-----+-----------+----------+
The following program creates a row-level trigger for the customers table that would fire for
INSERT or UPDATE or DELETE operations performed on the CUSTOMERS table. This
trigger will display the salary difference between the old values and new values −
CREATE OR REPLACE TRIGGER display_salary_changes
Database Management System (KCS-551) Lab Manual
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
Vandana Tripathi A. P (BBDITM C. S. E) Page 55 of 56
BEFORE DELETE OR INSERT OR UPDATE ON customers
FOR EACH ROW
WHEN (NEW.ID > 0)
DECLARE
sal_diff number;
BEGIN
sal_diff := :NEW.salary - :OLD.salary;
dbms_output.put_line('Old salary: ' || :OLD.salary);
dbms_output.put_line('New salary: ' || :NEW.salary);
dbms_output.put_line('Salary difference: ' || sal_diff);
END;
/
When the above code is executed at the SQL prompt, it produces the following result −
Trigger created.
The following points need to be considered here −
• OLD and NEW references are not available for table-level triggers, rather you can use
them for record-level triggers.
• If you want to query the table in the same trigger, then you should use the AFTER
keyword, because triggers can query the table or change it again only after the initial
changes are applied and the table is back in a consistent state.
• The above trigger has been written in such a way that it will fire before any DELETE
or INSERT or UPDATE operation on the table, but you can write your trigger on a
single or multiple operations, for example BEFORE DELETE, which will fire
whenever a record will be deleted using the DELETE operation on the table.
Triggering a Trigger
Let us perform some DML operations on the CUSTOMERS table. Here is one INSERT
statement, which will create a new record in the table −
INSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY)
VALUES (7, 'Kriti', 22, 'HP', 7500.00 );
When a record is created in the CUSTOMERS table, the above create
trigger, display_salary_changes will be fired and it will display the following result −
Old salary:
New salary: 7500
Salary difference:
Database Management System (KCS-551) Lab Manual
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
Vandana Tripathi A. P (BBDITM C. S. E) Page 56 of 56
Because this is a new record, old salary is not available and the above result comes as null.
Let us now perform one more DML operation on the CUSTOMERS table. The UPDATE
statement will update an existing record in the table −
UPDATE customers
SET salary = salary + 500
WHERE id = 2;
When a record is updated in the CUSTOMERS table, the above create
trigger, display_salary_changes will be fired and it will display the following result −
Old salary: 1500
New salary: 2000
Salary difference: 500

More Related Content

What's hot

System programmin practical file
System programmin practical fileSystem programmin practical file
System programmin practical fileAnkit Dixit
 
systems programming lab programs in c
systems programming lab programs in csystems programming lab programs in c
systems programming lab programs in cMeghna Roy
 
Lecture6 introduction to data streams
Lecture6 introduction to data streamsLecture6 introduction to data streams
Lecture6 introduction to data streamshktripathy
 
Naive bayesian classification
Naive bayesian classificationNaive bayesian classification
Naive bayesian classificationDr-Dipali Meher
 
Design and Develop SQL DDL statements which demonstrate the use of SQL objec...
 Design and Develop SQL DDL statements which demonstrate the use of SQL objec... Design and Develop SQL DDL statements which demonstrate the use of SQL objec...
Design and Develop SQL DDL statements which demonstrate the use of SQL objec...bhavesh lande
 
Operating system support in distributed system
Operating system support in distributed systemOperating system support in distributed system
Operating system support in distributed systemishapadhy
 
Python For Data Science Cheat Sheet
Python For Data Science Cheat SheetPython For Data Science Cheat Sheet
Python For Data Science Cheat SheetKarlijn Willems
 
Line drawing algo.
Line drawing algo.Line drawing algo.
Line drawing algo.Mohd Arif
 
COMPUTER GRAPHICS LAB MANUAL
COMPUTER GRAPHICS LAB MANUALCOMPUTER GRAPHICS LAB MANUAL
COMPUTER GRAPHICS LAB MANUALVivek Kumar Sinha
 
01 knapsack using backtracking
01 knapsack using backtracking01 knapsack using backtracking
01 knapsack using backtrackingmandlapure
 
EX-6-Implement Matrix Multiplication with Hadoop Map Reduce.pptx
EX-6-Implement Matrix Multiplication with Hadoop Map Reduce.pptxEX-6-Implement Matrix Multiplication with Hadoop Map Reduce.pptx
EX-6-Implement Matrix Multiplication with Hadoop Map Reduce.pptxvishal choudhary
 
All-Reduce and Prefix-Sum Operations
All-Reduce and Prefix-Sum Operations All-Reduce and Prefix-Sum Operations
All-Reduce and Prefix-Sum Operations Syed Zaid Irshad
 
Cyrus beck line clipping algorithm
Cyrus beck line clipping algorithmCyrus beck line clipping algorithm
Cyrus beck line clipping algorithmPooja Dixit
 
Computer graphics lab report with code in cpp
Computer graphics lab report with code in cppComputer graphics lab report with code in cpp
Computer graphics lab report with code in cppAlamgir Hossain
 
Data Structures Practical File
Data Structures Practical File Data Structures Practical File
Data Structures Practical File Harjinder Singh
 
Naming And Binding (Distributed computing)
Naming And Binding (Distributed computing)Naming And Binding (Distributed computing)
Naming And Binding (Distributed computing)Sri Prasanna
 
Job sequencing with deadlines(with example)
Job sequencing with deadlines(with example)Job sequencing with deadlines(with example)
Job sequencing with deadlines(with example)Vrinda Sheela
 
Recovery with concurrent transaction
Recovery with concurrent transactionRecovery with concurrent transaction
Recovery with concurrent transactionlavanya marichamy
 

What's hot (20)

System programmin practical file
System programmin practical fileSystem programmin practical file
System programmin practical file
 
systems programming lab programs in c
systems programming lab programs in csystems programming lab programs in c
systems programming lab programs in c
 
Lecture6 introduction to data streams
Lecture6 introduction to data streamsLecture6 introduction to data streams
Lecture6 introduction to data streams
 
Naive bayesian classification
Naive bayesian classificationNaive bayesian classification
Naive bayesian classification
 
Computer Graphics
Computer GraphicsComputer Graphics
Computer Graphics
 
Design and Develop SQL DDL statements which demonstrate the use of SQL objec...
 Design and Develop SQL DDL statements which demonstrate the use of SQL objec... Design and Develop SQL DDL statements which demonstrate the use of SQL objec...
Design and Develop SQL DDL statements which demonstrate the use of SQL objec...
 
Operating system support in distributed system
Operating system support in distributed systemOperating system support in distributed system
Operating system support in distributed system
 
Python For Data Science Cheat Sheet
Python For Data Science Cheat SheetPython For Data Science Cheat Sheet
Python For Data Science Cheat Sheet
 
Line drawing algo.
Line drawing algo.Line drawing algo.
Line drawing algo.
 
COMPUTER GRAPHICS LAB MANUAL
COMPUTER GRAPHICS LAB MANUALCOMPUTER GRAPHICS LAB MANUAL
COMPUTER GRAPHICS LAB MANUAL
 
01 knapsack using backtracking
01 knapsack using backtracking01 knapsack using backtracking
01 knapsack using backtracking
 
EX-6-Implement Matrix Multiplication with Hadoop Map Reduce.pptx
EX-6-Implement Matrix Multiplication with Hadoop Map Reduce.pptxEX-6-Implement Matrix Multiplication with Hadoop Map Reduce.pptx
EX-6-Implement Matrix Multiplication with Hadoop Map Reduce.pptx
 
dbms lab manual
dbms lab manualdbms lab manual
dbms lab manual
 
All-Reduce and Prefix-Sum Operations
All-Reduce and Prefix-Sum Operations All-Reduce and Prefix-Sum Operations
All-Reduce and Prefix-Sum Operations
 
Cyrus beck line clipping algorithm
Cyrus beck line clipping algorithmCyrus beck line clipping algorithm
Cyrus beck line clipping algorithm
 
Computer graphics lab report with code in cpp
Computer graphics lab report with code in cppComputer graphics lab report with code in cpp
Computer graphics lab report with code in cpp
 
Data Structures Practical File
Data Structures Practical File Data Structures Practical File
Data Structures Practical File
 
Naming And Binding (Distributed computing)
Naming And Binding (Distributed computing)Naming And Binding (Distributed computing)
Naming And Binding (Distributed computing)
 
Job sequencing with deadlines(with example)
Job sequencing with deadlines(with example)Job sequencing with deadlines(with example)
Job sequencing with deadlines(with example)
 
Recovery with concurrent transaction
Recovery with concurrent transactionRecovery with concurrent transaction
Recovery with concurrent transaction
 

Similar to Data base management system LAB MANUAL KCS 551.pdf

CS8461 Operating System Lab Manual S.Selvi
CS8461 Operating System Lab Manual S.SelviCS8461 Operating System Lab Manual S.Selvi
CS8461 Operating System Lab Manual S.SelviSELVI SIVAPERUMAL
 
vtu data structures lab manual bcs304 pdf
vtu data structures lab manual bcs304 pdfvtu data structures lab manual bcs304 pdf
vtu data structures lab manual bcs304 pdfLPSChandana
 
SE LAB MANUAL (R16).pdf
SE LAB MANUAL (R16).pdfSE LAB MANUAL (R16).pdf
SE LAB MANUAL (R16).pdfSRPatel10
 
Database management system lLABMANUALpdf
Database management system lLABMANUALpdfDatabase management system lLABMANUALpdf
Database management system lLABMANUALpdfBhagyavantRajapure
 
OS lab manual1234512345123451234512345.pdf
OS lab manual1234512345123451234512345.pdfOS lab manual1234512345123451234512345.pdf
OS lab manual1234512345123451234512345.pdfSuperBoy40
 
Accelerated Prototyping of Cyber Physical Systems in an Incubator Context
Accelerated Prototyping of Cyber Physical Systems in an Incubator ContextAccelerated Prototyping of Cyber Physical Systems in an Incubator Context
Accelerated Prototyping of Cyber Physical Systems in an Incubator ContextSreyas Sriram
 
SDL-LAB-MANUAL-CS606-common-for-all-the-faculties.pdf
SDL-LAB-MANUAL-CS606-common-for-all-the-faculties.pdfSDL-LAB-MANUAL-CS606-common-for-all-the-faculties.pdf
SDL-LAB-MANUAL-CS606-common-for-all-the-faculties.pdfpriyanshuurkade
 
R2017 Syllabus anna university 2017 .pdf
R2017 Syllabus anna university 2017 .pdfR2017 Syllabus anna university 2017 .pdf
R2017 Syllabus anna university 2017 .pdfAishwaryaGiridev
 
1 18CS54 _Software Engineering and Testing _Introduction to CO PO _Syllabus ...
1  18CS54 _Software Engineering and Testing _Introduction to CO PO _Syllabus ...1  18CS54 _Software Engineering and Testing _Introduction to CO PO _Syllabus ...
1 18CS54 _Software Engineering and Testing _Introduction to CO PO _Syllabus ...Jayanthi Kannan MK
 
Futuristic knowledge management ppt bec bagalkot mba
Futuristic knowledge management ppt bec bagalkot mbaFuturistic knowledge management ppt bec bagalkot mba
Futuristic knowledge management ppt bec bagalkot mbaBabasab Patil
 
B tech information technology syllabus - MITAOE
B tech information technology syllabus - MITAOEB tech information technology syllabus - MITAOE
B tech information technology syllabus - MITAOEMITAcademy1
 
PPS Manual_AY_2021-22 I & II Sem.pdf
PPS Manual_AY_2021-22 I & II Sem.pdfPPS Manual_AY_2021-22 I & II Sem.pdf
PPS Manual_AY_2021-22 I & II Sem.pdfSugnanaraoM
 
22 Re-Engineering Traditional Learning Model with Outcome-Based Learning Curv...
22 Re-Engineering Traditional Learning Model with Outcome-Based Learning Curv...22 Re-Engineering Traditional Learning Model with Outcome-Based Learning Curv...
22 Re-Engineering Traditional Learning Model with Outcome-Based Learning Curv...ijtsrd
 
M.tech cse 10july13 (1)
M.tech cse  10july13 (1)M.tech cse  10july13 (1)
M.tech cse 10july13 (1)vijay707070
 
OOAD & ST LAB MANUAL.pdfOose feasibility study in detail Oose feasibility stu...
OOAD & ST LAB MANUAL.pdfOose feasibility study in detail Oose feasibility stu...OOAD & ST LAB MANUAL.pdfOose feasibility study in detail Oose feasibility stu...
OOAD & ST LAB MANUAL.pdfOose feasibility study in detail Oose feasibility stu...shohi1
 
Introductory PPT CSC202 SECURITY ARCHITECTURE.pptx
Introductory PPT CSC202 SECURITY ARCHITECTURE.pptxIntroductory PPT CSC202 SECURITY ARCHITECTURE.pptx
Introductory PPT CSC202 SECURITY ARCHITECTURE.pptxAkash Bhasney
 
Cse443 Project Report - LPU (Modern Big Data Analysis with SQL Specialization)
Cse443 Project Report - LPU (Modern Big Data Analysis with SQL Specialization)Cse443 Project Report - LPU (Modern Big Data Analysis with SQL Specialization)
Cse443 Project Report - LPU (Modern Big Data Analysis with SQL Specialization)Qazi Maaz Arshad
 

Similar to Data base management system LAB MANUAL KCS 551.pdf (20)

CS8461 Operating System Lab Manual S.Selvi
CS8461 Operating System Lab Manual S.SelviCS8461 Operating System Lab Manual S.Selvi
CS8461 Operating System Lab Manual S.Selvi
 
vtu data structures lab manual bcs304 pdf
vtu data structures lab manual bcs304 pdfvtu data structures lab manual bcs304 pdf
vtu data structures lab manual bcs304 pdf
 
SE LAB MANUAL (R16).pdf
SE LAB MANUAL (R16).pdfSE LAB MANUAL (R16).pdf
SE LAB MANUAL (R16).pdf
 
Database management system lLABMANUALpdf
Database management system lLABMANUALpdfDatabase management system lLABMANUALpdf
Database management system lLABMANUALpdf
 
Be computer-engineering-2012
Be computer-engineering-2012Be computer-engineering-2012
Be computer-engineering-2012
 
OA centre of excellence
OA centre of excellenceOA centre of excellence
OA centre of excellence
 
OS lab manual1234512345123451234512345.pdf
OS lab manual1234512345123451234512345.pdfOS lab manual1234512345123451234512345.pdf
OS lab manual1234512345123451234512345.pdf
 
Accelerated Prototyping of Cyber Physical Systems in an Incubator Context
Accelerated Prototyping of Cyber Physical Systems in an Incubator ContextAccelerated Prototyping of Cyber Physical Systems in an Incubator Context
Accelerated Prototyping of Cyber Physical Systems in an Incubator Context
 
SDL-LAB-MANUAL-CS606-common-for-all-the-faculties.pdf
SDL-LAB-MANUAL-CS606-common-for-all-the-faculties.pdfSDL-LAB-MANUAL-CS606-common-for-all-the-faculties.pdf
SDL-LAB-MANUAL-CS606-common-for-all-the-faculties.pdf
 
R2017 Syllabus anna university 2017 .pdf
R2017 Syllabus anna university 2017 .pdfR2017 Syllabus anna university 2017 .pdf
R2017 Syllabus anna university 2017 .pdf
 
1 18CS54 _Software Engineering and Testing _Introduction to CO PO _Syllabus ...
1  18CS54 _Software Engineering and Testing _Introduction to CO PO _Syllabus ...1  18CS54 _Software Engineering and Testing _Introduction to CO PO _Syllabus ...
1 18CS54 _Software Engineering and Testing _Introduction to CO PO _Syllabus ...
 
Futuristic knowledge management ppt bec bagalkot mba
Futuristic knowledge management ppt bec bagalkot mbaFuturistic knowledge management ppt bec bagalkot mba
Futuristic knowledge management ppt bec bagalkot mba
 
B tech information technology syllabus - MITAOE
B tech information technology syllabus - MITAOEB tech information technology syllabus - MITAOE
B tech information technology syllabus - MITAOE
 
FDS_dept_ppt.pptx
FDS_dept_ppt.pptxFDS_dept_ppt.pptx
FDS_dept_ppt.pptx
 
PPS Manual_AY_2021-22 I & II Sem.pdf
PPS Manual_AY_2021-22 I & II Sem.pdfPPS Manual_AY_2021-22 I & II Sem.pdf
PPS Manual_AY_2021-22 I & II Sem.pdf
 
22 Re-Engineering Traditional Learning Model with Outcome-Based Learning Curv...
22 Re-Engineering Traditional Learning Model with Outcome-Based Learning Curv...22 Re-Engineering Traditional Learning Model with Outcome-Based Learning Curv...
22 Re-Engineering Traditional Learning Model with Outcome-Based Learning Curv...
 
M.tech cse 10july13 (1)
M.tech cse  10july13 (1)M.tech cse  10july13 (1)
M.tech cse 10july13 (1)
 
OOAD & ST LAB MANUAL.pdfOose feasibility study in detail Oose feasibility stu...
OOAD & ST LAB MANUAL.pdfOose feasibility study in detail Oose feasibility stu...OOAD & ST LAB MANUAL.pdfOose feasibility study in detail Oose feasibility stu...
OOAD & ST LAB MANUAL.pdfOose feasibility study in detail Oose feasibility stu...
 
Introductory PPT CSC202 SECURITY ARCHITECTURE.pptx
Introductory PPT CSC202 SECURITY ARCHITECTURE.pptxIntroductory PPT CSC202 SECURITY ARCHITECTURE.pptx
Introductory PPT CSC202 SECURITY ARCHITECTURE.pptx
 
Cse443 Project Report - LPU (Modern Big Data Analysis with SQL Specialization)
Cse443 Project Report - LPU (Modern Big Data Analysis with SQL Specialization)Cse443 Project Report - LPU (Modern Big Data Analysis with SQL Specialization)
Cse443 Project Report - LPU (Modern Big Data Analysis with SQL Specialization)
 

Recently uploaded

Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...Dr.Costas Sachpazis
 
Introduction and different types of Ethernet.pptx
Introduction and different types of Ethernet.pptxIntroduction and different types of Ethernet.pptx
Introduction and different types of Ethernet.pptxupamatechverse
 
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLS
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLSMANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLS
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLSSIVASHANKAR N
 
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...roncy bisnoi
 
Porous Ceramics seminar and technical writing
Porous Ceramics seminar and technical writingPorous Ceramics seminar and technical writing
Porous Ceramics seminar and technical writingrakeshbaidya232001
 
UNIT - IV - Air Compressors and its Performance
UNIT - IV - Air Compressors and its PerformanceUNIT - IV - Air Compressors and its Performance
UNIT - IV - Air Compressors and its Performancesivaprakash250
 
result management system report for college project
result management system report for college projectresult management system report for college project
result management system report for college projectTonystark477637
 
Booking open Available Pune Call Girls Koregaon Park 6297143586 Call Hot Ind...
Booking open Available Pune Call Girls Koregaon Park  6297143586 Call Hot Ind...Booking open Available Pune Call Girls Koregaon Park  6297143586 Call Hot Ind...
Booking open Available Pune Call Girls Koregaon Park 6297143586 Call Hot Ind...Call Girls in Nagpur High Profile
 
The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...
The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...
The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...ranjana rawat
 
Booking open Available Pune Call Girls Pargaon 6297143586 Call Hot Indian Gi...
Booking open Available Pune Call Girls Pargaon  6297143586 Call Hot Indian Gi...Booking open Available Pune Call Girls Pargaon  6297143586 Call Hot Indian Gi...
Booking open Available Pune Call Girls Pargaon 6297143586 Call Hot Indian Gi...Call Girls in Nagpur High Profile
 
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur EscortsHigh Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur EscortsCall Girls in Nagpur High Profile
 
Java Programming :Event Handling(Types of Events)
Java Programming :Event Handling(Types of Events)Java Programming :Event Handling(Types of Events)
Java Programming :Event Handling(Types of Events)simmis5
 
Extrusion Processes and Their Limitations
Extrusion Processes and Their LimitationsExtrusion Processes and Their Limitations
Extrusion Processes and Their Limitations120cr0395
 
Glass Ceramics: Processing and Properties
Glass Ceramics: Processing and PropertiesGlass Ceramics: Processing and Properties
Glass Ceramics: Processing and PropertiesPrabhanshu Chaturvedi
 
Introduction to Multiple Access Protocol.pptx
Introduction to Multiple Access Protocol.pptxIntroduction to Multiple Access Protocol.pptx
Introduction to Multiple Access Protocol.pptxupamatechverse
 
Processing & Properties of Floor and Wall Tiles.pptx
Processing & Properties of Floor and Wall Tiles.pptxProcessing & Properties of Floor and Wall Tiles.pptx
Processing & Properties of Floor and Wall Tiles.pptxpranjaldaimarysona
 
Online banking management system project.pdf
Online banking management system project.pdfOnline banking management system project.pdf
Online banking management system project.pdfKamal Acharya
 

Recently uploaded (20)

Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
 
Introduction and different types of Ethernet.pptx
Introduction and different types of Ethernet.pptxIntroduction and different types of Ethernet.pptx
Introduction and different types of Ethernet.pptx
 
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLS
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLSMANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLS
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLS
 
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...
 
Porous Ceramics seminar and technical writing
Porous Ceramics seminar and technical writingPorous Ceramics seminar and technical writing
Porous Ceramics seminar and technical writing
 
UNIT - IV - Air Compressors and its Performance
UNIT - IV - Air Compressors and its PerformanceUNIT - IV - Air Compressors and its Performance
UNIT - IV - Air Compressors and its Performance
 
result management system report for college project
result management system report for college projectresult management system report for college project
result management system report for college project
 
Booking open Available Pune Call Girls Koregaon Park 6297143586 Call Hot Ind...
Booking open Available Pune Call Girls Koregaon Park  6297143586 Call Hot Ind...Booking open Available Pune Call Girls Koregaon Park  6297143586 Call Hot Ind...
Booking open Available Pune Call Girls Koregaon Park 6297143586 Call Hot Ind...
 
The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...
The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...
The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...
 
Booking open Available Pune Call Girls Pargaon 6297143586 Call Hot Indian Gi...
Booking open Available Pune Call Girls Pargaon  6297143586 Call Hot Indian Gi...Booking open Available Pune Call Girls Pargaon  6297143586 Call Hot Indian Gi...
Booking open Available Pune Call Girls Pargaon 6297143586 Call Hot Indian Gi...
 
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur EscortsHigh Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
 
Java Programming :Event Handling(Types of Events)
Java Programming :Event Handling(Types of Events)Java Programming :Event Handling(Types of Events)
Java Programming :Event Handling(Types of Events)
 
Extrusion Processes and Their Limitations
Extrusion Processes and Their LimitationsExtrusion Processes and Their Limitations
Extrusion Processes and Their Limitations
 
Glass Ceramics: Processing and Properties
Glass Ceramics: Processing and PropertiesGlass Ceramics: Processing and Properties
Glass Ceramics: Processing and Properties
 
Introduction to Multiple Access Protocol.pptx
Introduction to Multiple Access Protocol.pptxIntroduction to Multiple Access Protocol.pptx
Introduction to Multiple Access Protocol.pptx
 
Roadmap to Membership of RICS - Pathways and Routes
Roadmap to Membership of RICS - Pathways and RoutesRoadmap to Membership of RICS - Pathways and Routes
Roadmap to Membership of RICS - Pathways and Routes
 
Processing & Properties of Floor and Wall Tiles.pptx
Processing & Properties of Floor and Wall Tiles.pptxProcessing & Properties of Floor and Wall Tiles.pptx
Processing & Properties of Floor and Wall Tiles.pptx
 
Online banking management system project.pdf
Online banking management system project.pdfOnline banking management system project.pdf
Online banking management system project.pdf
 
Water Industry Process Automation & Control Monthly - April 2024
Water Industry Process Automation & Control Monthly - April 2024Water Industry Process Automation & Control Monthly - April 2024
Water Industry Process Automation & Control Monthly - April 2024
 
DJARUM4D - SLOT GACOR ONLINE | SLOT DEMO ONLINE
DJARUM4D - SLOT GACOR ONLINE | SLOT DEMO ONLINEDJARUM4D - SLOT GACOR ONLINE | SLOT DEMO ONLINE
DJARUM4D - SLOT GACOR ONLINE | SLOT DEMO ONLINE
 

Data base management system LAB MANUAL KCS 551.pdf

  • 1. Database Management System (KCS-551) Lab Manual DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING Vandana Tripathi A. P (BBDITM C. S. E) Page 1 of 56 DATABASE MANAGEMENT SYSTEM (KCS-551) LABORATORY MANUAL B.TECH, 3rd Year, Semester - V COMPUTER SCIENCE & ENGINEERING
  • 2. Database Management System (KCS-551) Lab Manual DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING Vandana Tripathi A. P (BBDITM C. S. E) Page 2 of 56 MANUAL CONTENTS This manual is intended for the 3rd year students of Computer Science & Engineering in the subject of Database Management System (Using MySQL). This manual typically contains practical/lab sessions related Database Management System implemented using MySQL covering various aspects related the subject to enhanced understanding. Students are advised to thoroughly go through this manual rather than only topics mentioned in the syllabus as practical aspects are the key to understanding and conceptual visualization of theoretical aspects covered in the books. Good Luck for your Enjoyable Laboratory Sessions HOD, CSE
  • 3. Database Management System (KCS-551) Lab Manual DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING Vandana Tripathi A. P (BBDITM C. S. E) Page 3 of 56 PREFACE This manual is designed in accordance to the new syllabus (2022-23) prescribed by A.K.T.U. for the Fifth Semester Database Management System Laboratory. This practical manual will be helpful for students of Computer Science & Engineering for understanding the course from the point of view of applied aspects. Though all the efforts have been made to make this manual error free, yet some errors might have crept in inadvertently. Suggestions from the readers for the improvement of the manual are most welcomed. Vision of the Institute “To become a leading institute of providing professionally competent and socially responsive technocrats with high moral values." Mission of the Institute M1. To create an eco-system for the dissemination of technical knowledge, to achieve academic excellence. M2. To develop technocrats with creative skills and leadership qualities, to solve local and global challenges. M3. To impart human values and ethics in students, to make them socially and eco-friendly responsible.
  • 4. Database Management System (KCS-551) Lab Manual DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING Vandana Tripathi A. P (BBDITM C. S. E) Page 4 of 56 Vision of the Department “To produce globally competent professionals having social values and commitment to serve the global needs with the ability to work in an interdisciplinary environment." Mission of the Department M1. "To impart quality education to the students to enhance their ethical, professional and leadership qualities to make them globally competitive." M2. "To create a conducive environment in which students can explore computational problems and analyze them to identify the optimal solutions." M3. "To strive for continual enhancement of technical knowledge & innovation through industry interface to accomplish global needs." Program Educational Objectives (PEOs) PEO1: Students must be able to apply software engineering principles to analyze complex computing problems and identify their solutions. PEO2: Students must be able to analyze, design, and implement the latest technology-driven projects. PEO3: Students must be able to work in a collaborative environment and understand the ethical, social, and economic impact of their work. Program Outcomes (POs) PO’s An Engineering Graduate of the Department of Computer Science and Engineering Program will be able to demonstrate: PO1 ENGINEERING KNOWLEDGE: Apply the knowledge of mathematics, including discrete mathematics, probability, statistics and fundamentals of various engineering disciplines like computer science and engineering, electronic engineering and Electrical engineering in the core information technologies. PO2 PROBLEM ANALYSIS: Analyze a problem and identify the computing requirements appropriate to its solution.
  • 5. Database Management System (KCS-551) Lab Manual DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING Vandana Tripathi A. P (BBDITM C. S. E) Page 5 of 56 PO3 DESIGN/DEVELOPMENT OF SOLUTIONS: Design and implement hardware and software systems, components, process or program to meet the desired needs within reasonable economic, environmental, social, political, ethical, health and safety, manufacturability, and sustainability constraints. PO4 CONDUCT INVESTIGATIONS OF COMPLEX PROBLEMS: Reassess literature and indulge in research to use research-based knowledge and methods to design and conduct new experiments, as well as to organize, analyze and interpret data to produce draw valid Conclusions and recommendations. PO5 MODERN TOOL USAGE: Use appropriate techniques, resources, and modern engineering and IT tools necessary for computer engineering practice. PO6 THE ENGINEER AND SOCIETY: Show the understanding of local and global impact of computing on individuals, organizations and society. PO7 ENVIRONMENT AND SUSTAINABILITY: Integrate IT-based solutions in environmental contexts, and demonstrate the knowledge of need for sustainable development. PO8 ETHICS: Demonstrate the knowledge of professional and ethical responsibilities along with the norms of the engineering practice. PO9 INDIVIDUAL AND TEAM WORK: Demonstrate leadership and an ability to work as a member with responsibility to function on multi-disciplinary teams to accomplish a common goal. PO10 COMMUNICATION: Demonstrate effectively communicate skills in both oral and written form with a range of audiences. PO11 PROJECT MANAGEMENT AND FINANCE: Apply the knowledge and understanding of engineering and management principles to design, planned budget and propose IT project for an identified need within a specific scope. PO12 LIFE-LONG LEARNING: Developed confidence to acquire new knowledge in the computing discipline and to engage in life-long learning. Program Specific Outcomes (PSOs) PSO 1: Able to design and implement the data structures and algorithms to deliver quality software products. PSO 2: Able to apply Artificial Intelligence and Machine Learning concepts to solve society- related needs.
  • 6. Database Management System (KCS-551) Lab Manual DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING Vandana Tripathi A. P (BBDITM C. S. E) Page 6 of 56 Course Outcomes (COs) CO’s Statement Bloom’s Knowledge Level (KL) CO1 To implement ER diagram and different types of DDL, DML and DCL queries. L3 CO2 To implement different Normalization forms NF1, NF2, etc. L3 CO 3 To implement programs using different procedures, functions, packages, cursor etc. L3 CO 4 To design and implement payroll processing system, library information system. L4 CO 5 To design and implement a procedure which generate all the prime numbers and mini project. L4
  • 7. Database Management System (KCS-551) Lab Manual DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING Vandana Tripathi A. P (BBDITM C. S. E) Page 7 of 56 INDEX S. No. Name of the Experiment CO BTL Virtual Lab Link/ Source for Conduction of Experiment* 1. Installing MySQL/Oracle and creating Entity-Relationship Diagram. 1 L4 https://www.youtube.com/watch?v=EHF bk_6ThAQ https://www.youtube.com/watch?v=2fPP _u_Nzyw 2. WrWrite the queries for Data Definition and Data Manipulation Language. 2 L3 http://vlabs.iitb.ac.in/vlabs- dev/labs/dblab/labs/exp3/index.php 3. Write SQL queries using SQL operators and logical operations (=,<,>,etc) 2 L3 http://vlabs.iitb.ac.in/vlabs- dev/labs/dblab/labs/exp3/index.php 4. Write SQL queries using Aggregate Functions 2 L3 http://vlabs.iitb.ac.in/vlabs- dev/labs/dblab/labs/exp3/index.php 5. a.riWrite SQL queries for relational algebra. b.Write SQL queries for extracting data from more than one table. 2 L4 https://www.youtube.com/watch?v=o7Np 5bHtc2w http://vlabs.iitb.ac.in/vlabs- dev/labs/dblab/labs/exp3/index.php 6. Write SQL queries for sub queries, nested queries. 3 L5 https://www.youtube.com/watch?v=miT O-dCgJpo 7. Write program by the use of PL/SQL. 3 L4 https://www.youtube.com/watch?v=J5wjI f4gdq4&list=PLWPirh4EWFpHj0kKqqY udPNOrGEa0fFIr
  • 8. Database Management System (KCS-551) Lab Manual DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING Vandana Tripathi A. P (BBDITM C. S. E) Page 8 of 56 8. Concepts for ROLL BACK, COMMIT & CHECK POINTS. 4 L4 https://www.youtube.com/watch?v=Li6B jT_W8W8 9. Creating Procedure and Functions in Oracle. 5 L4 https://www.youtube.com/watch?v=Pxlj5 bZW3xw 10. Creating Cursor and Trigger in Oracle. 5 L4 https://www.youtube.com/watch?v=KGE y1j-CzaY https://www.youtube.com/watch?v=nfpe N0_SPmM
  • 9. Database Management System (KCS-551) Lab Manual DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING Vandana Tripathi A. P (BBDITM C. S. E) Page 9 of 56 INTRODUCTION Aims The aim of this course is to design database using data modelling techniques and its logical implementation using MySQL , which encourages a different solve real problems that are suited to this style. Practical experimentation with the language is strongly encouraged. Course Objectives At the end of the course, students will be able to: 1 To Explain basic database concepts, applications, data models, schemas and instances. 2 To Demonstrate the use of constraints and relational algebra operations. IV. Describe the basbasics of SQL and construct queries using SQL 3 To emphasize the importance of normalization in databases.
  • 10. Database Management System (KCS-551) Lab Manual DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING Vandana Tripathi A. P (BBDITM C. S. E) Page 10 of 56 Aim - Installing MySQL/Oracle and creating Entity-Relationship Diagram. Content: Installation steps for MySQL: • Download MySQL from https://dev.mysql.com/downloads/mysql/ Installing MySQL on Windows: Your downloaded MySQL is neatly packaged with an installer. Download the installer package, unzip it anywhere and run setup.exe. By default, this process will install everything under C:mysql Verify MySQL installation: Step 1 : Open from start Step 2 : enter the password you have set during installation . Babu Banarasi Das Institute of Technology & Management, Lucknow LAB MANUAL Course Name: Database Management System Lab Experiment No. 1 Course Code: KCS 551 Branch: CSE Semester: V
  • 11. Database Management System (KCS-551) Lab Manual DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING Vandana Tripathi A. P (BBDITM C. S. E) Page 11 of 56 • Step-3 : if you already have created data bases then use them else create new database. • Creating Entity-Relationship Diagram Consider following databases and draw ER diagram and convert entities and relationships to relation table for a given scenario. 1. COLLEGE DATABASE: STUDENT (USN, SName, Address, Phone, Gender) SEMSEC (SSID, Sem, Sec) CLASS (USN, SSID) SUBJECT (Subcode, Title, Sem, Credits) IAMARKS (USN, Subcode, SSID, Test1, Test2, Test3, FinalIA) 2. COMPANY DATABASE: EMPLOYEE (SSN, Name, Address, Sex, Salary, SuperSSN, DNo) DEPARTMENT (DNo, DName, MgrSSN, MgrStartDate) DLOCATION (DNo,DLoc) PROJECT (PNo, PName, PLocation, DNo) WORKS_ON (SSN, PNo, Hours)
  • 12. Database Management System (KCS-551) Lab Manual DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING Vandana Tripathi A. P (BBDITM C. S. E) Page 12 of 56 College Database: E-R Diagram
  • 13. Database Management System (KCS-551) Lab Manual DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING Vandana Tripathi A. P (BBDITM C. S. E) Page 13 of 56 COMPANY DATABASE:
  • 14. Database Management System (KCS-551) Lab Manual DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING Vandana Tripathi A. P (BBDITM C. S. E) Page 14 of 56
  • 15. Database Management System (KCS-551) Lab Manual DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING Vandana Tripathi A. P (BBDITM C. S. E) Page 15 of 56 Aim: Write the queries for Data Definition and Data Manipulation Language. Types of SQL Commands There are five types of SQL commands: DDL, DML, DCL, TCL, and DQL. 1. Data Definition Language (DDL) o DDL changes the structure of the table like creating a table, deleting a table, altering a table, etc. o All the command of DDL are auto-committed that means it permanently save all the changes in the database. Here are some commands that come under DDL: o CREATE o ALTER o DROP o TRUNCATE a. CREATE It is used to create a new table in the database. Syntax: 1. CREATE TABLE TABLE_NAME (COLUMN_NAME DATATYPES[,....]); Example: 1. CREATE TABLE EMPLOYEE(Name VARCHAR2(20), Email VARCHAR2(100), DOB D ATE); b. DROP: It is used to delete both the structure and record stored in the table. Syntax Babu Banarasi Das Institute of Technology & Management, Lucknow LAB MANUAL Course Name: Database Management System Lab Experiment No. 2 Course Code: KCS 551 Branch: CSE Semester: V
  • 16. Database Management System (KCS-551) Lab Manual DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING Vandana Tripathi A. P (BBDITM C. S. E) Page 16 of 56 1. DROP TABLE table_name; Example 1. DROP TABLE EMPLOYEE; c. ALTER: It is used to alter the structure of the database. This change could be either to modify the characteristics of an existing attribute or probably to add a new attribute. Syntax: To add a new column in the table 1. ALTER TABLE table_name ADD column_name COLUMN-definition; To modify existing column in the table: 1. ALTER TABLE table_name MODIFY(column_definitions....); EXAMPLE 1. ALTER TABLE STU_DETAILS ADD(ADDRESS VARCHAR2(20)); 2. ALTER TABLE STU_DETAILS MODIFY (NAME VARCHAR2(20)); d. TRUNCATE: It is used to delete all the rows from the table and free the space containing the table. Syntax: 1. TRUNCATE TABLE table_name; Example:TRUNCATE TABLE EMPLOYEE; 2. Data Manipulation Language o DML commands are used to modify the database. It is responsible for all form of changes in the database. o The command of DML is not auto-committed that means it can't permanently save all the changes in the database. They can be rollback.
  • 17. Database Management System (KCS-551) Lab Manual DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING Vandana Tripathi A. P (BBDITM C. S. E) Page 17 of 56 o INSERT o UPDATE o DELETE a. INSERT: The INSERT statement is a SQL query. It is used to insert data into the row of a table. Syntax: 1. INSERT INTO TABLE_NAME 2. (col1, col2, col3,.... col N) 3. VALUES (value1, value2, value3, .... valueN); For example: 1. INSERT INTO javatpoint (Author, Subject) VALUES ("Sonoo", "DBMS"); b. UPDATE: This command is used to update or modify the value of a column in the table. Syntax: 1. UPDATE table_name SET [column_name1= value1,...column_nameN = valueN] [WHERE CONDITION] For example: 1. UPDATE students 2. SET User_Name = 'Sonoo' 3. WHERE Student_Id = '3' c. DELETE: It is used to remove one or more row from a table. Syntax: 1. DELETE FROM table_name [WHERE condition]; For example: 1. DELETE FROM javatpoint 2. WHERE Author="Sonoo";
  • 18. Database Management System (KCS-551) Lab Manual DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING Vandana Tripathi A. P (BBDITM C. S. E) Page 18 of 56 Aim - Write SQL queries using SQL operators and logical operations (=,<,>,etc) Content - SQL Arithmetic Operators: SQL Bitwise Operators Operator Description & Bitwise AND | Bitwise OR ^ Bitwise exclusive OR SQL Comparison Operators Operator Description Babu Banarasi Das Institute of Technology & Management, Lucknow LAB MANUAL Course Name: Database Management System Lab Experiment No. 3 Course Code: KCS 551 Branch: CSE Semester: V
  • 19. Database Management System (KCS-551) Lab Manual DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING Vandana Tripathi A. P (BBDITM C. S. E) Page 19 of 56 = Equal to > Greater than < Less than >= Greater than or equal to <= Less than or equal to <> Not equal to SQL Logical Operators Operator Description Example ALL TRUE if all of the subquery values meet the condition AND TRUE if all the conditions separated by AND is TRUE
  • 20. Database Management System (KCS-551) Lab Manual DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING Vandana Tripathi A. P (BBDITM C. S. E) Page 20 of 56 ANY TRUE if any of the subquery values meet the condition BETWEEN TRUE if the operand is within the range of comparisons EXISTS TRUE if the subquery returns one or more records IN TRUE if the operand is equal to one of a list of expressions LIKE TRUE if the operand matches a pattern NOT Displays a record if the condition(s) is NOT TRUE OR TRUE if any of the conditions separated by OR is TRUE SOME TRUE if any of the subquery values meet the condition
  • 21. Database Management System (KCS-551) Lab Manual DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING Vandana Tripathi A. P (BBDITM C. S. E) Page 21 of 56 Aim - Write SQL query using character, number, date and group functions Content - Character functions accept character inputs and can return either characters or number values as output. SQL provides a number of different character datatypes which includes – CHAR, VARCHAR, VARCHAR2, LONG, RAW, and LONG RAW. The various datatypes are categorized into three different datatypes : 1. VARCHAR2 – A variable-length character datatype whose data is converted by the RDBMS. 2. CHAR – The fixed-length datatype. 3. RAW – A variable-length datatype whose data is not converted by the RDBMS, but left in “raw” form. Character Functions SQL provides a rich set of character functions that allow you to get information about strings and modify the contents of those strings in multiple ways. Character functions are of the following two types: 1. Case-Manipulative Functions (LOWER, UPPER and INITCAP) 2. Character-Manipulative Functions (CONCAT, LENGTH, SUBSTR, INSTR, LPAD, RPAD, TRIM and REPLACE) Case-Manipulative Functions 1. LOWER : This function converts alpha character values to lowercase. LOWER will actually return a fixed-length string if the incoming string is fixed-length. LOWER will not change any characters in the string that are not letters, since case is irrelevant for numbers and special characters, such as the dollar sign ( $ ) or modulus ( % ). Syntax: LOWER(SQL course) Input1: SELECT LOWER('GEEKSFORGEEKS') FROM DUAL; Output1: geeksforgeeks Input2: SELECT LOWER('DATABASE@456') FROM DUAL; Output2: database@456 2. UPPER : This function converts alpha character values to uppercase. Also UPPER function too, will actually return a fixed-length string if the incoming string is fixed- length. UPPER will not change any characters in the string that are not letters, since case is irrelevant for numbers and special characters, such as the dollar sign ( $ ) or modulus ( % ). Syntax: Babu Banarasi Das Institute of Technology & Management, Lucknow LAB MANUAL Course Name: Database Management System Lab Experiment No. 4 Course Code: KCS 551 Branch: CSE Semester: V
  • 22. Database Management System (KCS-551) Lab Manual DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING Vandana Tripathi A. P (BBDITM C. S. E) Page 22 of 56 UPPER(SQL course) Input1: SELECT UPPER('geeksforgeeks') FROM DUAL; Output1: GEEKSFORGEEKS Input2: SELECT UPPER('dbms$508%7') FROM DUAL; Output2: DBMS$508%7 3. INITCAP : This function converts alpha character values to uppercase for the first letter of each word and all others in lowercase. The words in the string is must be separated by either # or _ or space. Syntax: INITCAP(SQL course) Input1: SELECT INITCAP('geeksforgeeks is a computer science portal for geeks') FROM DUAL; Output1: Geeksforgeeks Is A Computer Science Portal For Geeks Input2: SELECT INITCAP('PRACTICE_CODING_FOR_EFFICIENCY') FROM DUAL; Output2: Practice_Coding_For_Efficiency Character-Manipulative Functions 1. CONCAT : This function always appends ( concatenates ) string2 to the end of string1. If either of the string is NULL, CONCAT function returns the non-NULL argument. If both strings are NULL, CONCAT returns NULL. Syntax: CONCAT('String1', 'String2') Input1: SELECT CONCAT('computer' ,'science') FROM DUAL; Output1: computerscience Input2: SELECT CONCAT( NULL ,'Android') FROM DUAL; Output2: Android Input3: SELECT CONCAT( NULL ,NULL ) FROM DUAL; Output3: - 2. LENGTH : This function returns the length of the input string. If the input string is NULL, then LENGTH function returns NULL and not Zero. Also, if the input string contains extra spaces at the start, or in between or at the end of the string, then the LENGTH function includes the extra spaces too and returns the complete length of the string. Syntax: LENGTH(Column|Expression) Input1: SELECT LENGTH('Learning Is Fun') FROM DUAL; Output1: 15
  • 23. Database Management System (KCS-551) Lab Manual DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING Vandana Tripathi A. P (BBDITM C. S. E) Page 23 of 56 Input2: SELECT LENGTH(' Write an Interview Experience ') FROM DUAL; Output2: 34 Input3: SELECT LENGTH('') FROM DUAL; or SELECT LENGTH( NULL ) FROM DUAL; Output3: - 3. SUBSTR : This function returns a portion of a string from a given start point to an end point. If a substring length is not given, then SUBSTR returns all the characters till the end of string (from the starting position specified). Syntax: SUBSTR('String',start-index,length_of_extracted_string) Input1: SELECT SUBSTR('Database Management System', 9) FROM DUAL; Output1: Management System Input2: SELECT SUBSTR('Database Management System', 9, 7) FROM DUAL; Output2: Manage 4. INSTR : This function returns numeric position of a character or a string in a given string. Optionally, you can provide a position m to start searching, and the occurrence n of string. Also, if the starting position is not given, then it starts search from index 1, by default. If after searching in the string, no match is found then, INSTR function returns 0. Syntax: INSTR(Column|Expression, 'String', [,m], [n]) Input: SELECT INSTR('Google apps are great applications','app',1,2) FROM DUAL; Output: 23 5. LPAD and RPAD : These functions return the strings padded to the left or right ( as per the use ) ; hence the “L” in “LPAD” and the “R” in “RPAD” ; to a specified length, and with a specified pad string. If the pad string is not specified, then the given string is padded on the left or right ( as per the use ) with spaces. Syntax: 6. LPAD(Column|Expression, n, 'String') Syntax: RPAD(Column|Expression, n, 'String') LPAD Input1: SELECT LPAD('100',5,'*') FROM DUAL; LPAD Output1: **100 LPAD Input2: SELECT LPAD('hello', 21, 'geek') FROM DUAL; LPAD Output2: geekgeekgeekgeekhello RPAD Input1: SELECT RPAD('5000',7,'*') FROM DUAL; RPAD Output1: 5000*** RPAD Input1: SELECT RPAD('earn', 19, 'money') FROM DUAL; RPAD Output1: earnmoneymoneymoney
  • 24. Database Management System (KCS-551) Lab Manual DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING Vandana Tripathi A. P (BBDITM C. S. E) Page 24 of 56 7. TRIM : This function trims the string input from the start or end (or both). If no string or char is specified to be trimmed from the string and there exists some extra space at start or end of the string, then those extra spaces are trimmed off. Syntax: TRIM(Leading|Trailing|Both, trim_character FROM trim_source) Input1: SELECT TRIM('G' FROM 'GEEKS') FROM DUAL; Output1: EEKS Input2: SELECT TRIM(' geeksforgeeks ') FROM DUAL; Output2:geeksforgeeks 8. REPLACE : This function searches for a character string and, if found, replaces it with a given replacement string at all the occurrences of the string. REPLACE is useful for searching patterns of characters and then changing all instances of that pattern in a single function call. If a replacement string is not given, then REPLACE function removes all the occurrences of that character string in the input string. If neither a match string nor a replacement string is specified, then REPLACE returns NULL. Syntax: REPLACE(Text, search_string, replacement_string) Input1: SELECT REPLACE('DATA MANAGEMENT', 'DATA','DATABASE') FROM DUAL; Output1: DATABASE MANAGEMENT Input2: SELECT REPLACE('abcdeabcccabdddeeabcc', 'abc') FROM DUAL; Output2: deccabdddeec
  • 25. Database Management System (KCS-551) Lab Manual DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING Vandana Tripathi A. P (BBDITM C. S. E) Page 25 of 56 Aim – a. Write SQL queries for relational algebra. b.Write SQL queries for extracting data from more than one table. Content - SQL JOIN A JOIN clause is used to combine rows from two or more tables, based on a related column between them. Let's look at a selection from the "Orders" table: OrderID CustomerID OrderDate 10308 2 1996-09-18 10309 37 1996-09-19 10310 77 1996-09-20 Babu Banarasi Das Institute of Technology & Management, Lucknow LAB MANUAL Course Name: Database Management System Lab Experiment No. 5 Course Code: KCS 551 Branch: CSE Semester: V
  • 26. Database Management System (KCS-551) Lab Manual DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING Vandana Tripathi A. P (BBDITM C. S. E) Page 26 of 56 Then, look at a selection from the "Customers" table: CustomerID CustomerName ContactName Country 1 Alfreds Futterkiste Maria Anders Germany 2 Ana Trujillo Emparedados y helados Ana Trujillo Mexico 3 Antonio Moreno Taquería Antonio Moreno Mexico Notice that the "CustomerID" column in the "Orders" table refers to the "CustomerID" in the "Customers" table. The relationship between the two tables above is the "CustomerID" column. Then, we can create the following SQL statement (that contains an INNER JOIN), that selects records that have matching values in both tables: Example SELECT Orders.OrderID, Customers.CustomerName, Orders.OrderDate FROM Orders INNER JOIN Customers ON Orders.CustomerID=Customers.CustomerID; Output- OrderID CustomerName OrderDate 10308 Ana Trujillo Emparedados y helados 9/18/1996
  • 27. Database Management System (KCS-551) Lab Manual DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING Vandana Tripathi A. P (BBDITM C. S. E) Page 27 of 56 10365 Antonio Moreno Taquería 11/27/1996 10383 Around the Horn 12/16/1996 10355 Around the Horn 11/15/1996 10278 Berglunds snabbköp 8/12/1996 Different Types of SQL JOINs Here are the different types of the JOINs in SQL: • (INNER) JOIN: Returns records that have matching values in both tables • LEFT (OUTER) JOIN: Returns all records from the left table, and the matched records from the right table • RIGHT (OUTER) JOIN: Returns all records from the right table, and the matched records from the left table • FULL (OUTER) JOIN: Returns all records when there is a match in either left or right table
  • 28. Database Management System (KCS-551) Lab Manual DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING Vandana Tripathi A. P (BBDITM C. S. E) Page 28 of 56
  • 29. Database Management System (KCS-551) Lab Manual DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING Vandana Tripathi A. P (BBDITM C. S. E) Page 29 of 56 Aim - Write SQL queries for extracting data from more than one table and for sub queries, nested queries. Content – Creating a subquery to retrieve data from more than one table When you need to include in your WHERE clause selection criteria that only exists in another table, you can add subqueries to a SQL statement to retrieve the values that satisfy the condition. A subquery is a complete query that appears in the WHERE or HAVING clause of an SQL statement. Rules for creating a subquery • Enclose the subquery in parentheses. • Specify only one column or expression in a subquery unless you are using IN, ANY, ALL, or EXISTS. • A subquery cannot contain a BETWEEN or LIKE clause. • A subquery cannot contain an ORDER BY clause. • A subquery in an UPDATE statement cannot retrieve data from the same table in which data is to be updated. • A subquery in a DELETE statement cannot retrieve data from the same table in which data is to be deleted. The following query displays the names and IDs of employees who work in Boston. The subquery (in parentheses) finds the department number for the location of BOSTON in the Q.ORG table. Then the main query selects the names of the employees in that department from the Q.STAFF table. SELECT NAME, ID FROM Q.STAFF WHERE DEPT=(SELECT DEPTNUMB FROM Q.ORG WHERE LOCATION='BOSTON') In the next example, the subquery and main query retrieve data from the same table. The subquery calculates the average salary for all the employees in the Q.STAFF table. Then, the Babu Banarasi Das Institute of Technology & Management, Lucknow LAB MANUAL Course Name: Database Management System Lab Experiment No. 6 Course Code: KCS 551 Branch: CSE Semester: V
  • 30. Database Management System (KCS-551) Lab Manual DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING Vandana Tripathi A. P (BBDITM C. S. E) Page 30 of 56 main query selects the salespeople whose salaries are equal to or greater than the average salary. SELECT ID, NAME, SALARY FROM Q.STAFF WHERE JOB = 'SALES' AND SALARY >= (SELECT AVG(SALARY) FROM Q.STAFF) Retrieving more than one value with a subquery Usually a subquery selects only one column and returns only one value to the query. However, you can create a subquery that uses the ANY or ALL keywords with comparison operators (=, ¬=, >, >=, <, or <=) to return a particular set of values. In addition, just as you use the IN keyword in place of multiple OR statements in a query, you can also use IN in place of the ANY keyword in a subquery. The query in the following figure selects any employee who works in the Eastern division. The subquery finds the department numbers in the Eastern division, and then the main query selects the employees who work in any of these departments. Use the ANY keyword for this query, because it is likely that the subquery will find more than one department in the Eastern division. If you use the ALL keyword instead of the ANY keyword, no data is selected because no employee works in all departments of the Eastern division. This SQL query contains a subquery that uses the ANY keyword. SELECT NAME, ID FROM Q.STAFF WHERE DEPT = ANY (SELECT DEPTNUMB FROM Q.ORG WHERE DIVISION='EASTERN') The query in the following figure selects the department with the highest average salary. The subquery finds the average salary for each department, and then the main query selects the department with the highest average salary. Use the ALL keyword for this subquery. The department selected by the query must have an average salary greater than or equal to all the average salaries of the other departments. . This SQL query contains a subquery using the ALL keyword.
  • 31. Database Management System (KCS-551) Lab Manual DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING Vandana Tripathi A. P (BBDITM C. S. E) Page 31 of 56 SELECT DEPT, AVG(SALARY) FROM Q.STAFF GROUP BY DEPT HAVING AVG(SALARY) >= ALL (SELECT AVG(SALARY) FROM Q.STAFF GROUP BY DEPT) The query in following figure selects all salespeople (and their salaries) who work for managers earning more than $20,000 a year. The subquery finds the managers who earn more than $20,000 a year, and the main query selects the salespeople who work for those managers. Use the IN keyword for this subquery because you need to find values from more than one department. This SQL query contains a subquery using the IN keyword. SELECT ID, NAME, SALARY FROM Q.STAFF WHERE JOB = 'SALES' AND DEPT IN (SELECT DISTINCT DEPT FROM Q.STAFF WHERE JOB = 'MGR' AND SALARY > 20000) You can also specify NOT IN in a subquery to select information from one table when corresponding information does not exist in the other table. Checking for rows that satisfy a condition Not only can you use a subquery to return a value to the query, you can also use a WHERE EXISTS clause in a subquery to check for rows that satisfy a certain row condition. The query in the following figure selects employees from the Q.STAFF table who have a salary of less than $14,000 and who work in a department where at least one other employee with the same job earns a salary greater than $14,000. (The subquery checks for other employees in the department with the same job, but who earn a salary greater than $14,000 This subquery checks for rows that satisfy a condition. SELECT NAME, DEPT, JOB, SALARY
  • 32. Database Management System (KCS-551) Lab Manual DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING Vandana Tripathi A. P (BBDITM C. S. E) Page 32 of 56 FROM Q.STAFF S WHERE S.SALARY < 14000 AND EXISTS (SELECT * FROM Q.STAFF WHERE S.DEPT=DEPT AND SALARY >14000 AND S.JOB=JOB) ORDER BY S.DEPT Specifying a correlation name in a subquery You can specify a correlation name in a subquery to use a condition to evaluate every row retrieved by the main query. The query in the following figure selects the department, name, and salary of the employees who have the highest salary in their departments. The subquery calculates the maximum salary for each department that is selected by the main query. The correlation name, Y, compares each row that is selected by the query to the maximum salary that is calculated for the department in the subquery. This subquery specifies a correlation name. SELECT DEPT, NAME, SALARY FROM Q.STAFF Y WHERE SALARY = (SELECT MAX (SALARY) FROM Q.STAFF WHERE DEPT = Y.DEPT)
  • 33. Database Management System (KCS-551) Lab Manual DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING Vandana Tripathi A. P (BBDITM C. S. E) Page 33 of 56 Aim - Write program by the use of PL/SQL. Content – PL/SQL PL/SQL is a block structured language. The programs of PL/SQL are logical blocks that can contain any number of nested sub-blocks. Pl/SQL stands for "Procedural Language extension of SQL" that is used in Oracle. PL/SQL is integrated with Oracle database (since version 7). The functionalities of PL/SQL usually extended after each release of Oracle database. Although PL/SQL is closely integrated with SQL language, yet it adds some programming constraints that are not available in SQL. PL/SQL Functionalities PL/SQL includes procedural language elements like conditions and loops. It allows declaration of constants and variables, procedures and functions, types and variable of those types and triggers. It can support Array and handle exceptions (runtime errors). After the implementation of version 8 of Oracle database have included features associated with object orientation. You can create PL/SQL units like procedures, functions, packages, types and triggers, etc. which are stored in the database for reuse by applications. With PL/SQL, you can use SQL statements to manipulate Oracle data and flow of control statements to process the data. The PL/SQL is known for its combination of data manipulating power of SQL with data processing power of procedural languages. It inherits the robustness, security, and portability of the Oracle Database. PL/SQL is not case sensitive so you are free to use lower case letters or upper case letters except within string and character literals. A line of PL/SQL text contains groups of characters known as lexical units. It can be classified as follows: o Delimeters o Identifiers o Literals o Comment Babu Banarasi Das Institute of Technology & Management, Lucknow LAB MANUAL Course Name: Database Management System Lab Experiment No. 7 Course Code: KCS 551 Branch: CSE Semester: V
  • 34. Database Management System (KCS-551) Lab Manual DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING Vandana Tripathi A. P (BBDITM C. S. E) Page 34 of 56 PL/SQL - Arrays In this chapter, we will discuss arrays in PL/SQL. The PL/SQL programming language provides a data structure called the VARRAY, which can store a fixed-size sequential collection of elements of the same type. A varray is used to store an ordered collection of data, however it is often better to think of an array as a collection of variables of the same type. All varrays consist of contiguous memory locations. The lowest address corresponds to the first element and the highest address to the last element. An array is a part of collection type data and it stands for variable-size arrays. We will study other collection types in a later chapter 'PL/SQL Collections'. Each element in a varray has an index associated with it. It also has a maximum size that can be changed dynamically. Creating a Varray Type A varray type is created with the CREATE TYPE statement. You must specify the maximum size and the type of elements stored in the varray. The basic syntax for creating a VARRAY type at the schema level is − CREATE OR REPLACE TYPE varray_type_name IS VARRAY(n) of <element_type> Where, • varray_type_name is a valid attribute name, • n is the number of elements (maximum) in the varray, • element_type is the data type of the elements of the array. Maximum size of a varray can be changed using the ALTER TYPE statement. For example, CREATE Or REPLACE TYPE namearray AS VARRAY(3) OF VARCHAR2(10); / Type created.
  • 35. Database Management System (KCS-551) Lab Manual DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING Vandana Tripathi A. P (BBDITM C. S. E) Page 35 of 56 The basic syntax for creating a VARRAY type within a PL/SQL block is − TYPE varray_type_name IS VARRAY(n) of <element_type> For example − TYPE namearray IS VARRAY(5) OF VARCHAR2(10); Type grades IS VARRAY(5) OF INTEGER; Let us now work out on a few examples to understand the concept − Example 1 The following program illustrates the use of varrays − DECLARE type namesarray IS VARRAY(5) OF VARCHAR2(10); type grades IS VARRAY(5) OF INTEGER; names namesarray; marks grades; total integer; BEGIN names := namesarray('Kavita', 'Pritam', 'Ayan', 'Rishav', 'Aziz'); marks:= grades(98, 97, 78, 87, 92); total := names.count; dbms_output.put_line('Total '|| total || ' Students'); FOR i in 1 .. total LOOP dbms_output.put_line('Student: ' || names(i) || ' Marks: ' || marks(i)); END LOOP; END; / When the above code is executed at the SQL prompt, it produces the following result − Total 5 Students Student: Kavita Marks: 98 Student: Pritam Marks: 97 Student: Ayan Marks: 78 Student: Rishav Marks: 87 Student: Aziz Marks: 92
  • 36. Database Management System (KCS-551) Lab Manual DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING Vandana Tripathi A. P (BBDITM C. S. E) Page 36 of 56 Aim - Concepts for ROLL BACK, COMMIT & CHECK POINTS. Content – SQL - Transactions A transaction is a unit of work that is performed against a database. Transactions are units or sequences of work accomplished in a logical order, whether in a manual fashion by a user or automatically by some sort of a database program. A transaction is the propagation of one or more changes to the database. For example, if you are creating a record or updating a record or deleting a record from the table, then you are performing a transaction on that table. It is important to control these transactions to ensure the data integrity and to handle database errors. Practically, you will club many SQL queries into a group and you will execute all of them together as a part of a transaction. Properties of Transactions Transactions have the following four standard properties, usually referred to by the acronym ACID. • Atomicity − ensures that all operations within the work unit are completed successfully. Otherwise, the transaction is aborted at the point of failure and all the previous operations are rolled back to their former state. • Consistency − ensures that the database properly changes states upon a successfully committed transaction. • Isolation − enables transactions to operate independently of and transparent to each other. • Durability − ensures that the result or effect of a committed transaction persists in case of a system failure. Transaction Control The following commands are used to control transactions. • COMMIT − to save the changes. • ROLLBACK − to roll back the changes. Babu Banarasi Das Institute of Technology & Management, Lucknow LAB MANUAL Course Name: Database Management System Lab Experiment No. 8 Course Code: KCS 551 Branch: CSE Semester: V
  • 37. Database Management System (KCS-551) Lab Manual DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING Vandana Tripathi A. P (BBDITM C. S. E) Page 37 of 56 • SAVEPOINT − creates points within the groups of transactions in which to ROLLBACK. • SET TRANSACTION − Places a name on a transaction. Transactional Control Commands Transactional control commands are only used with the DML Commands such as - INSERT, UPDATE and DELETE only. They cannot be used while creating tables or dropping them because these operations are automatically committed in the database. The COMMIT Command The COMMIT command is the transactional command used to save changes invoked by a transaction to the database. The COMMIT command is the transactional command used to save changes invoked by a transaction to the database. The COMMIT command saves all the transactions to the database since the last COMMIT or ROLLBACK command. The syntax for the COMMIT command is as follows. COMMIT; Example Consider the CUSTOMERS table having the following records − +----+----------+-----+-----------+----------+ | ID | NAME | AGE | ADDRESS | SALARY | +----+----------+-----+-----------+----------+ | 1 | Ramesh | 32 | Ahmedabad | 2000.00 | | 2 | Khilan | 25 | Delhi | 1500.00 | | 3 | kaushik | 23 | Kota | 2000.00 | | 4 | Chaitali | 25 | Mumbai | 6500.00 | | 5 | Hardik | 27 | Bhopal | 8500.00 | | 6 | Komal | 22 | MP | 4500.00 | | 7 | Muffy | 24 | Indore | 10000.00 | +----+----------+-----+-----------+----------+ Following is an example which would delete those records from the table which have age = 25 and then COMMIT the changes in the database. SQL> DELETE FROM CUSTOMERS WHERE AGE = 25; SQL> COMMIT;
  • 38. Database Management System (KCS-551) Lab Manual DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING Vandana Tripathi A. P (BBDITM C. S. E) Page 38 of 56 Thus, two rows from the table would be deleted and the SELECT statement would produce the following result. +----+----------+-----+-----------+----------+ | ID | NAME | AGE | ADDRESS | SALARY | +----+----------+-----+-----------+----------+ | 1 | Ramesh | 32 | Ahmedabad | 2000.00 | | 3 | kaushik | 23 | Kota | 2000.00 | | 5 | Hardik | 27 | Bhopal | 8500.00 | | 6 | Komal | 22 | MP | 4500.00 | | 7 | Muffy | 24 | Indore | 10000.00 | +----+----------+-----+-----------+----------+ The ROLLBACK Command The ROLLBACK command is the transactional command used to undo transactions that have not already been saved to the database. This command can only be used to undo transactions since the last COMMIT or ROLLBACK command was issued. The syntax for a ROLLBACK command is as follows − ROLLBACK; Example Consider the CUSTOMERS table having the following records − +----+----------+-----+-----------+----------+ | ID | NAME | AGE | ADDRESS | SALARY | +----+----------+-----+-----------+----------+ | 1 | Ramesh | 32 | Ahmedabad | 2000.00 | | 2 | Khilan | 25 | Delhi | 1500.00 | | 3 | kaushik | 23 | Kota | 2000.00 | | 4 | Chaitali | 25 | Mumbai | 6500.00 | | 5 | Hardik | 27 | Bhopal | 8500.00 | | 6 | Komal | 22 | MP | 4500.00 | | 7 | Muffy | 24 | Indore | 10000.00 | +----+----------+-----+-----------+----------+ Following is an example, which would delete those records from the table which have the age = 25 and then ROLLBACK the changes in the database. SQL> DELETE FROM CUSTOMERS WHERE AGE = 25; SQL> ROLLBACK; Thus, the delete operation would not impact the table and the SELECT statement would produce the following result.
  • 39. Database Management System (KCS-551) Lab Manual DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING Vandana Tripathi A. P (BBDITM C. S. E) Page 39 of 56 +----+----------+-----+-----------+----------+ | ID | NAME | AGE | ADDRESS | SALARY | +----+----------+-----+-----------+----------+ | 1 | Ramesh | 32 | Ahmedabad | 2000.00 | | 2 | Khilan | 25 | Delhi | 1500.00 | | 3 | kaushik | 23 | Kota | 2000.00 | | 4 | Chaitali | 25 | Mumbai | 6500.00 | | 5 | Hardik | 27 | Bhopal | 8500.00 | | 6 | Komal | 22 | MP | 4500.00 | | 7 | Muffy | 24 | Indore | 10000.00 | +----+----------+-----+-----------+----------+ The SAVEPOINT Command A SAVEPOINT is a point in a transaction when you can roll the transaction back to a certain point without rolling back the entire transaction. The syntax for a SAVEPOINT command is as shown below. SAVEPOINT SAVEPOINT_NAME; This command serves only in the creation of a SAVEPOINT among all the transactional statements. The ROLLBACK command is used to undo a group of transactions. The syntax for rolling back to a SAVEPOINT is as shown below. ROLLBACK TO SAVEPOINT_NAME; Following is an example where you plan to delete the three different records from the CUSTOMERS table. You want to create a SAVEPOINT before each delete, so that you can ROLLBACK to any SAVEPOINT at any time to return the appropriate data to its original state. Example Consider the CUSTOMERS table having the following records. +----+----------+-----+-----------+----------+ | ID | NAME | AGE | ADDRESS | SALARY | +----+----------+-----+-----------+----------+ | 1 | Ramesh | 32 | Ahmedabad | 2000.00 | | 2 | Khilan | 25 | Delhi | 1500.00 | | 3 | kaushik | 23 | Kota | 2000.00 | | 4 | Chaitali | 25 | Mumbai | 6500.00 | | 5 | Hardik | 27 | Bhopal | 8500.00 | | 6 | Komal | 22 | MP | 4500.00 | | 7 | Muffy | 24 | Indore | 10000.00 | +----+----------+-----+-----------+----------+
  • 40. Database Management System (KCS-551) Lab Manual DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING Vandana Tripathi A. P (BBDITM C. S. E) Page 40 of 56 The following code block contains the series of operations. SQL> SAVEPOINT SP1; Savepoint created. SQL> DELETE FROM CUSTOMERS WHERE ID=1; 1 row deleted. SQL> SAVEPOINT SP2; Savepoint created. SQL> DELETE FROM CUSTOMERS WHERE ID=2; 1 row deleted. SQL> SAVEPOINT SP3; Savepoint created. SQL> DELETE FROM CUSTOMERS WHERE ID=3; 1 row deleted. Now that the three deletions have taken place, let us assume that you have changed your mind and decided to ROLLBACK to the SAVEPOINT that you identified as SP2. Because SP2 was created after the first deletion, the last two deletions are undone − SQL> ROLLBACK TO SP2; Rollback complete. Notice that only the first deletion took place since you rolled back to SP2. SQL> SELECT * FROM CUSTOMERS; +----+----------+-----+-----------+----------+ | ID | NAME | AGE | ADDRESS | SALARY | +----+----------+-----+-----------+----------+ | 2 | Khilan | 25 | Delhi | 1500.00 | | 3 | kaushik | 23 | Kota | 2000.00 | | 4 | Chaitali | 25 | Mumbai | 6500.00 | | 5 | Hardik | 27 | Bhopal | 8500.00 | | 6 | Komal | 22 | MP | 4500.00 | | 7 | Muffy | 24 | Indore | 10000.00 | +----+----------+-----+-----------+----------+ 6 rows selected. The RELEASE SAVEPOINT Command The RELEASE SAVEPOINT command is used to remove a SAVEPOINT that you have created. The syntax for a RELEASE SAVEPOINT command is as follows. RELEASE SAVEPOINT SAVEPOINT_NAME;
  • 41. Database Management System (KCS-551) Lab Manual DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING Vandana Tripathi A. P (BBDITM C. S. E) Page 41 of 56 Once a SAVEPOINT has been released, you can no longer use the ROLLBACK command to undo transactions performed since the last SAVEPOINT. The SET TRANSACTION Command The SET TRANSACTION command can be used to initiate a database transaction. This command is used to specify characteristics for the transaction that follows. For example, you can specify a transaction to be read only or read write. The syntax for a SET TRANSACTION command is as follows. SET TRANSACTION [ READ WRITE | READ ONLY ];
  • 42. Database Management System (KCS-551) Lab Manual DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING Vandana Tripathi A. P (BBDITM C. S. E) Page 42 of 56 Aim - Creating Procedure and Functions in MySQL/Oracle Content - A stored procedure is a prepared SQL code that you can save, so the code can be reused over and over again. So if you have an SQL query that you write over and over again, save it as a stored procedure, and then just call it to execute it. You can also pass parameters to a stored procedure, so that the stored procedure can act based on the parameter value(s) that is passed. Stored Procedure Syntax CREATE PROCEDURE procedure_name AS sql_statement GO; Execute a Stored Procedure EXEC procedure_name; The procedure syntax has the following parameters: MySQL procedure parameter has one of three modes: IN parameter It is the default mode. It takes a parameter as input, such as an attribute. When we define it, the calling program has to pass an argument to the stored procedure. This parameter's value is always protected. OUT parameters Babu Banarasi Das Institute of Technology & Management, Lucknow LAB MANUAL Course Name: Database Management System Lab Experiment No. 9 Course Code: KCS 551 Branch: CSE Semester: V
  • 43. Database Management System (KCS-551) Lab Manual DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING Vandana Tripathi A. P (BBDITM C. S. E) Page 43 of 56 It is used to pass a parameter as output. Its value can be changed inside the stored procedure, and the changed (new) value is passed back to the calling program. It is noted that a procedure cannot access the OUT parameter's initial value when it starts. NOUT parameters It is a combination of IN and OUT parameters. It means the calling program can pass the argument, and the procedure can modify the INOUT parameter, and then passes the new value back to the calling program. Call a stored procedure: We can use the CALL statement to call a stored procedure. This statement returns the values to its caller through its parameters (IN, OUT, or INOUT). The following syntax is used to call the stored procedure in MySQL: 1. CALL procedure_name ( parameter(s)) Example Let us understand how to create a procedure in MySQL through example. First, we need to select a database that will store the newly created procedure. We can select the database using the below statement: 1. mysql> USE database_name; Suppose this database has a table named student_info that contains the following data:
  • 44. Database Management System (KCS-551) Lab Manual DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING Vandana Tripathi A. P (BBDITM C. S. E) Page 44 of 56 Procedure without Parameter Suppose we want to display all records of this table whose marks are greater than 70 and count all the table rows. The following code creates a procedure named get_merit_students: 1. DELIMITER && 2. CREATE PROCEDURE get_merit_student () 3. BEGIN 4. SELECT * FROM student_info WHERE marks > 70; 5. SELECT COUNT(stud_code) AS Total_Student FROM student_info; 6. END && 7. DELIMITER ; If this code executed successfully, we would get the below output:
  • 45. Database Management System (KCS-551) Lab Manual DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING Vandana Tripathi A. P (BBDITM C. S. E) Page 45 of 56 Let us call the procedure to verify the output: 1. mysql> CALL get_merit_student(); It will give the output as follows: Procedures with IN Parameter In this procedure, we have used the IN parameter as 'var1' of integer type to accept a number from users. Its body part fetches the records from the table using a SELECT statement and returns only those rows that will be supplied by the user. It also returns the total number of rows of the specified table. See the procedure code: volume is gedempt
  • 46. Database Management System (KCS-551) Lab Manual DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING Vandana Tripathi A. P (BBDITM C. S. E) Page 46 of 56 1. DELIMITER && 2. CREATE PROCEDURE get_student (IN var1 INT) 3. BEGIN 4. SELECT * FROM student_info LIMIT var1; 5. SELECT COUNT(stud_code) AS Total_Student FROM student_info; 6. END && 7. DELIMITER ; After successful execution, we can call the procedure as follows: 1. mysql> CALL get_student(4); We will get the below output: Procedures with OUT Parameter In this procedure, we have used the OUT parameter as the 'highestmark' of integer type. Its body part fetches the maximum marks from the table using a MAX() function. See the procedure code: 1. DELIMITER && 2. CREATE PROCEDURE display_max_mark (OUT highestmark INT) 3. BEGIN 4. SELECT MAX(marks) INTO highestmark FROM student_info; 5. END && 6. DELIMITER ;
  • 47. Database Management System (KCS-551) Lab Manual DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING Vandana Tripathi A. P (BBDITM C. S. E) Page 47 of 56 This procedure's parameter will get the highest marks from the student_info table. When we call the procedure, the OUT parameter tells the database systems that its value goes out from the procedures. Now, we will pass its value to a session variable @M in the CALL statement as follows: 1. mysql> CALL display_max_mark(@M); 2. mysql> SELECT @M; Here is the output: Procedures with INOUT Parameter In this procedure, we have used the INOUT parameter as 'var1' of integer type. Its body part first fetches the marks from the table with the specified id and then stores it into the same variable var1. The var1 first acts as the IN parameter and then OUT parameter. Therefore, we can call it the INOUT parameter mode. See the procedure code: 1. DELIMITER && 2. CREATE PROCEDURE display_marks (INOUT var1 INT) 3. BEGIN 4. SELECT marks INTO var1 FROM student_info WHERE stud_id = var1;
  • 48. Database Management System (KCS-551) Lab Manual DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING Vandana Tripathi A. P (BBDITM C. S. E) Page 48 of 56 5. END && 6. DELIMITER ; After successful execution, we can call the procedure as follows: 1. mysql> SET @M = '3'; 2. mysql> CALL display_marks(@M); 3. mysql> SELECT @M; We will get the below output: Show or list stored procedures in MySQL When we have several procedures in the MySQL server, it is very important to list all procedures. It is because sometimes the procedure names are the same in many databases. In that case, this query is very useful. We can list all procedure stored on the current MySQL server as follows: . SHOW PROCEDURE STATUS [LIKE 'pattern' | WHERE search_condition] This statement displays all stored procedure names, including their characteristics.
  • 49. Database Management System (KCS-551) Lab Manual DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING Vandana Tripathi A. P (BBDITM C. S. E) Page 49 of 56 If we want to display procedures in a particular database, we need to use the WHERE clause. In case we want to list stored procedures with a specific word, we need to use the LIKE clause. We can list all stored procedure in the MySQL mystudentsb database using the below statement: 1. mysql> SHOW PROCEDURE STATUS WHERE db = 'mystudentdb'; It will give the below output where we can see that the mystudentdb database contains four stored procedures: Delete/drop stored procedures in MySQL MySQL also allows a command to drop the procedure. When the procedure is dropped, it is removed from the database server also. The following statement is used to drop a stored procedure in MySQL: 1. DROP PROCEDURE [ IF EXISTS ] procedure_name;
  • 50. Database Management System (KCS-551) Lab Manual DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING Vandana Tripathi A. P (BBDITM C. S. E) Page 50 of 56 Suppose we want to remove the procedure named display_marks from the mystudentdb database. We can do this by first selecting the database and then use the syntax as follows to remove the procedure: 1. mysql> DROP PROCEDURE display_marks; We can verify it by listing the procedure in the specified database using the SHOW PROCEDURE STATUS command. See the below output: Alter the procedure in MySQL MySQL does not allow any command to alter the procedure in MySQL. However,it provides a command that is used to change the characteristics of a stored procedure. This command may alter more than one change in the procedure but does not modify the stored procedure's parameters or body. If we want to make such changes, we must drop and re-create the procedure using the DROP PROCEDURE and
  • 51. Database Management System (KCS-551) Lab Manual DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING Vandana Tripathi A. P (BBDITM C. S. E) Page 51 of 56 CREATE PROCEDURE statement. The below statement is used to change the characteristics of a procedure but not the actual procedure: 1. ALTER PROCEDURE procedure_name [characteristics ...] 2. 3. characteristics: { 4. COMMENT 'string' 5. | LANGUAGE SQL 6. | { CONTAINS SQL | NO SQL | READS SQL DATA | MODIFIES SQL DATA } 7. | SQL SECURITY { DEFINER | INVOKER } 8. } Suppose we want to add a comment to the existing procedure. In such a case, we can use the ALTER statement as follows to accomplish this task: 1. mysql> ALTER PROCEDURE get_merit_student 2. COMMENT 'It displays all records'; After executing this statement, we can verify it by using the below statement: 1. mysql> SHOW CREATE PROCEDURE get_merit_student G; It will display the below output where we can see that the comment is added successfully.
  • 52. Database Management System (KCS-551) Lab Manual DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING Vandana Tripathi A. P (BBDITM C. S. E) Page 52 of 56
  • 53. Database Management System (KCS-551) Lab Manual DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING Vandana Tripathi A. P (BBDITM C. S. E) Page 53 of 56 Aim - Creating Cursor and Trigger in MySQL/Oracle. Content – Triggers in PL/SQL. Triggers are stored programs, which are automatically executed or fired when some events occur. Triggers are, in fact, written to be executed in response to any of the following events − • A database manipulation (DML) statement (DELETE, INSERT, or UPDATE) • A database definition (DDL) statement (CREATE, ALTER, or DROP). • A database operation (SERVERERROR, LOGON, LOGOFF, STARTUP, or SHUTDOWN). Triggers can be defined on the table, view, schema, or database with which the event is associated. Benefits of Triggers Triggers can be written for the following purposes − • Generating some derived column values automatically • Enforcing referential integrity • Event logging and storing information on table access • Auditing • Synchronous replication of tables • Imposing security authorizations • Preventing invalid transactions Creating Triggers The syntax for creating a trigger is − CREATE [OR REPLACE ] TRIGGER trigger_name {BEFORE | AFTER | INSTEAD OF } {INSERT [OR] | UPDATE [OR] | DELETE} [OF col_name] ON table_name [REFERENCING OLD AS o NEW AS n] [FOR EACH ROW] WHEN (condition) DECLARE Declaration-statements Babu Banarasi Das Institute of Technology & Management, Lucknow LAB MANUAL Course Name: Database Management System Lab Experiment No. 10 Course Code: KCS 551 Branch: CSE Semester: V
  • 54. Database Management System (KCS-551) Lab Manual DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING Vandana Tripathi A. P (BBDITM C. S. E) Page 54 of 56 BEGIN Executable-statements EXCEPTION Exception-handling-statements END; Where, • CREATE [OR REPLACE] TRIGGER trigger_name − Creates or replaces an existing trigger with the trigger_name. • {BEFORE | AFTER | INSTEAD OF} − This specifies when the trigger will be executed. The INSTEAD OF clause is used for creating trigger on a view. • {INSERT [OR] | UPDATE [OR] | DELETE} − This specifies the DML operation. • [OF col_name] − This specifies the column name that will be updated. • [ON table_name] − This specifies the name of the table associated with the trigger. • [REFERENCING OLD AS o NEW AS n] − This allows you to refer new and old values for various DML statements, such as INSERT, UPDATE, and DELETE. • [FOR EACH ROW] − This specifies a row-level trigger, i.e., the trigger will be executed for each row being affected. Otherwise the trigger will execute just once when the SQL statement is executed, which is called a table level trigger. • WHEN (condition) − This provides a condition for rows for which the trigger would fire. This clause is valid only for row-level triggers. Example To start with, we will be using the CUSTOMERS table we had created and used in the previous chapters − Select * from customers; +----+----------+-----+-----------+----------+ | ID | NAME | AGE | ADDRESS | SALARY | +----+----------+-----+-----------+----------+ | 1 | Ramesh | 32 | Ahmedabad | 2000.00 | | 2 | Khilan | 25 | Delhi | 1500.00 | | 3 | kaushik | 23 | Kota | 2000.00 | | 4 | Chaitali | 25 | Mumbai | 6500.00 | | 5 | Hardik | 27 | Bhopal | 8500.00 | | 6 | Komal | 22 | MP | 4500.00 | +----+----------+-----+-----------+----------+ The following program creates a row-level trigger for the customers table that would fire for INSERT or UPDATE or DELETE operations performed on the CUSTOMERS table. This trigger will display the salary difference between the old values and new values − CREATE OR REPLACE TRIGGER display_salary_changes
  • 55. Database Management System (KCS-551) Lab Manual DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING Vandana Tripathi A. P (BBDITM C. S. E) Page 55 of 56 BEFORE DELETE OR INSERT OR UPDATE ON customers FOR EACH ROW WHEN (NEW.ID > 0) DECLARE sal_diff number; BEGIN sal_diff := :NEW.salary - :OLD.salary; dbms_output.put_line('Old salary: ' || :OLD.salary); dbms_output.put_line('New salary: ' || :NEW.salary); dbms_output.put_line('Salary difference: ' || sal_diff); END; / When the above code is executed at the SQL prompt, it produces the following result − Trigger created. The following points need to be considered here − • OLD and NEW references are not available for table-level triggers, rather you can use them for record-level triggers. • If you want to query the table in the same trigger, then you should use the AFTER keyword, because triggers can query the table or change it again only after the initial changes are applied and the table is back in a consistent state. • The above trigger has been written in such a way that it will fire before any DELETE or INSERT or UPDATE operation on the table, but you can write your trigger on a single or multiple operations, for example BEFORE DELETE, which will fire whenever a record will be deleted using the DELETE operation on the table. Triggering a Trigger Let us perform some DML operations on the CUSTOMERS table. Here is one INSERT statement, which will create a new record in the table − INSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY) VALUES (7, 'Kriti', 22, 'HP', 7500.00 ); When a record is created in the CUSTOMERS table, the above create trigger, display_salary_changes will be fired and it will display the following result − Old salary: New salary: 7500 Salary difference:
  • 56. Database Management System (KCS-551) Lab Manual DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING Vandana Tripathi A. P (BBDITM C. S. E) Page 56 of 56 Because this is a new record, old salary is not available and the above result comes as null. Let us now perform one more DML operation on the CUSTOMERS table. The UPDATE statement will update an existing record in the table − UPDATE customers SET salary = salary + 500 WHERE id = 2; When a record is updated in the CUSTOMERS table, the above create trigger, display_salary_changes will be fired and it will display the following result − Old salary: 1500 New salary: 2000 Salary difference: 500