DBMS Manual2
DBMS Manual2
VISION
“To attain global excellence through education, innovation, research, and work ethics with
the commitment to serve humanity.”
MISSION
The Institute shall endeavour to incorporate the following basic missions in the teaching
methodology:
M2. To foster moral values in students and equip them for developing sustainable solutions to serve
both national and global needs in society and industry.
M3. To digitize educational resources and process for enhanced teaching and effective learning.
M5. To encourage faculty-student networking with alumni, industry, institutions, and other
stakeholders for collective engagement.
i
MAHARAJA AGRASEN INSTITUTE OF TECHNOLOGY
VISION
“To attain global excellence through education, innovation, research, and work ethics in the field of
Computer Science and engineering with the commitment to serve humanity.”
MISSION
M1: To lead in the advancement of computer science and engineering through internationally
recognized research and education.
M2: To prepare students for full and ethical participation in a diverse society and encourage
lifelong learning.
M3: To foster development of problem solving and communication skills as an integral
component of the profession.
M4: To impart knowledge, skills and cultivate an environment supporting incubation, product
development, technology transfer, capacity building and entrepreneurship in the field of
computer science and engineering.
M5: To encourage faculty, student’s networking with alumni, industry, institutions, and other
stakeholders for collective engagement.
ii
Program Outcomes (POs)
Engineering Graduates will be able to:
1.Engineering knowledge: Apply the knowledge of mathematics, science, engineering fundamentals,
and an engineering specialization to the solution of complex engineering problems.
2.Problem analysis: Identify, formulate, review research literature, and analyze complex engineering
problems reaching substantiated conclusions using first principles of mathematics, natural sciences, and
engineering sciences.
3.Design/development of solutions: Design solutions for complex engineering problems and design
system components or processes that meet the specified needs with appropriate consideration for the
public health and safety, and the cultural, societal, and environmental considerations.
4.Conduct investigations of complex problems: Use research-based knowledge and research methods
including design of experiments, analysis and interpretation of data, and synthesis of the information to
provide valid conclusions.
5.Modern tool usage: Create, select, and apply appropriate techniques, resources, and modern
engineering and IT tools including prediction and modeling to complex engineering activities with an
understanding of the limitations.
6.The engineer and society: Apply reasoning informed by the contextual knowledge to assess societal,
health, safety, legal and cultural issues and the consequent responsibilities relevant to the professional
engineering practice.
7.Environment and sustainability: Understand the impact of the professional engineering solutions in
societal and environmental contexts, and demonstrate the knowledge of, and need for sustainable
development.
8.Ethics: Apply ethical principles and commit to professional ethics and responsibilities and norms of
the engineering practice.
9.Individual and team work: Function effectively as an individual, and as a member or leader indiverse
teams, and in multidisciplinary settings.
11.Project management and finance: Demonstrate knowledge and understanding of the engineering
and management principles and apply these to one’s own work, as a member and leader in a team, to
manage projects and in multidisciplinary environments.
12.Life-long learning: Recognize the need for, and have the preparation and ability to engage in
independent and life-long learning in the broadest context of technological change
iii
Program Specific Outcome (PSO)
PSO1: Able to explore and apply emerging technologies in computer science and engineering such as
Artificial Intelligence, Machine Learning, Data Science, etc.
PSO2: Able to independently and collaboratively design, develop and evaluate innovative solutions to
existing problems, addressing the needs of industry and society.
PSO3: Able to pursue advanced studies, conduct research and development, and cultivate
entrepreneurship skills in the modern computing environment.
PEO1: Graduates will work with the top institutions and researchers, dedicating themselves to lifelong
learning and social responsibility. (M1, M2)
PEO2: Graduates will exhibit outstanding communication skills and the capacity to collaborate
effectively within diverse teams. (M3)
PEO3: Graduates cultivating skills in computer science and engineering contribute to driving
innovation,
entrepreneurship, and economic growth. (M4)
PEO4: Graduates network with stakeholders to contribute to the growth of the department. (M5)
iv
INDEX OF THE CONTENTS
Page No:
v
1. Introduction to the Lab
Course Objectives:
PO1 PO2 PO3 PO4 PO5 PO6 PO7 PO8 PO9 PO10 PO11 PO12
CO1 3 3 3 2 2 1 1 1 1 2 1 2
CO2 3 3 3 2 2 1 1 1 1 2 1 2
CO3 3 3 3 2 3 2 1 2 1 2 1 2
CO4 3 3 3 2 3 1 1 1 2 2 1 2
CO1 2 2 1
CO2 2 2 1
CO3 3 3 2
CO4 3 3 3
1
2. LAB REQUIREMENTS
Hardware Detail
LaserJet Printer 1 No
Software Detail
Operating System: Fedora, Linux
Software: Maria DB
2
3. LIST OF EXPERIMENTS (As prescribed by G.G.S.I.P.U)
1. Experiments based on DDL commands – CREATE, ALTER, DROP and TRUNCATE. (CO1, CO2)
2. Apply the integrity constraints like Primary Key, Foreign key, Check, NOT NULL, etc. to the
tables. (CO3)
3. Experiments based on basic DML commands – SELECT, INSERT, UPDATE and DELETE. (CO2)
4. Write the queries for implementing Built-in functions, GROUP BY, HAVING and ORDER BY.
(CO3)
8. Write the queries to create the views and queries based on views. (CO4)
3
4. LIST OF EXPERIMENTS (beyond syllabus)
1. The Institute offers multiple B. Tech Courses. Students can take admission in any Course offered by the
Institute. Multiple subjects are taught in each branch. The institute has a Director and Hod of each B. Tech
Course. The HoD of another branch may be given additional responsibility to take charge of one more
department for a limited period in the absence of Hod of that branch. Faculties recruited in each B. Tech
Course can teach only a single same subject to students of different B.Tech Courses. For each subject,
there is a faculty coordinator responsible for coordinating all the faculties teaching the same subject. A
batch of 20 students is assigned a faculty mentor. The mentor takes counsellor meetings twice a month.
Draw the ER diagram (Conceptual design) of the given problem statement. (CO1)
2. To demonstrate a connection to a MariaDB database using the following languages: C, Java and Python
4
Database Management System
CIC-256
Faculty name : Dr. Prerna Sharma Student name : Nikil Kumar Agrawal
RollNo: 08614802723
Semester: 4th
5
Database Management System Lab (CIC - 256) Lab Assessment Sheet
R1 R2 R3 R4 R5
Total
Faculty
S.No Experiment Marks Remarks
Signature
(10)
2 2 2 2 2
Marks Marks Marks Marks Marks
10
6
6. MARKING SCHEME FOR THE PRACTICAL EXAMS
Total Marks: 40
Is proposed
PO1, PO2, PSO1,
R2 design/procedure/algorithm No Partially Completely
PO3 PSO2
solves the problem?
Has the understanding of
the tool/programming PO1, PO3, PSO1,
R3 No Partially Completely
language to implement the PO5 PSO2
proposed solution?
Are the result(s) verified
PO2, PO4,
R4 using sufficient test data to No Partially Completely PSO2
PO5
support the conclusions?
Individuality of PSO1,
R5 No Partially Completely PO8, PO12
submission? PSO3
Each experiment will be evaluated out of 10 marks. At the end of the semester, an average of 8 best
performed practical’s will be considered as marks out of 40.
7
It is taken by the concerned lecturer of the batch and by an external examiner. In this exam, the
student needs to perform the experiment allotted at the time of the examination; a sheet will be
given to the student in which some details asked by the examiner need to be written, and at the
last, viva will be taken by the external examiner.
Total Marks: 60
2. Viva Voice: 15
3. Experiment performance: 15
4. File submitted: 10
NOTE:
• Internal marks + External marks = Total marks given to the students (40
marks) (60 marks) (100 marks)
A database management system (DBMS) is software that controls the storage, organization, and retrieval
of data. Typically, a DBMS has the following elements:
• Kernel code
This code manages memory and storage for the DBMS.
8
• Repository of metadata
This repository is usually called a data dictionary.
• Query language
This language enables applications to access the data.
A database application is a software program that interacts with a database to access and
manipulate data.
Database Management Systems (DBMS) can be categorized into different generations based on
their development and features.
2. Query Compiler:
- The query compiler receives the user's query and performs the necessary analysis and
transformations to generate an optimized query execution plan. It analyzes the query syntax,
9
checks the query against the database schema, performs query optimization, and generates an
execution plan.
3. Query Optimizer:
- The query optimizer evaluates multiple possible execution plans for a given query and
selects the most efficient plan based on factors like cost estimation, data access paths, join
strategies, and index usage. The goal is to minimize the overall execution time and resource
utilization.
4. Execution Engine:
- The execution engine takes the optimized query execution plan and performs the actual
execution of the query against the database. It consists of several sub-components:
c. Transaction Manager:
- The transaction manager ensures the ACID properties of database
transactions (Atomicity, Consistency, Isolation, Durability). It handles
concurrency control, manages transaction boundaries, and ensures data
consistency during transaction execution.
d. Memory Manager:
- The memory manager handles the allocation and deallocation of memory
resources used by the DBMS. It optimizes memory usage to minimize disk I/O
operations and improve overall performance.
5. Storage Manager:
10
- The storage manager is responsible for managing the physical storage of data on disk or
other storage devices. It handles tasks such as data organization, file management, disk space
allocation, and I/O operations.
6. Data Dictionary:
- The data dictionary (also called the system catalog) stores metadata about the database,
including the schema definition, data types, constraints, indexes, and other information. It is
used by the DBMS components for query analysis, optimization, and execution.
The evaluation engine, encompassing the query compiler, query optimizer, and execution
engine, plays a crucial role in processing user queries and ensuring efficient execution. It
transforms high-level queries into low-level operations, optimizes their execution, and
coordinates the various components involved in retrieving and manipulating data.
1. Tabular Structure: RDBMS organizes data into tables or relations, with rows
representing individual records and columns representing attributes or fields. This tabular
structure allows for structured and organized storage of data.
11
3. Data Integrity: RDBMS enforces integrity constraints to ensure the accuracy and reliability
of the data. Constraints include primary keys, foreign keys, unique constraints, and check
constraints, which maintain the relationships between tables and prevent inconsistent or
invalid data.
5. Relationships and Joins: RDBMS supports relationships between tables through primary
key and foreign key associations. Joins allow for combining data from multiple tables based
on related columns, enabling complex data retrieval and analysis.
6. Data Independence: RDBMS provides logical and physical data independence. Logical data
independence allows applications to be isolated from changes in the database structure,
while physical data independence separates the logical view of data from the physical
storage details.
7. Scalability and Performance: RDBMS can handle large amounts of data and support
highperformance operations. Techniques like indexing, query optimization, and
caching are employed to improve query response times and overall system performance.
8. Security: RDBMS offers built-in security mechanisms to control access to the data. This
includes authentication, authorization, and privileges management to ensure that only
authorized users can access and modify the data.
12
9. Data Backup and Recovery: RDBMS provides mechanisms for data backup and recovery to
protect against data loss or system failures. This includes features like transaction logging,
point-in-time recovery, and database backups.
• DB2
• MySQL
• Maria DB
• Oracle
• PostgreSQL
• SQL Server
• Sybase
Structured Query Language is a database computer language designed for managing data in
relational database management systems (RDBMS), and originally based upon Relational
Algebra. Its scope includes data query and update, schema creation and modification, and data
access control.
SQL was one of the first languages for Edgar F. Codd's relational model and became the most
widely used language for relational databases.
The tables in the following sections provide a functional summary of SQL statements and
are divided into these categories:
Data Types:
13
Data Type Description Example
INT Integer age
INT
VARCHAR(n) Variable-length character string name
VARCHAR(50)
CHAR(n) Fixed-length character string code
CHAR(10)
TEXT Variable-length text description
TEXT
DATE Date birth_date
DATE
TIME Time entry_time
TIME
DATETIME Date and time created_at
DATETIME
BOOLEAN / BOOL Boolean value (0 or 1) is_active
BOOLEAN
DECIMAL(p, s) Fixed-point decimal number price
DECIMAL(8, 2)
FLOAT(p) Floating-point number salary
FLOAT(10)
DOUBLE(p) Double-precision floating-point number distance
DOUBLE(8)
ENUM Enumeration (a list of permitted values) status ENUM('active',
'inactive')
SET Set (a list of permitted values) permissions SET('read',
'write')
BLOB Binary Large Object (for binary data) image
BLOB
JSON JSON data type metadata
JSON
Experiment-1
14
Experiment-1
Aim: Experiments based on DDL commands – CREATE, ALTER, DROP and TRUNCATE.
Tool Used: Maria DB
SYNTAX:
CREATE TABLE table_name
(column1 datatype, column2
datatype, column3 datatype,
);
PART-I: Creation of tables
OUTPUT TABLE:
OUTPUT TABLE:
INPUT QUERY:
CREATE TABLE SALESMAN_MASTER(SALESMANNO VARCHAR(6),
SALESMANNAME VARCHAR(220),
ADDRESS1 VARCHAR(30), ADDRESS2 VARCHAR(30),
CITY VARCHAR(20) , PINCODE INT(11) , STATE VARCHAR(20),
SALAMT DECIMAL(8,2) );
OUTPUT TABLE:
16
PART-II: Alter of values into tables
17
Input Query to drop the ADDRESS2 column from SALESMAN_MASTER table;
19
PRACTICE QUESTIONS:
1. Create a table EMPLOYEE with following schema:
(Emp_no, E_name, E_address, E_ph_no, Dept_no, Dept_name,Job_id , Salary)
20
5. Modify the column width of the job field of emp table
6. Truncate the data from the "Orders" table, keeping the table structure intact.
VIVA - QUESTIONS:
21
Que1. What is a NULL value and how does it differ from a zero value?
Aim: Apply the integrity constraints like Primary Key, Foreign key, Check, NOT NULL, etc. to the
tables.
The following SQL ensures that the "ID", "LastName", and "FirstName" columns will NOT accept
NULL values when the "Persons" table is created:
CREATE TABLE
Persons ( ID int
NOT NULL,
22
LastName varchar(255) NOT NULL,
FirstName varchar(255) NOT
NULL, Age int );
UNIQUE Constraint
The UNIQUE constraint ensures that all values in a column are different.
Both the UNIQUE and PRIMARY KEY constraints provide a guarantee for uniqueness for a
CREATE TABLE
Persons ( ID int
NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int,
UNIQUE
(ID)
);
CREATE TABLE
Persons ( ID int
NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int,
PRIMARY KEY (ID)
);
23
CREATE TABLE Orders ( OrderID
int NOT NULL,
OrderNumber int NOT
NULL, PersonID int,
PRIMARY KEY (OrderID),
FOREIGN KEY (PersonID) REFERENCES Persons(PersonID)
);
CHECK Constraint
The CHECK constraint is used to limit the value range that can be placed in a column.If you
define a CHECK constraint on a single column it allows only certain values for this column.If
you define a CHECK constraint on a table it can limit the values in certain columns based on
values in other columns in the row
CREATE TABLE
Persons ( ID
int NOT
NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int,
CHECK (Age>=18)
);
DEFAULT Constraint
The DEFAULT constraint is used to provide a default value for a column.
The default value will be added to all new records IF no other value is specified
CREATE TABLE
Persons ( ID int
NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int,
City varchar(255) DEFAULT 'Sandnes'
);
Schema Diagram:
24
Table Creation
CREATE TABLE
CLASS ( USN
VARCHAR (10),
SSID VARCHAR (5),
PRIMARY KEY (USN,
SSID),
FOREIGN KEY (USN) REFERENCES STUDENT
(USN), FOREIGN KEY (SSID) REFERENCES SEMSEC
(SSID));
25
(SUBCODE));
CREATE TABLE
IAMARKS ( USN
VARCHAR (10),
SUBCODE VARCHAR (8),
SSID VARCHAR (5),
TEST1 NUMBER (2),
TEST2 NUMBER (2),
TEST3 NUMBER (2),
FINALIA NUMBER (2),
PRIMARY KEY (USN, SUBCODE, SSID),
FOREIGN KEY (USN) REFERENCES STUDENT (USN),
FOREIGN KEY (SUBCODE) REFERENCES SUBJECT (SUBCODE),
FOREIGN KEY (SSID) REFERENCES SEMSEC (SSID));
DESC SEMSEC;
DESC CLASS;
DESC SUBJECT;
26
DESC IAMARKS;
27
PRACTICE QUESTIONS:
Schema Diagram
VIVA – QUESTIONS:
INPUT QUERY:
insert into product_master values('P00001',' T-Shirts ',5,'Piece',200,50,5350,250); insert into
product_master values('P0345',' Shirts ',6,'Piece',150,50,500,350);
insert into product_master values('P06734',' Cotton Jeans ',5,'Piece',100,20,600,450); insert
into product_master values('P07865',' Jeans ',5,'Piece',100,20,750,500); insert into
product_master values('P07868','Trousers',2,'Piece',150,50,850,550); insert into
product_master values('P07885',' Pull Overs ',2.5,'Piece',80,30,700,450); insert into
product_master values('P07965',' Denim Shirts ',4,'Piece',100,40,350,250); insert into
product_master values('P07975',' Lycra Tops’,5,'Piece',70,30,300,175); insert into
product_master values('P08865',' Skirts ',5,'Piece',75,30,450,300);
After executing the above commands you will get following table:
30
Jeans
P07865 Jeans 5 Piece 100 20 750 500
P07868 Trousers 2 Piece 150 50 850 550
P07885 Pull Overs 2.5 Piece 80 30 700 450
P07965 Denim 4 Piece 100 40 350 250
Shirts
P07975 Lycra Tops 5 Piece 70 30 300 175
P08865 Skirts 5 Piece 75 30 450 300
PART-II: In this experiment we will be focusing on SELECT command which comes under
DDL and WHERE clause.
Name
Ivan
MamtaMuzumdar
ChhayaBankar
Ashwini Joshi
31
Hansel Colaco
Deepak Sharma
c. Retrieve the list of names, city and the state of all the clients.
INPUT QUERY: SELECT NAME, CITY, STATE FROM CLIENT_MASTER;
Name
MamtaMuzumdar
Ashwini Joshi
Deepak Sharma
32
e.List all the clients who are located in Mumbai.
INPUT QUERY: SELECT NAME FROM CLIENT_MASTER WHERE CITY = ‘Mumbai’;
Name
ChhayaBankar
Hansel Colaco
PART-III: In this experiment we will be focusing on commands like update and delete
commands which comes under DML .We will be applying these commands on records we
already created in experiment 1.
SYNTAX: UPDATE
UPDATE table_name
SET column1 = value1, column2 =
value2, WHERE condition;
SYNTAX: DELETE
Client No City
33
C00005 Bangalore
34
In same Manner values can be inserted into SALESMAN_MASTER table :
d. Delete all salesmen from the Salesman_Master whose salaries are equal to Rs. 3500.
INPUT QUERY: delete salesmen from salesmen_master where salary='3500';
SAMPLE OUTPUT DATA: It will delete all the salemen from salesmen_master table where
salary od salemen is 3500.
e. Delete all product from Product_Master where the quantity on hand us equal to 100.
INPUT QUERY: Similar to the one above.
SAMPLE OUTPUT DATA: It will delete all the products from Product_master table where
quantity on hand is 100
f. Delete from Client_Master where the column state holds the value “Tamil Nadu”.
INPUT QUERY: Similar to the one above.
SAMPLE OUTPUT DATA: It will delete from Client_master table where state holds “Tamil
Nadu”.
35
PRACTICE QUESTIONS:
VIVA- QUESTIONS:
36
Experiment-4
Aim: Write the queries for implementing Built-in functions, GROUP BY, HAVING and ORDER BY.
Tool Used: Maria DB
MIN() Syntax: The MIN() function returns the smallest value of the selected column.
SELECT
MIN(column_
name) FROM
table_name
WHERE
condition;
Example: SELECT MIN (Sal) FROM emp;
MAX() Syntax: The MAX() function returns the largest value of the selected column.
SELECT
MAX(column
_name)
FROM
table_name
WHERE
condition;
Example: SELECT MAX (Sal) FROM emp;
COUNT() Syntax: The COUNT() function returns the number of rows that matches a specified
criteria.
SELECT
COUNT(column_n
ame) FROM
table_name
WHERE
condition;
Example: SELECT COUNT (Sal) FROM emp;
AVG() Syntax: The AVG() function returns the average value of a numeric column.
SELECT
AVG(column_
name) FROM
table_name
WHERE
condition;
Example: Select AVG (10, 15, 30) FROM DUAL;
SUM() Syntax: The SUM() function returns the total sum of a numeric column.
37
SELECT
SUM(column_
name) FROM
table_name
WHERE
condition;
Example: SELECT SUM (Sal) From emp;
PART-II : In this experiment we will be working on clauses like HAVING, GROUP BY and
ORDER BY to be applied on a table .
GROUP BY: The GROUP BY statement is often used with aggregate functions (COUNT, MAX,
MIN, SUM, AVG) to group the result-set by one or more columns.
SELECT column_name(s)
FROM
table_name WHERE
condition
GROUP BY column_name(s)
ORDER BY column_name(s);
A) The following SQL statement lists the number of customers in each country:
B) The following SQL statement lists the number of customers in each country, sorted high to low:
SELECT COUNT(CustomerID),
38
Country FROM Customers
GROUP BY Country
ORDER BY COUNT(CustomerID) DESC;
HAVING clause: The HAVING clause was added to SQL because the WHERE
keyword could not be used with aggregate functions. Syntax: SELECT
column_name(s) FROM
table_name WHERE
condition
GROUP BY column_name(s)
HAVING condition
ORDER BY column_name(s);
A) The following SQL statement lists the number of customers in each country. Only include
countries with more than 5 customers:
SELECT COUNT(CustomerID),
Country FROM Customers
GROUP BY Country
HAVING COUNT(CustomerID) > 5 ;
B) The following SQL statement lists the number of customers in each country, sorted high to
low (Only include countries with more than 5 customers):
SELECT COUNT(CustomerID),
Country FROM Customers
GROUP BY Country
HAVING COUNT(CustomerID) > 5
ORDER BY COUNT(CustomerID)
DESC;
Now some Queries using the above clauses:
Sales:
product_id sales_date quantity_sold
1 2023-01- 10
01
1 2023-01- 15
02
2 2023-01- 5
01
2 2023-01- 20
02
39
3 2023-01- 8
01
3 2023-01- 12
02
1. Count the number of sales for each product: SELECT product_id, COUNT(*) AS sales_count FROM
Sales GROUP BY product_id;
Output:
product_id Sales_count
1 2
2 2
3 2
Output:
product_id total_quantity_sold
1 25
2 25
3 20
product_id total_quantity_sold
1 25
2 25
40
4. Find products with an average sales quantity greater than 10 units:
SELECT product_id, AVG(quantity_sold) AS avg_quantity_sold
FROM Sales
GROUP BY product_id
HAVING AVG(quantity_sold) > 10;
product_id avg_quantity_sold
1 12.5
2 12.5
3 10
ORDER BY:
This query is used to display a selected set of fields from a relation in an ordered manner base on some
field.
Example: SQL> SELECT empno, ename, job FROM emp ORDER BY job;
41
PRACTICE QUESTIONS:
Schema:
Sales
1. Calculate the total quantity sold for each product, but only show products with a total quantity
sold greater than or equal to 25.
2. Count the number of sales for each product and sales date, but only show those with more than
one sale on any date.
3. Find products that have never sold more than 10 units in a single sale.
4. Calculate the total quantity sold for each product and show only those with an average quantity
sold less than or equal to 15 units.
VIVA – QUESTIONS:
Types of Joins
42
In Sql Server we have only three types of joins. Using these joins we fetch the data from multiple
tables based on condition.
Inner Join
Inner join returns only those records/rows that match/exists in both the tables. Syntax for Inner
Join is as
Outer Join
We have three types of Outer Join.
Left Outer Join
Left outer join returns all records/rows from left table and from right table returns only
matched records. If there are no columns matching in the right table, it returns NULL
values. Syntax for Left outer Join is as :
Select * from table_1 as t1 left outer join table_2 as t2 on t1.IDcol=t2.IDcol
Right outer join returns all records/rows from right table and from left table returns only
matched records. If there are no columns matching in the left table, it returns NULL
values. Syntax for right outer Join is as :
43
Select * from
table_1 as t1 right
outer join table_2 as
t2 on
t1.IDcol=t2.IDcol
Full outer join combines left outer join and right outer join. This join returns all
records/rows from both the tables.If there are no columns matching in the both tables, it
returns NULL values. Syntax for full outer Join is as :
Select * from table_1 as t1
full outer join table_2 as t2 on
t1.IDcol=t2.IDcol
Cross Join
Cross join is a cartesian join means cartesian product of both the tables. This join does not
need any condition to join two tables. This join returns records/rows that are
multiplication of record number from both the tables means e ach row on left table will
related to each row of right table. Syntax for right outer Join is as :
Select *
from table_1
cross join
table_2
Self-Join
Self-join is used to join a database table to itself, particularly when the table has a Foreign
key that references its own Primary Key. Basically we have only three types of joins :
Inner join, Outer join and Cross join. We use any of these three JOINS to join a table to
itself. Hence Self join is not a type of Sql join.
44
Next we will solve some Queries which uses above different types of JOIN operations. Customer:
Order:
Queries:
1. INNER JOIN to Retrieve Customer Orders with Customer Details:
2. LEFT JOIN to Retrieve All Customers and Their Orders (Including Customers with No
Orders):
45
LEFT JOIN Orders O ON C.customer_id = O.customer_id;
SELECT * FROM
46
Orders CROSS JOIN
Customers;
47
; PRACTICE
QUESTIONS:
1. Find all information of sailors who have reserved boat number 101.
2. Find the name of boat reserved by Bob.
3. Find the names of sailors who have reserved a red boat, and list in the order of age.
4. Find the names of sailors who have reserved at least one boat.
5. Find the ids and names of sailors who have reserved two different boats on the same day.
6. Find the ids of sailors who have reserved a red boat or a green boat.
48
7. Find the name and the age of the youngest sailor.
8. Count the number of different sailor names.
9. Find the average age of sailors for each rating level.
10. Find the average age of sailors for each rating level that has at least two sailors.
VIVA - QUESTIONS:
Theory:
SUBQUERIES: The query within another is known as a sub query. A statement containing sub query is
called parent statement. The rows returned by sub query are used by the parent statement or in other
words A subquery is a SELECT statement that is embedded in a clause of another SELECT statement You
can place the subquery in a number of SQL clauses:
• WHERE clause
• HAVING clause
• FROM clause
• OPERATORS( IN.ANY,ALL,<,>,>=,<= etc.)
Types
1. Sub queries that return several values
Sub queries can also return more than one value. Such results should be made use along with the operators in
and any.
2. Multiple queries
49
Here more than one sub query is used. These multiple sub queries are combined by means of ‘and’ & ‘or’
keywords.
A sub query is evaluated once for the entire parent statement whereas a correlated Sub query is evaluated once per
row processed by the parent statement.
Student Database
Course database
50
CSC106 IT Computer4 135000
CSC107 Mechanical mech 123000
Registration database
Student_id Course_id
S1 CSC101
S2 CSC102
S3 CSC103
S4 CSC104
S5 CSC105
S6 CSC106
S7 CSC107
1. Find all students who have scored higher than the average score in a specific subject:
SELECT
student_name
FROM students
WHERE score > (SELECT AVG(score) FROM scores WHERE subject = 'Math'); Output:
2. Get the list of students who have not registered for any course:
SELECT
student_name
FROM students
WHERE student_id NOT IN (SELECT DISTINCT student_id FROM registrations);
PRACTICE QUESTIONS:
1. Retrieve the details of students who have scored the highest marks in each subject.
51
2. Find the courses taken by students from a specific city.
3. Retrieve the names of students who have taken all available courses.
4. Find the courses with the highest enrolment.
5. Get the list of students who have scored lower than the average score in all subjects.
6. Retrieve the names of students who have not registered for a specific course.
7. Find the courses with no registered students.
8. Retrieve the names of students who have registered for all courses in a specific department.
VIVA - QUESTIONS:
Experiment- 7
52
Tool Used: Maria DB
Theory: Set operations in DBMS are operations that allow you to combine or compare the results of two or more
queries.
1.UNION: Combines results from multiple SELECT statements, removing duplicates, and returns all distinct rows
from each query. Requires the same number of columns with compatible data types.
2.UNION ALL: Similar to UNION but includes duplicate rows in the result set. It returns all rows from each query
without removing duplicates.
3.INTERSECT: Retrieves common rows between SELECT statements, finding the intersection of sets. Requires
matching column count and data types.
4.EXCEPT (or MINUS): Returns rows from the first SELECT statement not found in subsequent SELECT
statement(s). Subtracts rows from the second SELECT(s) from the first SELECT's result.
Student Database
Student_name Student_id subject score City
Ram S1 Hindi 80 New York
Sham S2 Sst 99 Atlanta
Aditya S3 math 78 Delhi
Advik S4 Science 78 Hyderabad
Prerna S5 Computer 89 New Jersey
Neetu S6 Biology 90 Calcutta
karuna S7 chemistry 68 Bangalore
Course database
Course_id Course_name department fees
CSC101 Computer science Computer science 132000
CSC102 AI Computer2 133000
CSC103 Data mining Computer3 132000
CSC104 ECE Electronics 134000
CSC105 EEE Electronics3 134000
CSC106 IT Computer4 135000
CSC107 Mechanical mech 123000
Registration database
Student_id Course_id
S1 CSC101
S2 CSC102
S3 CSC103
S4 CSC104
S5 CSC105
S6 CSC106
S7 CSC107
New_students
Student_name Student_id subject score City
Ram S1 Hindi 80 New York
Sham S2 Sst 99 Atlanta
53
Aditya S3 math 78 Delhi
Advik S4 Science 78 Hyderabad
Prerna S5 Computer 89 New Jersey
Divya S6 SSt 89 Delhi
Dimple S7 maths 89 kerela
Insert Records:
INSERT INTO Students (Student_name, Student_id, subject, score, City)
VALUES ('Ram', 'S1', 'Hindi', 80, 'New York'),('Sham', 'S2', 'Sst', 99, 'Atlanta'),
('Aditya', 'S3', 'Math', 78, 'Delhi'), ('Advik', 'S4', 'Science', 78, 'Hyderabad'),
('Prerna', 'S5', 'Computer', 89, 'New Jersey'),('Neetu', 'S6', 'Biology', 90, 'Calcutta'),
('Karuna', 'S7', 'Chemistry', 68, 'Bangalore');
Insert Records:
INSERT INTO courses (course_id, course_name, department, fees) VALUES
('CSC101', 'Computer science', 'Computer science', 132000), ('CSC102', 'AI', 'Computer2', 133000),
('CSC103', 'Data mining', 'Computer3', 132000), ('CSC104', 'ECE', 'Electronics', 134000),
('CSC105', 'EEE', 'Electronics3', 134000), ('CSC106', 'IT', 'Computer4', 135000),
('CSC107', 'Mechanical', 'mech', 123000);
Insert Records:
INSERT INTO registrations(student_id, course_id)VALUES ('S1', 'CSC101'),('S2', 'CSC102'),
('S3', 'CSC103'),('S4', 'CSC104'),('S5', 'CSC105'),('S6', 'CSC106'),('S7', 'CSC107');
Insert Records:
INSERT INTO new_students (student_name, student_id, subject, score, city)VALUES
('Ram', 'S1', 'Hindi', 80, 'New York'),('Sham', 'S2', 'Sst', 99, 'Atlanta'),
('Aditya', 'S3', 'math', 78, 'Delhi'),('Advik', 'S4', 'Science', 78, 'Hyderabad'),
('Prerna', 'S5', 'Computer', 89, 'New Jersey'),('Divya', 'S6', 'SSt', 89, 'Delhi'),
('Dimple', 'S7', 'maths', 89, 'Kerela');
54
1. Combine the names of students from the "students" and "new_students" tables without
duplicates:
2.Get the names of students who are present in both the "students" and "new_students" tables:
Input Query : SELECT student_name FROM students INTERSECT
SELECT student_name FROM new_students;
Output:
PRACTICE QUESTIONS:
1.Retrieve a list of student names from the "students" table, excluding those present in the "new_students" table.
Input Query :
Output:
2.Combine the names of students from the "students" and "new_students" tables, including duplicates.
55
Input Query : SELECT student_name FROM studentsUNION ALLSELECT student_name FROM
new_students;
Output:
3.Get the names of students who are either in the "students" table or in the "new_students" table, but not in both.
Input Query :
Output:
4.Retrieve a list of student names who have registered for at least one course from either the "students" or
"new_students" tables.
Input Query :
Output:
5.Combine the student names from the "students" and "new_students" tables, including duplicates, and sort the result
in ascending order.
Input Query :
Output:
6.Retrieve the student names from the "students" table who have not registered for any courses.
Input Query :
Output:
7.Get the names of students who are present in both the "students" table and the "new_students" table, including
56
duplicates.
Input Query :
Output:
VIVA - QUESTIONS:
1. What is the difference between the UNION and UNION ALL operations in DBMS?
2. How does the INTERSECT operation work in DBMS, and what is its purpose?
3. Explain the EXCEPT (or MINUS) operation in DBMS and provide an example.
4. Can you combine multiple set operations in a single query? If so, provide an example.
5. What happens if the SELECT statements in a set operation have different column names or
incompatible data types?
Experiment- 8
Aim: Write the queries to create the views and queries based on views.
Syntax:
CREATE VIEW view_name
AS SELECT column1,
column2, ... FROM
table_name
WHERE condition;
Example:
SQL> CREATE VIEW employee AS SELECT empno,ename,job FROM EMP
WHERE job = ‘clerk’; SQL>
View created.
58
UPDATING A VIEW : A view can updated by using the following syntax : Syntax :
CREATE OR REPLACE VIEW view_name AS
SELECT column_name(s)
FROM
table_name
WHERE
condition;
Output:
Output:
59
PRACTICE QUESTIONS:
Table: Students
1 John Doe 1 A
2 Jane Smith 2 B
3 Mike Johnson 1 A-
Table: Departments
Write an SQL query to create a view named "Student Grades" that retrieves the Student ID, Student
Name, and Grade from the Students table.
Write an SQL query to retrieve the contents of the "Student Grades" view created in the previous question.
Write an SQL query to create a view named "Top Students" that retrieves the Student ID, Student Name,
and Grade of students who have a grade of "A".
Write an SQL query to retrieve the contents of the "Top Students" view created in the previous question.
Write an SQL query to create a view named "Department Summary" that retrieves the Department ID,
Department Name, and the total number of students in each department.
Write an SQL query to retrieve the contents of the "Department Summary" view created in the previous
question.
Write an SQL query to create a view named "Top Scoring Departments" that retrieves the Department ID,
Department Name, and the average grade of students in each department, sorted in descending order by
the average grade.
VIVA - QUESTIONS:
60
Que2. How we create a view?
61
Experiment- 9
Theory:
• The selection structure tests a condition, then executes one sequence of statements instead of
another, depending on whether the condition is true or false. A condition is any variable or
expression that returns a BOOLEAN value (TRUE or FALSE).
• The iteration structure executes a sequence of statements repeatedly as long as a condition holds
true.
• The sequence-structure simply executes a sequence of statements in the order in which they occur.
Often, it is necessary to take alternative actions depending on circumstances. The IF statement lets you
execute a sequence of statements conditionally. That is, whether the sequence is executed or not depends
on the value of a condition. There are three forms of IF statements: IF-THEN, IF- THEN-ELSE, and
IFTHEN-ELSIF. The CASE statement is a compact way to evaluate a single condition and choose
between many alternative actions.
IF-THEN Statement:
The simplest form of IF statement associates a condition with a sequence of statements enclosed by the
keywords THEN and END IF (not ENDIF), as follows:
IF condition THEN
sequence_of_statements
END IF;
The sequence of statements is executed only if the condition is true. If the condition is false or null, the IF
statement does nothing. In either case, control passes to the next statement. An example follows:
IF-THEN-ELSE Statement:
62
The second form of IF statement adds the keyword ELSE followed by an alternative sequence of
statements, as follows:
IF condition THEN
sequence_of_statements1
ELSE
sequence_of_state
ments2 END IF;
The sequence of statements in the ELSE clause is executed only if the condition is false or null. Thus, the
ELSE clause ensures that a sequence of statements is executed. In the following example, the first UPDATE
statement is executed when the condition is true, but the second UPDATE statement is executed when
the condition is false or null:
The THEN and ELSE clauses can include IF statements. That is, IF statements can be nested, as the
following example shows:
IF-THEN-ELSIF Statement:
Sometimes you want to select an action from several mutually exclusive alternatives. The third form of IF
statement uses the keyword ELSIF (not ELSEIF) to introduce additional conditions, as follows:
IF condition1 THEN
sequence_of_statements1
ELSIF condition2 THEN
sequence_of_statements2
ELSE
sequence_of_state
ments3 END IF;
63
If the first condition is false or null, the ELSIF clause tests another condition. An IF statement can have
any number of ELSIF clauses; the final ELSE clause is optional. Conditions are evaluated one by one
from top to bottom. If any condition is true, its associated sequence of statements is executed and control
passes to the next statement. If all conditions are false or null, the sequence in the ELSE clause is
executed. Consider the following example:
BEGIN
...
IF sales > 50000 THEN
bonus := 1500;
ELSIF sales > 35000 THEN
bonus :=
500;
ELSE
bonus :=
100; END
IF;
INSERT INTO payroll VALUES (emp_id, bonus,
...); END;
If the value of sales is larger than 50000, the first and second conditions are true. Nevertheless, bonus is
assigned the proper value of 1500 because the second condition is never tested. When the first condition is
true, its associated statement is executed and control passes to the INSERT statement.
CASE Statement:
Like the IF statement, the CASE statement selects one sequence of statements to execute. However, to
select the sequence, the CASE statement uses a selector rather than multiple Boolean expressions. To
compare the IF and CASE statements, consider the following code that outputs descriptions of school
grades:
CASE grade
WHEN 'A' THEN
dbms_output.put_line('Excellent'); WHEN 'B'
THEN dbms_output.put_line('Very Good');
WHEN 'C' THEN
dbms_output.put_line('Good'); WHEN 'D' THEN
dbms_output.put_line('Fair'); WHEN 'F'
THEN dbms_output.put_line('Poor');
ELSE dbms_output.put_line('No such
grade'); END CASE;
The CASE statement is more readable and more efficient. So, when possible, rewrite lengthy IF-
THENELSIF statements as CASE statements.
The CASE statement begins with the keyword CASE. The keyword is followed by a selector, which is the
variable grade in the last example. The selector expression can be arbitrarily complex. For example, it can
contain function calls. Usually, however, it consists of a single variable. The selector expression is
evaluated only once. The value it yields can have any PL/SQL datatype other than BLOB, BFILE, an
object type, a PL/SQL record, an index-by-table, a varray, or a nested table.
The selector is followed by one or more WHEN clauses, which are checked sequentially. The value of the
selector determines which clause is executed. If the value of the selector equals the value of a WHENclause
expression, that WHEN clause is executed. For instance, in the last example, if grade equals 'C', the program
outputs 'Good'. Execution never falls through; if any WHEN clause is executed, control passes to the next
statement.
The ELSE clause works similarly to the ELSE clause in an IF statement. In the last example, if the grade is
not one of the choices covered by a WHEN clause, the ELSE clause is selected, and the phrase 'No such
grade' is output. The ELSE clause is optional. However, if you omit the ELSE clause, PL/SQL adds the
following implicit ELSE clause:
If the CASE statement selects the implicit ELSE clause, PL/SQL raises the predefined exception
CASE_NOT_FOUND. So, there is always a default action, even when you omit the ELSE clause.
The keywords END CASE terminate the CASE statement. These two keywords must be separated by a
space. The CASE statement has the following form:
65
[<<label_na
me>>]
CASE
selector
WHEN expression1 THEN
sequence_of_statements1; WHEN expression2 THEN
sequence_of_statements2;
...
WHEN expressionN THEN
sequence_of_statementsN; [ELSE
sequence_of_statementsN+1;]
END CASE [label_name];
Like PL/SQL blocks, CASE statements can be labeled. The label, an undeclared identifier enclosed by
double angle brackets, must appear at the beginning of the CASE statement. Optionally, the label name
can also appear at the end of the CASE statement.
Exceptions raised during the execution of a CASE statement are handled in the usual way. That is, normal
execution stops and control transfers to the exception-handling part of your PL/SQL block or subprogram.
PRACTICE QUESTIONS:
1. Write a PL/SQL block that checks if a variable named "age" is greater than or equal to 18. If it is,
display the message "You are eligible for voting."
2. Write a PL/SQL block that checks if a number variable named "score" is greater than 90. If it is,
display the message "Congratulations, you passed!" Otherwise, display the message "Sorry, you
did not pass."
3. Write a PL/SQL block that uses a FOR loop to display the numbers from 1 to 10 on separate lines.
4. Write a PL/SQL block that uses a WHILE loop to display the even numbers between 1 and 20 on
separate lines.
5. Write a PL/SQL block that uses a CASE statement to determine the grade based on a variable named
"percentage." Display the corresponding grade message (e.g., "A", "B", "C", etc.) depending on the
percentage value.
VIVA - QUESTIONS:
66
2) Which structure executes a sequence of statements repeatedly as long as a condition holds true?
3) What is the maximum number of ELSE clauses that can be included in an IF clause that is not
nested?
Experiment- 10
Theory:
An exception is an error which disrupts the normal flow of program instructions. PL/SQL provides us the
exception block which raises the exception thus helping the programmer to find out the fault and resolve
it.
There are two types of exceptions defined in PL/SQL
DECLARE
declarations section;
BEGIN
executable command(s);
EXCEPTION
WHEN exception1 THEN
statement1;
WHEN exception2 THEN
statement2;
[WHEN others THEN]
/* default exception handling code
*/ END;
67
Note:
When other keyword should be used only at the end of the exception handling block as no exception
handling part present later will get executed as the control will exit from the block after executing the
WHEN OTHERS.
1. System defined exceptions:
These exceptions are predefined in PL/SQL which get raised WHEN certain database
rule is violated.
System-defined exceptions are further divided into two categories:
1. Named system exceptions.
2. Unnamed system exceptions.
3. Named system exceptions: They have a predefined name by the system like
ACCESS_INTO_NULL, DUP_VAL_ON_INDEX, LOGIN_DENIED etc. the
list is quite big.
So, we will discuss some of the most commonly used exceptions: Let’s create
a table geeks.
1. NO_DATA_FOUND: It is raised WHEN a SELECT INTO statement returns no rows. For eg:
68
DECLARE
temp varchar(20);
BEGIN
SELECT g_id into temp from geeks where g_name='GeeksforGeeks';
exception
WHEN no_data_found THEN
dbms_output.put_line('ERROR');
dbms_output.put_line('there is no name as');
dbms_output.put_line('GeeksforGeeks in geeks table');
end;
Output:
ERROR
there is no name as GeeksforGeeks in geeks table
2. TOO_MANY_ROWS: It is raised WHEN a SELECT INTO statement returns more than one
row.
DECLARE
temp varchar(20);
BEGIN
EXCEPTION
WHEN too_many_rows THEN
dbms_output.put_line('error trying to SELECT too many rows');
end;
Output:
error trying to SELECT too many rows
BEGIN
SELECT g_name into temp from geeks where g_name='Suraj'; dbms_output.put_line('the
g_name is '||temp);
EXCEPTION
WHEN value_error THEN
dbms_output.put_line('Error');
dbms_output.put_line('Change data type of temp to varchar(20)');
END;
Output:
Error
Change data type of temp to varchar(20)
BEGIN
answer:=a/b;
dbms_output.put_line('the result after division is'||answer);
exception
WHEN zero_divide THEN
dbms_output.put_line('dividing by zero please check the values
again'); dbms_output.put_line('the value of a is '||a);
dbms_output.put_line('the value of b is '||b);
END;
Output: dividing by zero please check the
values again the value of a is 10 the
value of b is 0
1. Unnamed system exceptions: Oracle doesn’t provide name for some system exceptions called
unnamed system exceptions. These exceptions don’t occur frequently. These exceptions have
70
two parts code and an associated message. The way to handle to these exceptions is to
assign name to them using Pragma EXCEPTION_INIT Syntax:
PRAGMA EXCEPTION_INIT(exception_name, -error_number);
error_number are pre-defined and have negative integer range from -20000 to - 20999.
Example:
DECLARE
exp exception;
pragma exception_init (exp, -20015);
n int:=10;
BEGIN
FOR i IN 1..n LOOP
dbms_output.put_line(i*i);
IF i*i=36 THEN
RAISE exp;
END IF;
END LOOP;
EXCEPTION
WHEN exp THEN
dbms_output.put_line('Welcome to GeeksforGeeks');
END;
Output:
1
4
9
16
25
36
Welcome to GeeksforGeeks
BEGIN
IF y=0 then
raise exp1;
ELSE
div_r:= x / y; dbms_output.put_line('the
result is '||div_r);
END IF;
EXCEPTION
WHEN exp1 THEN
dbms_output.put_line('Error');
dbms_output.put_line('division by zero not allowed');
END;
Input 1:
x = 20
y = 10
Output:
the result is 2
Input 2:
x = 20
y=0
Output:
Error
division by zero not allowed
72
Input 3:
x=20 y =
30
Output:
<.em>
Error
y is greater than x please check the input
3. RAISE_APPLICATION_ERROR:
It is used to display user-defined error messages with error number whose range is in between
20000 and -20999. When RAISE_APPLICATION_ERROR executes it returns error message and
error code which looks same as Oracle built-in error. Example:
DECLARE myex
EXCEPTION; n
NUMBER :=10;
BEGIN
FOR i IN 1..n LOOP
dbms_output.put_line(i*i);
IF i*i=36 THEN
RAISE myex;
END IF;
END LOOP;
EXCEPTION
WHEN myex THEN
RAISE_APPLICATION_ERROR(-20015, 'Welcome to GeeksForGeeks');
END;
Output:
Error report:
ORA-20015: Welcome to
GeeksForGeeks ORA-06512: at
line 13
1
4
9
16
25
36
Note: The output is based on Oracle Sql developer, the output order might change IF you’re
running this code somewhere else.
73
Scope rules in exception handling:
• We can’t DECLARE an exception twice but we can
DECLARE the same exception in two different blocks.
• Exceptions DECLARED inside a block are local to that block and global to all its subblocks.
As a block can reference only local or global exceptions, enclosing blocks cannot reference
exceptions DECLARED in a sub-block.
If we REDECLARE a global exception in a sub-block, the local declaration prevails i.e., the scope of
local is more.
Example:
DECLARE
GeeksforGeeks
EXCEPTION; age
NUMBER:=16; BEGIN
-- sub-block BEGINs
DECLARE
BEGIN
IF age > 16 THEN
RAISE GeeksforGeeks; /* this is not handled*/
END IF;
END;
-- sub-block ends
EXCEPTION
-- Does not handle raised exception
WHEN GeeksforGeeks THEN
DBMS_OUTPUT.PUT_LINE
('Handling GeeksforGeeks exception.');
Advantages:
74
• Exception handling is very useful for error handling, without it we have to issue the
command at every point to check for execution errors:
Example:
Select ..
.. check for 'no data found'
error Select ..
.. check for 'no data found'
error Select ..
.. check for 'no data found' error
Here we can see that it is not robust as error processing is not separated from normal
processing and IF we miss some line in the code than it may lead to some other kind of error.
• With exception handling we handle errors without writing statements multiple times and we
can even handle different types of errors in one exception block:
Example:
BEGI
N
SEL
EC
T ...
SELECT ...
SELECT ...
.
.
.
exception
WHEN NO_DATA_FOUND THEN /* catches all 'no data found' errors */
...
WHEN ZERO_DIVIDE THEN /* different types of */
WHEN value_error THEN /* errors handled in same
block */
...
75
1. Improves readability by letting us isolate error-handling routines and thus providing
robustness.
2. Provides reliability, instead of checking for dIFferent types of errors at every point we can
simply write them in exception block and IF error exists exception will be raised thus helping
the programmer to find out the type of error and eventually resolve it.
Uses: One of the real-life uses of exception can be found in online train reservation system. While filling
the station code to book the ticket IF we input wrong code it shows us the exception that the code doesn’t
exist in database.
76
PRACTICE QUESTIONS:
1. Write a PL/SQL block that raises an exception if a variable named "balance" is negative. Handle
the exception by displaying a custom error message.
2. Write a PL/SQL block that includes a division operation. Handle the "ZERO_DIVIDE" exception
using the WHEN OTHERS clause to display a user-friendly message.
3. Define a user-defined exception named "InvalidInputException." Write a PL/SQL block that raises
this exception if a variable named "input" is not within the range of 1 to 100.
4. Define an exception named "CustomException." Associate it with the Oracle error code "ORA-
00001" using the EXCEPTION_INIT pragma. Write a PL/SQL block that handles the "CustomException"
and displays a specific error message for that error code.
5. Write a PL/SQL block that includes a subprogram. Inside the subprogram, raise an exception.
Handle the exception in the main block and display an appropriate message indicating the exception's
occurrence.
VIVA - QUESTIONS:
2. For which Exception, if a SELECT statement attempts to retrieve data based on its conditions, this
exception is raised when no rows satisfy the SELECT criteria?
Theory:
77
Procedures and Functions are the subprograms which can be created and saved in the database as database
objects. They can be called or referred inside the other blocks also.
Parameter:
The parameter is variable or placeholder of any valid PL/SQL datatype through which the PL/SQL
subprogram exchange the values with the main code. This parameter allows to give input to the
subprograms and to extract from these subprograms.
• These parameters should be defined along with the subprograms at the time of creation.
• These parameters are included in the calling statement of these subprograms to interact the values
with the subprograms.
• The datatype of the parameter in the subprogram and the calling statement should be same.
• The size of the datatype should not mention at the time of parameter declaration, as the size is
dynamic for this type.
1. IN Parameter
2. OUT Parameter
3. IN OUT Parameter
IN Parameter:
IN OUT Parameter:
• This parameter is used for both giving input and for getting output from the subprograms.
• It is a read-write variable inside the subprograms. Their values can be changed inside the
subprograms.
78
• In the calling statement, these parameters should always be a variable to hold the value from the
subprograms.
These parameter type should be mentioned at the time of creating the subprograms.
RETURN
RETURN is the keyword that instructs the compiler to switch the control from the subprogram to the
calling statement. In subprogram RETURN simply means that the control needs to exit from the
subprogram. Once the controller finds RETURN keyword in the subprogram, the code after this will be
skipped.
Normally, parent or main block will call the subprograms, and then the control will shift from those parent
block to the called subprograms. RETURN in the subprogram will return the control back to their parent
block. In the case of functions RETURN statement also returns the value. The datatype of this value is
always mentioned at the time of function declaration. The datatype can be of any valid PL/SQL data type.
• Procedures are standalone blocks of a program that can be stored in the database.
• Call to these PLSQL procedures can be made by referring to their name, to execute the PL/SQL
statements.
• It is mainly used to execute a process in PL/SQL.
• It can have nested blocks, or it can be defined and nested inside the other blocks or packages.
• It contains declaration part (optional), execution part, exception handling part (optional).
• The values can be passed into Oracle procedure or fetched from the procedure through parameters.
• These parameters should be included in the calling statement.
• A Procedure in SQL can have a RETURN statement to return the control to the calling block, but
it cannot return any values through the RETURN statement.
• Procedures cannot be called directly from SELECT statements. They can be called from another
block or through EXEC keyword.
Syntax:
CREATE OR REPLACE PROCEDURE
<procedure
_n
a
m
e>
(
79
<parameterl IN/OUT <datatype>
..
.
)
[
IS
|
A
S]
<declaration_part>
BEGIN
<execution part>
EXCEPTION
<exception handling part>
END;
• CREATE PROCEDURE instructs the compiler to create new procedure in Oracle. Keyword ‘OR
REPLACE’ instructs the compile to replace the existing procedure (if any) with the current one.
Procedure name should be unique.
• Keyword ‘IS’ will be used, when the stored procedure in Oracle is nested into some other blocks.
If the procedure is standalone then ‘AS’ will be used. Other than this coding standard, both have
the same meaning.
In this example, we are going to create an Oracle procedure that takes the name as input and prints the
welcome message as output. We are going to use EXEC command to call procedure.
Code Explanation:
• Code line 1: Creating the procedure with name ‘welcome_msg’ and with one parameter
‘p_name’ of ‘IN’ type.
• Code line 4: Printing the welcome message by concatenating the input name.
• Procedure is compiled successfully.
• Code line 7: Calling the procedure using EXEC command with the parameter ‘Guru99’.
Procedure is executed, and the message is printed out as “Welcome Guru99”.
80
What is Function?
Functions is a standalone PL/SQL subprogram. Like PL/SQL procedure, functions have a unique name by
which it can be referred. These are stored as PL/SQL database objects. Below are some of the
characteristics of functions. Functions are a standalone block that is mainly used for calculation
purpose.
• Function use RETURN keyword to return the value, and the datatype of this is defined at the time
of creation.
• A Function should either return a value or raise the exception, i.e. return is mandatory in functions.
• Function with no DML statements can be directly called in SELECT query whereas the function
with DML operation can only be called from other PL/SQL blocks.
• It can have nested blocks, or it can be defined and nested inside the other blocks or packages.
• It contains declaration part (optional), execution part, exception handling part (optional).
• The values can be passed into the function or fetched from the procedure through the parameters.
• These parameters should be included in the calling statement.
• A PLSQL function can also return the value through OUT parameters other than using RETURN.
• Since it will always return the value, in calling statement it always accompanies with assignment
operator to populate the variables.
Syntax
CREATE OR REPLACE FUNCTION
<procedure
_name> (
<parameterl IN/OUT <datatype>
)
RETURN
<datatype> [
IS | AS ]
<declaration_
part> BEGIN
<executi
on part>
EXCEPT
ION
<exception handling
part> END;
• CREATE FUNCTION instructs the compiler to create a new function. Keyword ‘OR REPLACE’
instructs the compiler to replace the existing function (if any) with the current one.
• The Function name should be unique.
• RETURN datatype should be mentioned.
• Keyword ‘IS’ will be used, when the procedure is nested into some other blocks. If the procedure
is standalone then ‘AS’ will be used. Other than this coding standard, both have the same meaning.
Code Explanation:
82
• Code line 1: Creating the Oracle function with name ‘welcome_msg_func’ and with one
parameter ‘p_name’ of ‘IN’ type.
• Code line 2: declaring the return type as VARCHAR2
• Code line 5: Returning the concatenated value ‘Welcome’ and the parameter value.
• Code line 8: Anonymous block to call the above function.
• Code line 9: Declaring the variable with datatype same as the return datatype of the function.
• Code line 11: Calling the function and populating the return value to the variable ‘lv_msg’.
• Code line 12: Printing the variable value. The output you will get here is “Welcome Guru99”
• Code line 14: Calling the same function through SELECT statement. The return value is directed
to the standard output directly.
Procedure Function
Used mainly to a execute certain process Used mainly to perform some calculation
Cannot call in SELECT statement A Function that contains no DML statemen called
in SELECT statement
Use OUT parameter to return the value Use RETURN to return the value
• Return datatype will not be specified at the Return datatype is mandatory at the time of time of
creation
creation
83
PRACTICE QUESTIONS:
1. Write a PL/SQL code snippet to create a function named "calculate_area" that accepts the radius of
a circle as a parameter and returns the calculated area of the circle.
2. Write a PL/SQL code snippet to create a procedure named "insert_employee" that inserts a new
employee record into an "Employees" table. The procedure should accept parameters such as employee
name, ID, and department.
3. Create two functions named "calculate_area" that accept different parameters. One function should
calculate the area of a rectangle based on its length and width, while the other function should calculate
the area of a square based on its side length.
4. Create a procedure named "get_employee_name" that accepts an employee ID as input and returns
the corresponding employee name as an OUT parameter.
5. Create a function named "divide_numbers" that accepts two numbers as parameters and returns the
result of dividing the first number by the second number. Handle the "ZERO_DIVIDE" exception and
return NULL if the second number is 0.
VIVA - QUESTIONS:
1. What are subprograms in PL/SQL and what are the advantages of subprograms?
6. What are the modes for passing parameters to stored Procedure or Function?
Experiment- 12
84
Aim: Demonstrate the concept of Triggers
Theory:
PL/SQL:
PL/SQL is a combination of SQL along with the procedural features of programming
languages. It was developed by Oracle Corporation in the early 90's to enhance the capabilities
of SQL. PL/SQL is one of three key programming languages embedded in the Oracle Database,
along with SQL itself and Java. This tutorial will give you great understanding on PL/SQL to
proceed with Oracle database and other advanced RDBMS concepts.
The PL/SQL programming language was developed by Oracle Corporation in the late 1980s as
procedural extension language for SQL and the Oracle relational database. Following are
certain notable facts about PL/SQL −
• PL/SQL can also directly be called from the command-line SQL*Plus interface.
• Direct call can also be made from external programming language calls to database.
• PL/SQL's general syntax is based on that of ADA and Pascal programming language.
• Apart from Oracle, PL/SQL is available in TimesTen in-memory database and IBM DB2.
Features of PL/SQL
PL/SQL has the following features −
Advantages of PL/SQL
PL/SQL has the following advantages −
• SQL is the standard database language and PL/SQL is strongly integrated with SQL.
PL/SQL supports both static and dynamic SQL. Static SQL supports DML operations and
transaction control from PL/SQL block. In Dynamic SQL, SQL allows embedding DDL
statements in PL/SQL blocks.
• PL/SQL allows sending an entire block of statements to the database at one time. This
reduces network traffic and provides high performance for the applications.
85
• PL/SQL gives high productivity to programmers as it can query, transform, and update data
in a database.
• PL/SQL saves time on design and debugging by strong features, such as exception
handling, encapsulation, data hiding, and object-oriented data types.
• Applications written in PL/SQL are fully portable.
TRIGGERS: 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 −
Benefits of Triggers
86
CREATE [OR REPLACE ] TRIGGER trigger_name
[OF col_name]
ON table_name
WHEN (condition)
DECLARE
Declaration-statements
BEGIN
Executable-statements
EXCEPTION
Exception-handling-statements
END;
Where,
87
PRACTICE QUESTIONS:
1. Write a PL/SQL trigger that fires before inserting a new record into a table named
"Employees." The trigger should automatically set the "created_date" column to the current date
and time.
2. Create a PL/SQL trigger that fires after updating the "Salary" column in a table named
"Employees." The trigger should log the old and new values of the salary in an audit table named
"Salary_Audit."
3. Write a PL/SQL trigger that fires instead of deleting a record from a table named "Orders."
The trigger should perform additional validation checks and prevent the deletion if specific
conditions are not met.
4. Create a PL/SQL compound trigger that fires before and after updating the "Quantity"
column in a table named "Inventory." The trigger should log the old and new values of the quantity
in separate audit tables named "Quantity_Before_Update" and "Quantity_After_Update."
5. Write a PL/SQL trigger that fires after inserting, updating, or deleting records from both the
"Customers" and "Orders" tables. The trigger should perform a specific action whenever a change
occurs in either of the tables.
VIVA - QUESTIONS:
88
Aim: The Institute offers multiple B. Tech Courses. Students can take admission in any Course offered by
the Institute. Multiple subjects are taught in each branch. The institute has a Director and Hod of each B.
Tech Course. The HoD of another branch may be given additional responsibility to take charge of one
more department for a limited period in the absence of Hod of that branch. Faculties recruited in each B.
Tech Course can teach only a single same subject to students of different B.Tech Courses. For each
subject, there is a faculty coordinator responsible for coordinating all the faculties teaching the same
subject. A batch of 20 students is assigned a faculty mentor. The mentor takes counsellor meetings twice a
month.
Data to be recorded in the database include:
Student – enrollment no, name, data of birth, address, contact no, email – id, qualifying exam
rank, Course
Faculty – Faculty name, contact no, email id, course
Parents data – Parents name, contact no, email id, Profession
Draw the ER diagram (Conceptual design) of the given problem statement. (CO1)
89
Relationships
1. Student - Course:
o A student enrolls in one course, but a course can have multiple students. o (1:N
relationship)
2. Course - Faculty:
o A course has multiple faculties assigned, and a faculty teaches one subject in one or more
courses.
o (1:N relationship)
3. Course - HoD:
o Each course has one HoD, but a faculty can be an HoD for more than one course
temporarily. o (1:1 relationship)
4. Subject - Faculty: o A subject has multiple faculties teaching it, but each subject has one coordinator. o
(1:N relationship)
5. Batch - Student: o A batch consists of multiple students, but a student belongs to one batch. o (1:N
relationship)
6. Batch - Mentor (Faculty):
o Each batch is assigned a mentor, but a faculty member can mentor multiple batches.
o (1:N relationship)
7. Director:
o The institute has one Director. o (1:1 relationship)
8. Parents - Student: o Each student is associated with their parents. o (1:1 relationship)
Experiment 2
Aim: To demonstrate a connection to a MariaDB database using the following languages: C, Java and
Python
The MariaDB database has been deployed on another virtual machine in the same intranet in advance,
and the database username and password for remote connection have been created. Here, assume that
our new username is proxysql and the password is proxypassword. Use the default port number 3306 for
the port number.
C:
Then, create a new C language file version.c and enter the following code:
#include<mysql.h>
90
#include<stdio.h>
#include<stdlib.h>
if (con == NULL)
{ fprintf(stderr, "%s\n",
mysql_error(con));
exit(1);
}
mysql_close(co
n); exit(0);
91
}
if (con == NULL)
{ fprintf(stderr, "%s\n",
mysql_error(con));
exit(1);
}
finish_with_error(con);
}
if (mysql_query(con, "INSERT INTO cars VALUES(4,'Volvo',29000)"))
{ finish_with_error(con);
}
if (mysql_query(con, "INSERT INTO cars VALUES(5,'Bentley',350000)"))
{ finish_with_error(con);
}
if (mysql_query(con, "INSERT INTO cars VALUES(6,'Citroen',21000)"))
{ finish_with_error(con);
}
if (mysql_query(con, "INSERT INTO cars VALUES(7,'Hummer',41400)"))
{ finish_with_error(con);
}
if (mysql_query(con, "INSERT INTO cars VALUES(8,'Volkswagen',21600)"))
{ finish_with_error(con);
}
if (mysql_query(con, "INSERT INTO people
VALUES(1,'Jim',7)")) { finish_with_error(con);
}
if (mysql_query(con, "INSERT INTO people
VALUES(1,'Jim',8)")) { finish_with_error(con);
}
if (mysql_query(con, "INSERT INTO people
VALUES(2,'Tom',6)"))
{ finish_with_error(con); }
}
printf("\n");
}
mysql_free_result(result);
1 Audi 52642
2 Mercedes 57127
3 Skoda 9000
4 Volvo 29000 5 Bentley 350000 6 Citroen 21000 7 Hummer 41400
8 Volkswagen 21600
Jim Hummer 42400
Jim Volkswagen 21600
Tom Citroen 21000
According to the above test, it can be found that C language connects to MariaDB database,
adds, deletes, changes and queries, creates tables, deletes tables, and other functions are all
normal on the 64-bit processing.
Java:
First, ensure the latest OpenJDK and Apache Maven versions have been installed on the test virtual
machine. Create a sample project with Apache Maven:
mvn archetype:generate -DgroupId=com.mycompany.app -DartifactId=my-app -
DarchetypeArtifactId=maven-archetype-quickstart -DinteractiveMode=false
Then in the generated pom.xml dependencies module, add the following content:
<dependency>
<groupId>org.mariadb.jdbc</groupId>
<artifactId>mariadb-java-client</artifactId>
<version>2.7.0</version>
</dependency>
95
Then edit src/main/java/com/mycompany/app the App.javafile in the directory, the content is as follows
package com.mycompany.app;
import java.sql.*;
1 mvn install
Execute the following command to execute.
The above is just a test of relatively simple functions. Below we test the connection pool function and
perform functions such as adding, deleting, modifying, and query.
package
com.mycompany.app;
import java.sql.*;
96
try (Connection connection =
DriverManager.getConnection(connectionString)) { try (Statement stmt =
connection.createStatement()) {
ResultSet rs = stmt.executeQuery("DROP TABLE IF EXISTS cars;");
stmt.executeQuery("CREATE TABLE cars(id INT PRIMARY KEY
AUTO_INCREMENT, name
VARCHAR(255), price INT)"); stmt.executeQuery("INSERT
INTO cars
VALUES(1,'Audi',52642)"); stmt.executeQuery("INSERT INTO
cars VALUES(2,'Mercedes',57127)"); rs =
stmt.executeQuery("SELECT * FROM cars");
rs.next();
System.out.println(rs.getStri
ng(2));
}
}
Audi
Volks
Wage
n
After the above test, the connection pool and addition, deletion, modification, and checking functions are
also normal.
Java’s connector functions are relatively rich, and it also implements load balancing or read-write
separation for clusters or primary replica databases. Next, we test the read-write separation function.
Before doing so, please ensure you have set up the MariaDB primary-replica database environment.
Change App.java to the following code. Note that the replication keyword is added to the JDBC
connection string, which represents primary-replica replication. If it is in other load-balancing
environments, keywords such as load balance are also supported. For details, refer to the official MariaDB
97
documentation. Also note that in the connection string, the primary database address is first, and the
replica database address is last. When the connection attribute is changed to ReadOnly, the statement will
go to the replica database to query.
package com.mycompany.app;
import java.sql.*;
VolksWage
n
execution
succeed.
The above demonstrated project uses Maven as an example. If you are not using Maven, you can also refer
to the instructions of other tools in the official MariaDB documentation:
https://mariadb.com/kb/en/mariadb-connector-j/
Python:
First make sure that Python3 and pip3 have been installed on the test virtual machine.
To connect MariaDB in Python, you need to install the C language connector first, you can execute the
following command to install
98
apt install libmariadb-dev
However, the current version of the mariadb package that comes with the current Ubuntu 18.04 version is
older and cannot meet the python version requirements. We compile one from the source code.
Execute the following command to download the connector source code and unzip it
wget https://downloads.mariadb.org/interstitial/connector-c-3.1.11/mariadb-connector-c-
3.1.11-src.zip unzip mariadb-connector-c-3.1.11-src.zip Start
compiling.
mkdir build-
mariadbconnector-c
cd buildmariadb-
connector-c
cmake ../mariadb-connector-c-3.1.11-src -DCMAKE_BUILD_TYPE=Release -
DCMAKE_INSTALL_PREFIX=/usr/
local make
make install
echo "/usr/local/lib/mariadb/" >
/etc/ld.so.conf.d/mariadb.conf ldconfig
Then execute the following command to install the Python connector:
import mariadb
pool =
mariadb.ConnectionPool( user="proxysql",
password="proxypassword
" , host="192.168.0.204",
port=3306,
pool_name="we
b-app",
pool_size=20
)
try:
pconn =
pool.get_connection(
) cur =
pconn.cursor()
data = [(3, 'Skoda', 9000),(4, 'Volvo', 29000),(5, 'Bently', 350000)]
99
cur.executemany("INSERT INTO testdb.cars(id, name, price) VALUES (?, ?, ?)", data)
cur.execute("select * from testdb.cars") cars = [] for (id,name,price) in cur:
cars.append(f"{id} {name}
{price}") print("\
n".join(cars))
except mariadb.PoolError as e:
# Report Error
printf("Error opening connection from pool: {e}")
Execute:
python3 testmariadb.py
The output is as follows
Volkswagen 52642
Mercedes 57127
Skoda 9000
Volvo 29000
Bently 350000
For other functions of the Python connector, you can refer to the
following link: https://mariadb.com/docs/appdev/connector-python/
To demonstrate a connection to a MariaDB database using Python, you can use the mysql-
connectorpython library. MariaDB is compatible with MySQL, so you can use the same library that is
used to connect to MySQL databases. Here's an example of how to connect to a MariaDB database using
Python:
Prerequisites:
1. Install MariaDB: If you haven't already, install MariaDB on your computer. You can download it from
the official website (https://mariadb.org/download/).
2. Install the mysql-connector-python library:
pip install mysql-connector-python
Python Example:
import mysql.connector
# Database connection
parameters db_params = {
'host': 'localhost', # Change to your database
100
host 'database': 'mydb', # Change to your
database name 'user': 'myuser', # Change to
your database username
'password': 'mypassword' # Change to your database
password }
try:
# Establish a connection to the database conn
= mysql.connector.connect(**db_params)
if conn.is_connected():
print("Connected to the database successfully.")
except mysql.connector.Error
as e: print(f"Error:
{e}")
Replace the db_params dictionary values with your specific database connection details
This Python script uses the mysql-connector-python library to connect to a MariaDB database, execute a
simple SQL query to fetch the database version, and then closes the connection.
Make sure you have MariaDB running and that you've created the specified database with the appropriate
user and permissions before running this script.
101