Dbms Manual
Dbms Manual
--------------`444]
DR2D24CREATE 4
JAWAHARLAL NEHRU TECHNOLOGICAL UNIVERSITY: KAKINADA
KAKINADA – 533 003, Andhra Pradesh, India
DEPARTMENT OF MASTER OF COMPUTER APPLICATIONS
\
2 | Page
3 | Page
4 | Page
5 | Page
6 | Page
L T P C
I Year – II Semester
0 0 3 1
.
5
DATABASE MANAGEMENT SYSTEM LAB
Course Objectives:
1) This Course will enable students to
2) Populate and query a database using SQL DDL/DML Commands
3) Declare and enforce integrity constraints on a database
4) Writing Queries using advanced concepts of SQL
5) Programming PL/SQL including procedures, functions, cursors and triggers
Course Outcomes:
1) At the end of the course the student will be able to:
2) Utilize SQL to execute queries for creating database and performing data manipulation operations
3) Examine integrity constraints to build efficient databases
7 | Page
4) Apply Queries using Advanced Concepts of SQL
5) Build PL/SQL programs including stored procedures, functions, cursors and triggers
List of Experiments:
1) Execute all DDL, DML and DCL commands on sample tables.
2) Implementation of different types of operators and built-in functions with suitable examples
3) Implementation of different types of joins with suitable examples
4) Create views, partitions, Sequence, Indexes and locks for a particular DB
5) Implement different types of constraints on relations.
6) Implementation of subqueries and nested queries.
7) Implement Queries on Group by & Having Clauses, ALIAS, Sequence By, Order By
8) Control Structure
a) Write a PL/SQL block for Addition of Two Numbers
b) Write a PL/SQL block for IF, IF and else condition
c) Write a PL/SQL block for implementation of loops
d) Write a PL/SQL block for greatest of three numbers using IF and ELSEIF
9) Exception Handling- Implement the following with respect to exception handling. Raising Exceptions, User Defined
Exceptions, Pre-Defined Exceptions
10) Write PL/SQL block for an application using exception handling Procedures
a) Write a PL/SQL Procedure using Positional Parameters
b) Write a PL/SQL Procedure using notational parameters
c) Write a PL/SQL Procedure for GCD Numbers
d) Write a PL/SQL Procedures for cursor implementation (explicit and implicit cursors)
11) Functions:
a) Write a PL/SQL block to implement factorial using functions
b) Write a PL/SQL function to search an address from the given database
12) Write a DBMS program to prepare Pl/SQL reports for an application using functions.
13) Triggers:
a) Write a Trigger to pop-up the DML operations
b) Write a Trigger to check the age valid or not Using Message Alert.
c) Create a Trigger to Raise appropriate error code and error message.
d) Create a Trigger on a table so that it will update another table while inserting values
14) Write a PL/SQL block for an application using cursors and all types of triggers.
15) Write a PL/SQL block for transaction operations of a typical application using package
INDEX
Experiments Page No
8 | Page
6) Implementation of subqueries and nested queries . 38
7)Implement Queries on Group by & Having Clauses, ALIAS, Sequence By, 43
Order By
8) Control Structure 45
a) Write a PL/SQL block for Addition of Two Numbers
b) Write a PL/SQL block for IF, IF and else condition
c) Write a PL/SQL block for implementation of loops
d) Write a PL/SQL block for greatest of three numbers using IF and ELSEIF
9) Exception Handling- Implement the following with respect to exception handling. 49
Raising Exceptions, User Defined Exceptions, Pre-Defined Exceptions
10) Write PL/SQL block for an application using exception handling Procedures 51
a) Write a PL/SQL Procedure using Positional Parameters
b) Write a PL/SQL Procedure using notational parameters
c) Write a PL/SQL Procedure for GCD Numbers
d) Write a PL/SQL Procedures for cursor implementation(explicit and implicit cursors)
11) Functions: 56
a) Write a PL/SQL block to implement factorial using functions
b) Write a PL/SQL function to search an address from the given database
12) Write a DBMS program to prepare Pl/SQL reports for an application using functions. 57
13) Triggers: 59
a) Write a Trigger to pop-up the DML operations
b) Write a Trigger to check the age valid or not Using Message Alert.
c) Create a Trigger to Raise appropriate error code and error message.
d) Create a Trigger on a table so that it will update another table while inserting values
14) Write a PL/SQL block for an application using cursors and all types of triggers. 61
create15) Write a PL/SQL block for transaction operations of a typical application using 63
package
Experiment-1
First of all, let’s define DDL, DML, DCL, and TCL in DBMS.
9 | Page
It’s four types of SQL sublanguages, that’s why it’s no sense to search for a difference between DDL vs DML or DCL vs TCL.
CREATE
CREATE statement is used to create a new database, table, index or stored procedure.
DROP
DROP statement allows you to remove database, table, index or stored procedure.
10 | Page
Drop table example:
CREATE TABLE user (
id INT(16) PRIMARY KEY AUTO_INCREMENT,
name VARCHAR(255) NOT NULL );
TRUNCATE student;
What is DML in SQL?
DML is a Data Manipulation Language, it’s used to build SQL queries to manipulate (select, insert, update, delete etc.) data in
the database.
SELECT
SELECT query is used to retrieve data from SQL tables.
Example:
Example:
11 | Page
UPDATE
UPDATE statement modifies records into the table.
Example:
CREATE TABLE user (
id INT(16) PRIMARY KEY AUTO_INCREMENT,
name VARCHAR(255) NOT NULL );
Example:
Its commands are responsible for access restrictions inside of the database.
GRANT
The GRANT command gives permissions to SQL user accounts.
For example, I want to grant all privileges to the ‘explain java’ database for user ‘dmytro@localhost’.
FLUSH PRIVILEGES;
REVOKE
A REVOKE statement is used to remove privileges from user accounts.
Example:
FLUSH PRIVILEGES;
Experiment-2
12 | Page
SELECT 10 * 10;Implementation of different types of operators and built-in functions with suitable examples
Arithmetic operators
SELECT 10 + 10;
- (Subtraction)
The - symbol subtracts one number from another.
SELECT 10 - 10;
* (Multiplication)
/ (Division)
The / symbol divides one number by another.
SELECT 10 / 10;
% (Remainder/Modulus)
The % symbol (sometimes referred to as Modulus) returns the remainder of one number divided by another.
SELECT 10 % 10;
Just a quick reminder: a binary number in computing is a number made up of 0s and 1s.
13 | Page
DECLARE @BitOne BIT = 1
DECLARE @BitTwo BIT = 1
SELECT @BitOne & @BitTwo;
Obviously this is just for variables that are type BIT. What would happen if we started using numbers instead? Take the
example below:
You might be thinking, “How on earth is it 194?!” and that’s perfectly understandable. To explain why, we first need to
convert the two numbers into their binary form:
Confused yet? Don’t worry! Bitwise operators can be confusing to understand, but they’re rarely used in practice.
| (Bitwise OR)
The | symbol (Bitwise OR) performs a bitwise logical OR operation between two values. Let’s revisit our example from
before:
Result - 11110110
The binary we are left with is 11110110, which equals a numeric value of 246.
14 | Page
|= (Bitwise OR Assignment)
The |= symbol (Bitwise OR Assignment) does the same as the Bitwise OR (|) operator but then sets the value of a variable to
the result that is returned.
Comparison operators
A comparison operator is used to compare two values and test whether they are the same.
= (Equal to)
The = symbol is used to filter results that equal a certain value. In the below example, this query will return all customers that
have an age of 20.
15 | Page
SELECT * FROM customers
WHERE age !> 20;
< (Less than)
The < symbol is used to filter results where a column’s value is less than the queried value. In the below example, this query
will return all customers that have an age below 20.
+= (Add equals)
The += operator will add a value to the original value and store the result in the original value. The below example sets a value
of 10, then adds 5 to the value and prints the result (15).
16 | Page
SET @addString += “quest”
PRINT @addString;
-= (Subtract equals)
The -= operator will subtract a value from the original value and store the result in the original value. The below example sets a
value of 10, then subtracts 5 from the value and prints the result (5).
ALL
The ALL operator returns TRUE if all of the subquery values meet the specified condition. In the below example, we are
filtering all users who have an age that is greater than the highest age of users in London.
SELECT product_name
FROM products
17 | Page
WHERE product_id > ANY (SELECT product_id FROM orders);
AND
The AND operator returns TRUE if all of the conditions separated by AND are true. In the below example, we are filtering
users that have an age of 20 and a location of London.
SELECT *
FROM users
WHERE age = 20 AND location = ‘London’;
BETWEEN
The BETWEEN operator filters your query to only return results that fit a specified range.
SELECT *
FROM users
WHERE age BETWEEN 20 AND 30;
EXISTS
The EXISTS operator is used to filter data by looking for the presence of any record in a subquery.
SELECT name
FROM customers
WHERE EXISTS
(SELECT order FROM ORDERS WHERE customer_id = 1);
IN
The IN operator includes multiple values set into the WHERE clause.
SELECT *
FROM users
WHERE first_name IN (‘Bob’, ‘Fred’, ‘Harry’);
LIKE
The LIKE operator searches for a specified pattern in a column. (For more information on how/why the % is used here, see the
section on the wildcard character operator).
SELECT *
FROM users
WHERE first_name LIKE ‘%Bob%’;
NOT
The NOT operator returns results if the condition or conditions are not true.
SELECT *
FROM users
WHERE first_name NOT IN (‘Bob’, ‘Fred’, ‘Harry’);
OR
The OR operator returns TRUE if any of the conditions separated by OR are true.In the below example, we are filtering users
that have an age of 20 or a location of London.
SELECT *
FROM users
18 | Page
WHERE age = 20 OR location = ‘London’;
IS NULL
The IS NULL operator is used to filter results with a value of NULL.
SELECT *
FROM users
WHERE age IS NULL;
String operators
String operators are primarily used for string concatenation (combining two or more strings together) and string pattern
matching.
+ (String concatenation)
The + operator can be used to combine two or more strings together. The below example would output ‘dataquest’.
SELECT *
FROM users
WHERE first_name LIKE ‘dan%’;
[] (Character(s) matches)
The [] is used to match any character within the specific range or set that is specified between the square brackets. In the below
example, we are searching for any users that have a first name that begins with a d and a second character that is somewhere in
the range c to r.
SELECT *
FROM users
WHERE first_name LIKE ‘d[c-r]%’’;
[^] (Character(s) not to match)
The [^] is used to match any character that is not within the specific range or set that is specified between the square brackets.
In the below example, we are searching for any users that have a first name that begins with a d and a second character that is
not a.
SELECT *
FROM users
19 | Page
WHERE first_name LIKE ‘d[^a]%’’;
_ (Wildcard match one character)
The _ symbol - sometimes referred to as the underscore character - is used to match any single character in a string comparison
operation. In the below example, we are searching for any users that have a first that begins with a d and has a third character
that is n. The second character can be any letter.
SELECT *
FROM users
WHERE first_name LIKE ‘d_n%’;
Other functions can be used in a variety of situations. Following is a list of function types that should contain almost every
supported built-in function:
20 | Page
Experiment-3
SQL Join statement is used to combine data or rows from two or more tables based on a common field between
them. Different types of Joins are as follows:
● INNER JOIN
● LEFT JOIN
● RIGHT JOIN
● FULL JOIN
StudentCourse
B. LEFT JOIN
22 | Page
This join returns all the rows of the table on the left side of the join and matches rows for the table on the right side of the join.
For the rows for which there is no matching row on the right side, the result-set will contain null. LEFT JOIN is also known as
LEFT OUTER JOIN.
Syntax:
SELECT table1.column1,table1.column2,table2.column1,....
FROM table1
LEFT JOIN table2
ON table1.matching_column = table2.matching_column;
table1: First table.
table2: Second table
matching_column: Column common to both the tables.
Note: We can also use LEFT OUTER JOIN instead of LEFT JOIN, both are the same.
C. RIGHT JOIN
23 | Page
RIGHT JOIN is similar to LEFT JOIN. This join returns all the rows of the table on the right side of the join and matching
rows for the table on the left side of the join. For the rows for which there is no matching row on the left side, the result-set
will contain null. RIGHT JOIN is also known as RIGHT OUTER JOIN.
Syntax:
SELECT table1.column1,table1.column2,table2.column1,....
FROM table1
RIGHT JOIN table2
ON table1.matching_column = table2.matching_column;
Output:
24 | Page
D. FULL JOIN
FULL JOIN creates the result-set by combining results of both LEFT JOIN and RIGHT JOIN. The result-set will contain all
the rows from both tables. For the rows for which there is no matching, the result-set will contain NULL values.
Syntax:
SELECT table1.column1,table1.column2,table2.column1,....
FROM table1
FULL JOIN table2
ON table1.matching_column = table2.matching_column;
25 | Page
FROM Student
FULL JOIN StudentCourse
ON StudentCourse.ROLL_NO = Student.ROLL_NO;
Output:
NAME COURSE_ID
HARSH 1
PRATIK 2
RIYANKA 2
DEEP 3
SAPTARSHI 1
DHANRAJ NULL
ROHIT NULL
NIRAJ NULL
NULL 4
NULL 5
NULL 4
Experiment-4
26 | Page
Create views, partitions, Sequence, Indexes and locks for a particular DB
EGIN TRAN
WHILE @i<100000
EGIN
27 | Page
NSERT INTO EmployeeReports
eportName,
eportNumber,
eportDescription
ALUES
ReportName',
ONVERT (varchar (20), @i),
EPLICATE ('Report', 1000)
ET @i=@GOi+1
ND
OMMIT TRAN
If we run a SQL query to pull ReportID, ReportName, ReportNumber data from the EmployeeReports table the result set that a
scan count is 5 and represents a number of times that the table was accessed during the query, and that we had 113,288 logical
reads that represent the total number of page accesses needed to process the query:
SET STATISTICS IO ON
SET STATISTICS TIME ON
SELECT er.ReportID, er.ReportName, er.ReportNumber
FROM dbo.EmployeeReports er
WHERE er.ReportNumber LIKE '%33%'
28 | Page
SET STATISTICS IO OFF
SET STATISTICS TIME OFF
As indicated, every page is read from the data cache, whether or not it was necessary to bring that page from disk into the
cache for any given read. To reduce the cost of the query we will change the SQL Server database schema and split
the EmployeeReports table vertically.
Next we’ll create the ReportsDesc table and move the large ReportDescription column, and the ReportsData table and move all
data from the EmployeeReports table except the ReportDescription column:
29 | Page
INSERT INTO dbo.ReportsData
(
ReportID,
ReportName,
ReportNumber
)
SELECT er.ReportID,
er.ReportName,
er.ReportNumber
FROM dbo.EmployeeReports er
30 | Page
Vertical partitioning on SQL Server tables may not be the right method in every case. However, if you have, for example, a
table with a lot of data that is not accessed equally, tables with data you want to restrict access to, or scans that return a lot of
data, vertical partitioning can help.
Horizontal Partitioning on SQL Server tables
Horizontal partitioning divides a table into multiple tables that contain the same number of columns, but fewer rows. For
example, if a table contains a large number of rows that represent monthly reports it could be partitioned horizontally into
tables by years, with each table representing all monthly reports for a specific year. This way queries requiring data for a
specific year will only reference the appropriate table. Tables should be partitioned in a way that queries reference as few
tables as possible.
Tables are horizontally partitioned based on a column which will be used for partitioning and the ranges associated to each
partition. Partitioning column is usually a datetime column but all data types that are valid for use as index columns can be
used as a partitioning column, except a timestamp column. The ntext, text, image, xml, varchar(max), nvarchar(max), or
varbinary(max), Microsoft .NET Framework common language runtime (CLR) user-defined type, and alias data type columns
cannot be specified.
There are two different approaches we could use to accomplish table partitioning. The first is to create a new partitioned table
and then simply copy the data from your existing table into the new table and do a table rename. The second approach is to
partition an existing table by rebuilding or creating a clustered index on the table.
31 | Page
An example of horizontal partitioning with creating a new partitioned table
SQL Server 2005 introduced a built-in partitioning feature to horizontally partition a table with up to 1000 partitions in SQL
Server 2008, and 15000 partitions in SQL Server 2012, and the data placement is handled automatically by SQL Server. This
feature is available only in the Enterprise Edition of SQL Server.
To create a partitioned table for storing monthly reports we will first create additional filegroups. A filegroup is a logical
storage unit. Every database has a primary filegroup that contains the primary data file (.mdf). An additional, user-defined,
filegroup can be created to contain secondary files (.ndf). We will create 12 filegroups for every month:
1 ALTER DATABASE
PartitioningDB
2
ADD FILEGROUP January
3
GO
4
ALTER DATABASE
5 PartitioningDB
6 ADD FILEGROUP February
7 GO
8 ALTER DATABASE
PartitioningDB
9
ADD FILEGROUP March
10
GO
11
ALTER DATABASE
12
PartitioningDB
13
ADD FILEGROUP April
14
GO
15
ALTER DATABASE
16 PartitioningDB
18 GO
19 ALTER DATABASE
PartitioningDB
20
ADD FILEGROUP June
21
GO
22
ALTER DATABASE
32 | Page
PartitioningDB
ADD FILEGROUP July
GO
ALTER DATABASE
23 PartitioningDB
24 ADD FILEGROUP Avgust
25 GO
26 ALTER DATABASE
PartitioningDB
27
ADD FILEGROUP September
28
GO
29
ALTER DATABASE
30
PartitioningDB
31
ADD FILEGROUP October
32
GO
33
ALTER DATABASE
34 PartitioningDB
C36 GO
ALTER DATABASE
PartitioningDB
ADD FILEGROUP December
GO
To check created and available file groups in the current database run the following query:
SELECT name AS AvailableFilegroups
FROM sys.filegroups
WHERE type = 'FG'
33 | Page
Views
CREATING VIEWS
We can create View using CREATE VIEW statement. A View can be created from a single table or multiple tables. Syntax:
CREATE VIEW view_name AS
SELECT column1, column2.....
FROM table_name
WHERE condition;
● To see the data in the View, we can query the view in the same manner as we query a table.
SELECT * FROM DetailsView;
Output:
34 | Page
● In this example, we will create a view named StudentNames from the table StudentDetails. Query:
CREATE VIEW StudentNames AS
SELECT S_ID, NAME
FROM StudentDetails
ORDER BY NAME;
● Creating View from multiple tables: In this example we will create a View named MarksView from two tables
StudentDetails and StudentMarks. To create a View from multiple tables we can simply include multiple tables in the
SELECT statement. Query:
CREATE VIEW MarksView AS
SELECT StudentDetails.NAME, StudentDetails.ADDRESS, StudentMarks.MARKS
FROM StudentDetails, StudentMarks
WHERE StudentDetails.NAME = StudentMarks.NAME;
● Output:
35 | Page
LISTING ALL VIEWS IN A DATABASE
We can list View using the SHOW FULL TABLES statement or using the information_schema table. A View can be created
from a single table or multiple tables.
Syntax (Using SHOW FULL TABLES):
use "database_name";
show full tables where table_type like "%VIEW";
Syntax (Using information_schema) :
select * from information_schema.views where table_schema = "database_name";
OR
DELETING VIEWS
We have learned about creating a View, but what if a created View is not needed any more? Obviously we will want to delete
it. SQL allows us to delete an existing View. We can delete or drop a View using the DROP statement. Syntax:
DROP VIEW view_name;
36 | Page
FROM table_name
WHERE condition;
● For example, if we want to update the view MarksView and add the field AGE to this View from StudentMarks Table, we
can do this as:
CREATE OR REPLACE VIEW MarksView AS
SELECT StudentDetails.NAME, StudentDetails.ADDRESS, StudentMarks.MARKS, StudentMarks.AGE
FROM StudentDetails, StudentMarks
WHERE StudentDetails.NAME = StudentMarks.NAME;
● Output:
● Inserting a row in a view: We can insert a row in a View in the same way as we do in a table. We can use the INSERT
INTO statement of SQL to insert a row in a View.
Syntax:
INSERT INTO view_name(column1, column2 , column3,..)
VALUES(value1, value2, value3..);
37 | Page
● Deleting a row from a View: Deleting rows from a view is also as simple as deleting rows from a table. We can use the
DELETE statement of SQL to delete rows from a view. Also deleting a row from a view first deletes the row from the
actual table and the change is then reflected in the view.
Syntax:
DELETE FROM view_name
WHERE condition;
Sequences
Sequence is a set of integers 1, 2, 3, … that are generated and supported by some database systems to produce unique values
on demand.
38 | Page
● A sequence is a user defined schema bound object that generates a sequence of numeric values.
● Sequences are frequently used in many databases because many applications require each row in a table to contain a unique
value and sequences provide an easy way to generate them.
● The sequence of numeric values is generated in an ascending or descending order at defined intervals and can be
configured to restart when exceeds max_value.
Syntax:
CREATE SEQUENCE sequence_name
START WITH initial_value
INCREMENT BY increment_value
MINVALUE minimum value
MAXVALUE maximum value
CYCLE|NOCYCLE ;
● Example 1:
● CREATE SEQUENCE sequence_1
● start with 1
● increment by 1
● minvalue 0
39 | Page
● maxvalue 100
● cycle;
Above query will create a sequence named sequence_1.Sequence will start from 1 and will be incremented by 1 having
maximum value 100. Sequence will repeat itself from start value after exceeding 100.
● Example 2:
Following is the sequence query creating sequence in descending order.
● CREATE SEQUENCE sequence_2
● increment by -1
● minvalue 1
● maxvalue 100
● cycle;
Above query will create a sequence named sequence_2.Sequence will start from 100 and should be less than or equal to
maximum value and will be incremented by -1 having minimum value 1.
● Example to use sequence : create a table named students with columns as id and name.
● (
● ID number(10),
● NAME char(20)
● );
40 | Page
| 2 | Suresh |
----------------------
Experiment-5
● A NOT NULL constraint is a rule that prevents null values from being entered into one or more columns within a table.
● A unique constraint (also referred to as a unique key constraint) is a rule that forbids duplicate values in one or more
columns within a table. Unique and primary keys are the supported unique constraints. For example, a unique
constraint can be defined on the supplier identifier in the supplier table to ensure that the same supplier identifier is not
given to two suppliers.
● A primary key constraint is a column or combination of columns that has the same properties as a unique constraint.
You can use a primary key and foreign key constraints to define relationships between tables.
constraint (also referred to as a referential constraint or a referential integrity constraint) is a logical rule about values in one
mns in one or more tables. For example, a set of tables shares information about a corporation's suppliers. Occasionally, a
me changes. You can define a referential constraint that states the ID of the supplier in a table must match a supplier ID in the
mation. This constraint prevents insert, update, or delete operations that would otherwise result in missing supplier information.
e check constraint (also called a check constraint) sets restrictions on data that is added to a specific table. For example, you
e a table check constraint whenever salary data is added or updated in a table that contains personal information. For such
ions, the table check constraint can ensure that the salary level for an employee is at least $20 000.
An informational constraint is an attribute of a certain type of constraint, but the attribute is not enforced by the database
manager.
41 | Page
one or more columns of every row of a table. Specifying check constraints is done through a restricted form of a search
condition.
● Foreign key (referential) constraints
Foreign key constraints (also known as referential constraints or referential integrity constraints) enable definition of
required relationships between and within tables.
● Informational constraints
An informational constraint is a constraint attribute that can be used by the SQL compiler to improve the access to
data. Informational constraints are not enforced by the database manager, and are not used for additional verification of
data; rather, they are used to improve query performance.
NOT NULL:
NOT NULL constraint makes sure that a column does not hold NULL value. When we don’t provide a value for a particular
column while inserting a record into a table, it takes a NULL value by default. By specifying
NULL constraint, we can be sure that a particular column(s) cannot have NULL values.
Example:
UNIQUE:
UNIQUE Constraint enforces a column or set of columns to have unique values. If a column has a unique constraint, it means
that particular column cannot have duplicate values in a table.
42 | Page
createDEFAULT:
The DEFAULT constraint provides a default value to a column when there is no value provided while inserting a record into a
table.
CHECK:
This constraint is used for specifying a range of values for a particular column of a table. When this constraint is being set on a
column, it ensures that the specified column must have the value falling in the specified range.
Key constraints:
KEY:
Primary key uniquely identifies each record in a table. It must have unique values and cannot contain nulls. In the below
example the ROLL_NO field is marked as primary key, that means the ROLL_NO field cannot have duplicate and null values.
43 | Page
);
FOREIGN KEY:
Foreign keys are the columns of a table that points to the primary key of another table. They act as a cross-reference between
tables.
Read more about it here.
Domain constraints:
Each table has a certain set of columns and each column allows the same type of data, based on its data type. The column does
not accept values of any other data type.
Domain constraints are user defined data type and we can define them like this:
Domain Constraint = data type + Constraints (NOT NULL / UNIQUE / PRIMARY KEY / FOREIGN KEY / CHECK /
DEFAULT)
Experiment-6
A Subquery or Inner query or a Nested query is a query within another SQL query and embedded within the WHERE clause.
A subquery is used to return data that will be used in the main query as a condition to further restrict the data to be retrieved.
Subqueries can be used with the SELECT, INSERT, UPDATE, and DELETE statements along with the operators like =, <, >,
>=, <=, IN, BETWEEN, etc.
There are a few rules that subqueries must follow
● The SELECT list cannot include any references to values that evaluate to a BLOB, ARRAY, CLOB, or NCLOB.
● A subquery cannot be immediately enclosed in a set function.
● The BETWEEN operator cannot be used with a subquery. However, the BETWEEN operator can be used within the
subquery.
intSubqueries with the SELECT Statement
Subqueries are most frequently used with the SELECT statement. The basic syntax is as follows
44 | Page
SELECT column_name [, column_name ]
FROM table1 [, table2 ]
WHERE column_name OPERATOR
(SELECT column_name [, column_name ]
FROM table1 [, table2 ]
[WHERE])
Example
Consider the CUSTOMERS table having the following records
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 35 | 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 |
+----+----------+-----+-----------+----------+
Now, let us check the following subquery with a SELECT statement.
SQL> SELECT *
FROM CUSTOMERS
WHERE ID IN (SELECT ID
FROM CUSTOMERS
WHERE SALARY > 4500) ;
This would produce the following result.
+----+----------+-----+---------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+---------+----------+
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+---------+----------+
Subqueries with the INSERT Statement
Subqueries also can be used with INSERT statements. The INSERT statement uses the data returned from the subquery to
insert into another table. The selected data in the subquery can be modified with any of the character, date or number
functions.
The basic syntax is as follows.
INSERT INTO table_name [ (column1 [, column2 ]) ]
SELECT [ *|column1 [, column2 ]
FROM table1 [, table2 ]
45 | Page
[ WHERE VALUE OPERATOR ]
Example
Consider a table CUSTOMERS_BKP with a similar structure as CUSTOMERS table. Now to copy the complete
CUSTOMERS table into the CUSTOMERS_BKP table, you can use the following syntax.
SQL> INSERT INTO CUSTOMERS_BKP
SELECT * FROM CUSTOMERS
WHERE ID IN (SELECT ID
FROM CUSTOMERS) ;
Subqueries with the UPDATE Statement
The subquery can be used in conjunction with the UPDATE statement. Either single or multiple columns in a table can be
updated when using a subquery with the UPDATE statement.
The basic syntax is as follows.
UPDATE table
SET column_name = new_value
[ WHERE OPERATOR [ VALUE ]
(SELECT COLUMN_NAME
FROM TABLE_NAME)
[ WHERE) ]
Example
Assuming, we have a CUSTOMERS_BKP table available which is a backup of the CUSTOMERS table. The following
example updates SALARY by 0.25 times in the CUSTOMERS table for all the customers whose AGE is greater than or equal
to 27.
SQL> UPDATE CUSTOMERS
SET SALARY = SALARY * 0.25
WHERE AGE IN (SELECT AGE FROM CUSTOMERS_BKP
WHERE AGE >= 27 );
This would impact two rows and finally the CUSTOMERS table would have the following records.
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 35 | Ahmedabad | 125.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 2125.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+-----------+----------+
deSubqueries with the DELETE Statement
The subquery can be used in conjunction with the DELETE statement like with any other statements mentioned above.
46 | Page
The basic syntax is as follows.
DELETE FROM TABLE_NAME
[ WHERE OPERATOR [ VALUE ]
(SELECT COLUMN_NAME
FROM TABLE_NAME)
[ WHERE) ]
Example
Assuming, we have a CUSTOMERS_BKP table available which is a backup of the CUSTOMERS table. The following
example deletes the records from the CUSTOMERS table for all the customers whose AGE is greater than or equal to 27.
SQL> DELETE FROM CUSTOMERS
WHERE AGE IN (SELECT AGE FROM CUSTOMERS_BKP
WHERE AGE >= 27 );
This would impact two rows and finally the CUSTOMERS table would have the following records.
+----+----------+-----+---------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+---------+----------+
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+---------+----------+
Nested subqueries
A subquery can be nested inside other subqueries. SQL has an ability to nest queries within one another. A subquery is a
SELECT statement that is nested within another SELECT statement and which returns intermediate results. SQL executes the
innermost subquery first, then the next level. See the following examples :
If we want to retrieve that unique job_id and there average salary from the employees table which unique job_id have a salary
is smaller than (the maximum of averages of min_salary of each unique job_id from the jobs table which job_id are in the list,
picking from (the job_history table which is within the department_id 50 and 100)) the following SQL statement can be used :
SQL Code:
dry)
FROM employees
47 | Page
GROUP BY job_id
HAVING AVG(salary)<
(SELECT MAX(AVG(min_salary))
WHERE job_id IN
WHERE department_id
GROUP BY job_id);
Copy
The above code is executed in Oracle 11g Express Edition.
orCREATE
SELECT job_id,AVG(salary)
SELECT job_id,AVG(salary)
FROM employees
GROUP BY job_id
HAVING AVG(salary)<
FROM jobs
WHERE job_id IN
WHERE department_id
Copy
48 | Page
The above code is executed in PostgreSQL 9.3
Output:
JOB_ID AVG(SALARY)
---------- -----------
IT_PROG 5760
AC_ACCOUNT 8300
ST_MAN 7280
AD_ASST 4400
SH_CLERK 3215
FI_ACCOUNT 7920
PU_CLERK 2780
SA_REP 8350
MK_REP 6000
ST_CLERK 2785
HR_REP 6500
Experiment-7
VALUES
Implement Queries on Group By & Having Clauses, ALIAS, Sequence By, Order By
IN
(6, '2022-05-28', '09:00:00', 'Downton Abbey A New Era', 'Drama', 137, 8.00),
(2, '2022-05-27', '10:00:00', 'Downton Abbey A New Era', 'Drama', 90, 18.00),
49 | Page
(3, '2022-05-27', '10:00:00', 'Men', 'Horror', 100, 18.00),
(10, '2022-05-28', '05:00:00', 'Downton Abbey A New Era', 'Drama', 118, 13.00),
output:
+------------+------------+----------+-------------------------+-------------+-------------+-------------+
+------------+------------+----------+-------------------------+-------------+-------------+-------------+
50 | Page
| 10 | 2022-05-28 | 05:00:00 | Downton Abbey A New Era | Drama | 118 | 13.00 |
+------------+------------+----------+-------------------------+-------------+-------------+-------------+
Experiment-8
Control Structure
a. Write a PL/SQL block for Addition of Two Numbers
Declare
x number(5);
y number(5);
z number(7);
begin
output:
Sum is 30
DECLARE
a number(3) := 100;
51 | Page
BEGIN
ELSE
END IF;
END;
Output:
value of a is : 100
a number(2);
BEGIN
FOR a in 10 .. 20 LOOP
END LOOP;
END;
52 | Page
/
value of a: 10
value of a: 11
value of a: 12 s
value of a: 13
value of a: 14
value of a: 15
value of a: 16
value of a: 17
value of a: 18
value of a: 19
value of a: 20
d. Write a PL/SQL block for greatest of three numbers using IF and ELSEIF
nprevious chapters
DEset CLARE
c_id customers.id%type := 8;
c_name customerS.Name%type;
c_addr customers.address%type;
BEGIN
FROM customers
WHERE id = c_id;
53 | Page
DBMS_OUTPUT.PUT_LINE ('Name: '|| c_name);
EXCEPTION
dbms_output.put_line('Error!');
END;
/umber(5)
declare x numbeYBHUJHY,ŚḌĒKW78Er(5);
z numbernumber(7);
begin
ms_output.put_line('Sum is '||z);
end;
54 | Page
Output:
Greatest number is 67
Exception Handling- Implement the following with respect to exception handling. Raising Exceptions, User Defined
Exceptions, Pre-Defined Exceptions
The general syntax for exception handling is as follows. Here you can list down as many exceptions as you can handle. The def
DECLARE
........
exception-handling-statements
END;
Example
Let us write a code to illustrate the concept. We will be using the CUSTOMERS table we had created and used in the
When the above code is executed at the SQL prompt, it produces the following result
No such customer!
Experiment-10
55 | Page
DECLARE
a number;
b number;
c number;
BEGIN
IF x < y THEN
z:= x;
ELSE
z:= y;
END IF;
END;
BEGIN
a:= 23;
b:= 45;
findMin(a, b, c);
END;
Output:
DECLARE
56 | Page
l_vc_dept VARCHAR2(30);
l_n_sal NUMBER;
BEGIN
l_n_sal:=func_emp(7815,'John','13-June-2011',l_vc_dept);
END;
||' is '
||num1);DECLARE
num1 INTEGER;
num2 INTEGER;
t INTEGER;
BEGIN
num1 := 8;
num2 := 48;
t := MOD(num2, num1);
num2 := num1;
57 | Page
num1 := t;
END LOOP;
dbms_output.Put_line('GCD of '
||num1
||num2
END;
-- Program End
Output:
GCD of 8 and 48 is 8
+----+----------+-----+-----------+----------+
+----+----------+-----+-----------+----------+
58 | Page
| 6 | Komal | 22 | MP | 4500.00 |
+----+----------+-----+-----------+----------+
DECLARE
total_rows number(2);
BEGIN
UPDATE customers
IF sql%notfound THEN
total_rows := sql%rowcount;
END IF;
END;
Output:
6 customers selected
Explicit cursors:
DECLARE
c_id customers.id%type;
c_addr customers.address%type;
59 | Page
CURSOR c_customers is
BEGIN
OPEN c_customers;
LOOP
END LOOP;
CLOSE c_customers;
END;
Output:
1 Ramesh Ahmedabad
2 Khilan Delhi
3 kaushik Kota
4 Chaitali Mumbai
5 Hardik Bhopal
6 Komal MP
Experiment-11
Functions:
declare
60 | Page
fac number :=1;
-- given number n
n number := &1;
-- start blockfac
begin
fac:=n*fac;
n:=n-1;
end loop;
-- end loop
dbms_output.put_line(fac);
end;
Output:
120
Experiment-12
Write a PL/SQL function to search an address from the given database
61 | Page
EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO
2 return emp.job%type
3 is
4 retval emp.job%type;
5 begin
6 select e.job
7 into retval
8 from emp e
10
11 return retval;
12
13 exception
16 end;
17 /
62 | Page
Function created.
RESULT
---------------------------------------------------------------------------------------------
MANAGER
Experiment-13
In this code section you will see the basic CREATE TRIGGER syntax.
Additionally the next table describes each of the arguments of the CREATE TRIGGER syntax.
Argument Description
Indicates when the trigger must fire. FOR or AFTER
occurs after the insert, delete or update occurs. INSTEAD
FOR | AFTER | INSTEAD OF
OF occurs instead of the insert, delete or update operation
from occurring.
[INSERT], [UPDATE], [DELETE The DML event (or list of events) that will cause the
] trigger to fire.
USE [SampleDB]
63 | Page
GO
In the code below you will see the most basic DML trigger we can make, which will return "Hello World". This trigger will
show a "Hello World!" line every time a row is added to the Employees table.
USE [SampleDB]
GO
CREATE TRIGGER [dbo].[TR_Employees] ON [dbo].[Employees]
FOR INSERT
AS
SELECT 'Hello World!'
GO
In order to test this trigger we need to insert some data into the Employees table. We can do so with the next script.
64 | Page
INSERT INTO dbo.Employees ( EmployeeName , EmployeeAddress ,MonthSalary )
VALUES ( 'Paul Martinez' , '22 Street 4217', 4000)
GO
On the next image you can see the execution of the previous script. Notice that when the INSERT statement executes it prints a
"Hello World!" message.
b. Write a Trigger to check the age valid or not Using Message Alert.
end;
65 | Page
Experiment-14
Write PL/SQL block for an application using cursors and all types of triggers.
DECLARE
CURSOR dpt_cur IS
SELECT d.department_id id,
department_name deptname,
city,
Nvl(first_name, '...') manager
FROM departments d
dbms_output.Put_line(Rpad(dept_all.dptname, 20)
|| Rpad(dept_all.manager, 15)
|| Rpad(dept_all.city, 20)
|| Rpad(emp_name, 20));
END LOOP;
END;
/
Output:
SQL> /
66 | Page
Accounting Shelley Seattle Shelley
Administration Jennifer Seattle Jennifer
Benefits ... Seattle ...
Construction ... Seattle ...
Contracting ... Seattle ...
Control And Credit ... Seattle ...
Corporate Tax ... Seattle ...
Executive Steven Seattle Steven
Finance Nancy Seattle Nancy
Government Sales ... Seattle ...
Human Resources Susan London Susan
IT Alexander Southlake Alexander
IT Helpdesk ... Seattle ...
IT Support ... Seattle ...
Manufacturing ... Seattle ...
Marketing Michael Toronto Michael
NOC ... Seattle ...
Operations ... Seattle ...
Payroll ... Seattle ...
Public Relations Hermann Munich Hermann
Purchasing Den Seattle Den
Recruiting ... Seattle ...
Retail Sales ... Seattle ...
Sales John Oxford John
Shareholder Services... Seattle ...
Shipping Adam South San Francisco Adam
Treasury ... Seattle ...
Experiment-15
Write a PL/SQL block for transaction operations of a typical application using package
67 | Page
/
DECLARE
total_rows number(2);
BEGIN
UPDATE customers
SET salary = salary + 5000;
IF sql%notfound THEN
dbms_output.put_line('no customers updated');
ELSE IF sql%found THEN
total_rows := sql%rowcount;
dbms_output.put_line( total_rows || ' customers updated ');
END IF;
END;
/
Output:
Old salary: 20000
New salary: 25000
Salary difference: 5000
Old salary: 22000
New salary: 27000
Salary difference: 5000
Old salary: 24000
New salary: 29000
Salary difference: 5000
Old salary: 26000
New salary: 31000
Salary difference: 5000
Old salary: 28000
New salary: 33000
Salary difference: 5000
Old salary: 30000
New salary: 35000
Salary difference: 5000
6 customers updated
68 | Page
69 | Page