DBMS LAB MANUAL 2025 (1)
DBMS LAB MANUAL 2025 (1)
LAB MANUAL
OF
DATABASE MANAGEMENT SYSTEMS
II B.TECH II Semester CourseCode:A2AM407PC
(HITS – R22)
Prepared By:
Mr. A . GOPI
Assistant Professor
DEPARTMENT OF CSE
(ARTIFICIAL INTELLIGENCE & MACHINE LEARNING)
1
S.No. NAME OF THE PROGRAMS Page
no.
1 WEEK -1
DDL Commands
Creation of Tables using SQL- Overview of using SQL tool and Data types in SQL
Altering Tables and
Dropping Tables
2 WEEK -2
Create Table with Primary key and Foreign Key& DML Commands
Creating Tables (along with Primary and Foreign keys), Practicing DML commands-
Insert,
Update
Delete.
3 WEEK -3
Selection Queries
Practicing Select command using following operations
AND, OR
ORDER BY
BETWEEN
LIKE
Apply CHECK constraint
4 WEEK -4
Aggregate Functions and Views
Practice Queries using following functions
COUNT,
SUM,
AVG,
MAX,
MIN,
9 WEEK -9
Procedures
Procedures- Creation of Stored Procedures, Execution of Procedure, and Modification of
Procedure.
10 WEEK -10
Cursors
Cursors- Declaring Cursor, Opening Cursor, Fetching the data, closing the cursor.
11 WEEK -11
PL/SQL Part 1
Practice PL/SQL –
block structure,
variables,
data types,
12 WEEK -12
PL/SQL Part 2
Practice PL/SQL –
operators,
control structures;
aseca
3
WEEK 1
AIM:
DDL Commands
Creation of Tables using SQL- Overview of using SQL tool and Data types in SQL
Altering Tables and
Dropping Tables
PROGRAM:
Creation of Tables using SQL- Overview of using SQL tool and Data types in SQL
Creating a basic table involves naming the table and defining its columns and each
column's data type.
The SQL CREATE TABLE statement is used to create a new table.
Syntax
The basic syntax of the CREATE TABLE statement is as follows −
CREATE TABLE table_name(
column1 datatype,
column2 datatype,
column3 datatype,
.....
columnN datatype,
PRIMARY KEY( one or more columns )
);
CREATE TABLE is the keyword telling the database system what you want to do. In this
case, you want to create a new table. The unique name or identifier for the table follows
the CREATE TABLE statement.
Then in brackets comes the list defining each column in the table and what sort of data
type it is. The syntax becomes clearer with the following example.
A copy of an existing table can be created using a combination of the CREATE TABLE
statement and the SELECT statement. You can check the complete details at Create
Table Using another Table.
Example
The following code block is an example, which creates a CUSTOMERS table with an ID
as a primary key and NOT NULL are the constraints showing that these fields cannot be
NULL while creating records in this table −
SQL> CREATE TABLE CUSTOMERS(
ID INT NOT NULL,
NAME VARCHAR (20) NOT NULL,
AGE INT NOT NULL,
ADDRESS CHAR (25) ,
4
SALARY DECIMAL (18, 2),
PRIMARY KEY (ID)
);
You can verify if your table has been created successfully by looking at the message
displayed by the SQL server, otherwise you can use the DESC command as follows −
SQL> DESC CUSTOMERS;
+---------+---------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+---------+---------------+------+-----+---------+-------+
| ID | int(11) | NO | PRI | | |
| NAME | varchar(20) | NO | | | |
| AGE | int(11) | NO | | | |
| ADDRESS | char(25) | YES | | NULL | |
| SALARY | decimal(18,2) | YES | | NULL | |
+---------+---------------+------+-----+---------+-------+
5 rows in set (0.00 sec)
Now, you have CUSTOMERS table available in your database which you can use to store
the required information related to customers.
Altering Tables and
The SQL ALTER TABLE command is used to add, delete or modify columns in an
existing table. You should also use the ALTER TABLE command to add and drop various
constraints on an existing table.
Syntax
The basic syntax of an ALTER TABLE command to add a New Column in an existing
table is as follows.
ALTER TABLE table_name ADD column_name datatype;
The basic syntax of an ALTER TABLE command to DROP COLUMN in an existing table
is as follows.
ALTER TABLE table_name DROP COLUMN column_name;
The basic syntax of an ALTER TABLE command to change the DATA TYPE of a column
in a table is as follows.
ALTER TABLE table_name MODIFY COLUMN column_name datatype;
The basic syntax of an ALTER TABLE command to add a NOT NULL constraint to a
column in a table is as follows.
ALTER TABLE table_name MODIFY column_name datatype NOT NULL;
The basic syntax of ALTER TABLE to ADD UNIQUE CONSTRAINT to a table is as
follows.
ALTER TABLE table_name
ADD CONSTRAINT MyUniqueConstraint UNIQUE(column1, column2...);
5
The basic syntax of an ALTER TABLE command to ADD CHECK CONSTRAINT to a
table is as follows.
ALTER TABLE table_name
ADD CONSTRAINT MyUniqueConstraint CHECK (CONDITION);
The basic syntax of an ALTER TABLE command to ADD PRIMARY KEY constraint to a
table is as follows.
ALTER TABLE table_name
ADD CONSTRAINT MyPrimaryKey PRIMARY KEY (column1, column2...);
The basic syntax of an ALTER TABLE command to DROP CONSTRAINT from a table is
as follows.
ALTER TABLE table_name
DROP CONSTRAINT MyUniqueConstraint;
If you're using MySQL, the code is as follows −
ALTER TABLE table_name
DROP INDEX MyUniqueConstraint;
The basic syntax of an ALTER TABLE command to DROP PRIMARY KEY constraint
from a table is as follows.
ALTER TABLE table_name
DROP CONSTRAINT MyPrimaryKey;
If you're using MySQL, the code is as follows −
ALTER TABLE table_name
DROP PRIMARY KEY;
Example
Consider the CUSTOMERS table having the following records −
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+-----------+----------+
Following is the example to ADD a New Column to an existing table −
ALTER TABLE CUSTOMERS ADD SEX char(1);
Now, the CUSTOMERS table is changed and following would be output from the SELECT
statement.
6
+----+---------+-----+-----------+----------+------+
| ID | NAME | AGE | ADDRESS | SALARY | SEX |
+----+---------+-----+-----------+----------+------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 | NULL |
| 2 | Ramesh | 25 | Delhi | 1500.00 | NULL |
| 3 | kaushik | 23 | Kota | 2000.00 | NULL |
| 4 | kaushik | 25 | Mumbai | 6500.00 | NULL |
| 5 | Hardik | 27 | Bhopal | 8500.00 | NULL |
| 6 | Komal | 22 | MP | 4500.00 | NULL |
| 7 | Muffy | 24 | Indore | 10000.00 | NULL |
+----+---------+-----+-----------+----------+------+
Following is the example to DROP sex column from the existing table.
ALTER TABLE CUSTOMERS DROP SEX;
Now, the CUSTOMERS table is changed and following would be the output from the
SELECT statement.
+----+---------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+---------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Ramesh | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | kaushik | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+---------+-----+-----------+----------+
Dropping Tables
The SQL DROP TABLE statement is used to remove a table definition and all the data,
indexes, triggers, constraints and permission specifications for that table.
NOTE − You should be very careful while using this command because once a table is
deleted then all the information available in that table will also be lost forever.
Syntax
The basic syntax of this DROP TABLE statement is as follows −
DROP TABLE table_name;
Example
Let us first verify the CUSTOMERS table and then we will delete it from the database as
shown below −
SQL> DESC CUSTOMERS;
+---------+---------------+------+-----+---------+-------+
7
| Field | Type | Null | Key | Default | Extra |
+---------+---------------+------+-----+---------+-------+
| ID | int(11) | NO | PRI | | |
| NAME | varchar(20) | NO | | | |
| AGE | int(11) | NO | | | |
| ADDRESS | char(25) | YES | | NULL | |
| SALARY | decimal(18,2) | YES | | NULL | |
+---------+---------------+------+-----+---------+-------+
5 rows in set (0.00 sec)
This means that the CUSTOMERS table is available in the database, so let us now drop it
as shown below.
SQL> DROP TABLE CUSTOMERS;
Query OK, 0 rows affected (0.01 sec)
Now, if you would try the DESC command, then you will get the following error −
SQL> DESC CUSTOMERS;
ERROR 1146 (42S02): Table 'TEST.CUSTOMERS' doesn't exist
Here, TEST is the database name which we are using for our examples.
8
WEEK -2
AIM:
Create Table with Primary key and Foreign Key& DML Commands
Creating Tables (along with Primary and Foreign keys), Practicing DML commands-
Insert,
Update
Delete.
PROGRAM:
If we want to retrieve the data from all the columns of the table, we have to use the
following SELECT command:
This SQL statement displays the following values of the student table:
BCA1001 Abhay 85
BCA1002 Anuj 75
BCA1003 Bheem 60
BCA1004 Ram 79
9
BCA1005 Sumit 80
Example 2: This example shows all the values of a specific column from the table.
This SELECT statement displays all the values of Emp_Salary and Emp_Id column
of Employee table:
Emp_Id Emp_Salary
201 25000
202 45000
203 30000
204 29000
205 40000
Example 3: This example describes how to use the WHERE clause with the SELECT
DML command.
BCA1001 Abhay 80
BCA1002 Ankit 75
BCA1003 Bheem 80
10
BCA1004 Ram 79
BCA1005 Sumit 80
If you want to access all the records of those students whose marks is 80 from the above
table, then you have to write the following DML command in SQL:
BCA1001 Abhay 80
BCA1003 Bheem 80
BCA1005 Sumit 80
Let's take the following student table, which consists of only 2 records of the student.
11
Stu_Id Stu_Name Stu_Marks Stu_Age
101 Ramesh 92 20
201 Jatin 83 19
Suppose, you want to insert a new record into the student table. For this, you have to
write the following DML INSERT command:
1. INSERT INTO Student (Stu_id, Stu_Name, Stu_Marks, Stu_Age) VALUES (104, Anmol, 89, 19);
Here, 'UPDATE', 'SET', and 'WHERE' are the SQL keywords, and 'Table_name' is the name
of the table whose values you want to update.
P101 Chips 20 20
P102 Chocolates 60 40
P103 Maggi 75 5
12
P201 Biscuits 80 20
P203 Namkeen 40 50
Suppose, you want to update the Product_Price of the product whose Product_Id is
P102. To do this, you have to write the following DML UPDATE command:
Example 2: This example describes how to update the value of multiple fields of
the database table.
101 Ramesh 92 20
201 Jatin 83 19
202 Anuj 85 19
203 Monty 95 21
102 Saket 65 21
103 Sumit 78 19
104 Ashish 98 20
Suppose, you want to update Stu_Marks and Stu_Age of that student whose Stu_Id is
103 and 202. To do this, you have to write the following DML Update command:
1. UPDATE Student SET Stu_Marks = 80, Stu_Age = 21 WHERE Stu_Id = 103 AND Stu_Id = 202;
This command of Data Manipulation Language does not delete the stored data
permanently from the database. We use the WHERE clause with the DELETE command
to select specific rows from the table.
P101 Chips 20 20
P102 Chocolates 60 40
P103 Maggi 75 5
P201 Biscuits 80 20
P203 Namkeen 40 50
Suppose, you want to delete that product from the Product table whose Product_Id is
P203. To do this, you have to write the following DML DELETE command:
Example 2: This example describes how to delete the multiple records or rows
from the database table.
14
Stu_Id Stu_Name Stu_Marks Stu_Age
101 Ramesh 92 20
201 Jatin 83 19
202 Anuj 85 19
203 Monty 95 21
102 Saket 65 21
103 Sumit 78 19
104 Ashish 98 20
Suppose, you want to delete the record of those students whose Marks is greater than
70. To do this, you have to write the following DML Update command:
15
WEEK -3
AIM:
Selection Queries
Practicing Select command using following operations
AND, OR
ORDER BY
BETWEEN
LIKE
Apply CHECK constraint
PROGRAM:
The AND and OR operators are used to filter records based on more than one
condition:
The AND operator displays a record if all the conditions separated by AND are
TRUE.
The OR operator displays a record if any of the conditions separated by OR is
TRUE.
AND Syntax
SELECT column1, column2, ...
FROM table_name
WHERE condition1 AND condition2 AND condition3 ...;
OR Syntax
SELECT column1, column2, ...
FROM table_name
WHERE condition1 OR condition2 OR condition3 ...;
NOT Syntax
SELECT column1, column2, ...
FROM table_name
WHERE NOT condition;
16
Demo Database
The table below shows the complete "Customers" table from the Northwind
sample database:
17
7 Blondel père Frédérique 24, place Strasbo 67000 France
et fils Citeaux Kléber urg
AND Example
The following SQL statement selects all fields from "Customers" where country is
"Germany" AND city is "Berlin":
OR Example
The following SQL statement selects all fields from "Customers" where city is
"Berlin" OR "München":
Example
SELECT * FROM Customers
WHERE City='Berlin' OR City='München';
The following SQL statement selects all fields from "Customers" where country is
"Germany" OR "Spain":
Example
SELECT * FROM Customers
WHERE Country='Germany' OR Country='Spain';
NOT Example
The following SQL statement selects all fields from "Customers" where country is
NOT "Germany":
Example
SELECT * FROM Customers
WHERE NOT Country='Germany';
19
Combining AND, OR and NOT
You can also combine the AND, OR and NOT operators.
The following SQL statement selects all fields from "Customers" where country is
"Germany" AND city must be "Berlin" OR "München" (use parenthesis to form
complex expressions):
Example
SELECT * FROM Customers
WHERE Country='Germany' AND (City='Berlin' OR City='München');
Example
SELECT * FROM Customers
WHERE NOT Country='Germany' AND NOT Country='USA';
The ORDER BY keyword sorts the records in ascending order by default. To sort the
records in descending order, use the DESC keyword.
ORDER BY Syntax
SELECT column1, column2, ...
FROM table_name
ORDER BY column1, column2, ... ASC|DESC;
Demo Database
Below is a selection from the "Customers" table in the Northwind sample
database:
20
CustomerID CustomerName ContactName Address City PostalCode Country
4 Around the Horn Thomas Hardy 120 Hanover Sq. London WA1 1DP UK
ORDER BY Example
The following SQL statement selects all customers from the "Customers" table,
sorted by the "Country" column:
Example
SELECT * FROM Customers
ORDER BY Country;
Example
SELECT * FROM Customers
ORDER BY Country DESC;
21
The SQL BETWEEN Operator
The BETWEEN operator selects values within a given range. The values can be
numbers, text, or dates.
The BETWEEN operator is inclusive: begin and end values are included.
BETWEEN Syntax
SELECT column_name(s)
FROM table_name
WHERE column_name BETWEEN value1 AND value2;
Demo Database
Below is a selection from the "Products" table in the Northwind sample database:
2 Chang 1 1 24 - 12 oz bottles 19
BETWEEN Example
The following SQL statement selects all products with a price between 10 and 20:
22
Example
SELECT * FROM Products
WHERE Price BETWEEN 10 AND 20;
Example
SELECT * FROM Products
WHERE Price NOT BETWEEN 10 AND 20;
Example
SELECT * FROM Products
WHERE Price BETWEEN 10 AND 20
AND CategoryID NOT IN (1,2,3);
Example
SELECT * FROM Products
WHERE ProductName BETWEEN 'Carnarvon Tigers' AND 'Mozzarella di Giovanni'
ORDER BY ProductName;
23
Example
SELECT * FROM Products
WHERE ProductName NOT BETWEEN 'Carnarvon Tigers' AND 'Mozzarella di
Giovanni'
ORDER BY ProductName;
Example
SELECT * FROM Orders
WHERE OrderDate BETWEEN #07/01/1996# AND #07/31/1996#;
OR:
Example
SELECT * FROM Orders
WHERE OrderDate BETWEEN '1996-07-01' AND '1996-07-31';
There are two wildcards often used in conjunction with the LIKE operator:
Note: MS Access uses an asterisk (*) instead of the percent sign (%), and a
question mark (?) instead of the underscore (_).
The percent sign and the underscore can also be used in combinations!
24
LIKE Syntax
SELECT column1, column2, ...
FROM table_name
WHERE columnN LIKE pattern;
Tip: You can also combine any number of conditions using AND or OR operators.
Here are some examples showing different LIKE operators with '%' and '_'
wildcards:
WHERE CustomerName LIKE 'a%' Finds any values that start with "a"
WHERE CustomerName LIKE '%a' Finds any values that end with "a"
WHERE CustomerName LIKE Finds any values that have "or" in any position
'%or%'
WHERE CustomerName LIKE Finds any values that have "r" in the second position
'_r%'
WHERE CustomerName LIKE Finds any values that start with "a" and are at least 2 chara
'a_%' length
WHERE CustomerName LIKE Finds any values that start with "a" and are at least 3 chara
'a__%' length
25
The following SQL statement selects all customers with a CustomerName starting
with "a":
Example
SELECT * FROM Customers
WHERE CustomerName LIKE 'a%';
The following SQL statement selects all customers with a CustomerName ending
with "a":
Example
SELECT * FROM Customers
WHERE CustomerName LIKE '%a';
The following SQL statement selects all customers with a CustomerName that
have "or" in any position:
Example
SELECT * FROM Customers
WHERE CustomerName LIKE '%or%';
The following SQL statement selects all customers with a CustomerName that
have "r" in the second position:
Example
SELECT * FROM Customers
WHERE CustomerName LIKE '_r%';
The following SQL statement selects all customers with a CustomerName that
starts with "a" and are at least 3 characters in length:
Example
SELECT * FROM Customers
WHERE CustomerName LIKE 'a__%';
The following SQL statement selects all customers with a ContactName that starts
with "a" and ends with "o": ALTER TABLE Persons
DROP CHECK CHK_PersonAge;
26
Example
SELECT * FROM Customers
WHERE ContactName LIKE 'a%o';
The following SQL statement selects all customers with a CustomerName that
does NOT start with "a":
Example
SELECT * FROM Customers
WHERE CustomerName NOT LIKE 'a%';
If you define a CHECK constraint on a column it will allow 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.
MySQL:
MySQL:
28
WEEK -4
AIM
COUNT() Syntax
SELECT COUNT(column_name)
FROM table_name
WHERE condition;
AVG() Syntax
SELECT AVG(column_name)
FROM table_name
WHERE condition;
SUM() Syntax
SELECT SUM(column_name)
FROM table_name
WHERE condition;
29
Demo Database
Below is a selection from the "Products" table in the Northwind sample database:
2 Chang 1 1 24 - 12 oz bottles 19
COUNT() Example
The following SQL statement finds the number of products:
Example
SELECT COUNT(ProductID)
FROM Products;
30
AVG() Example
The following SQL statement finds the average price of all products:
Example
SELECT AVG(Price)
FROM Products;
Demo Database
Below is a selection from the "OrderDetails" table in the Northwind sample
database:
1 10248 11 12
2 10248 42 10
3 10248 72 5
4 10249 14 9
5 10249 51 40
31
SUM() Example
The following SQL statement finds the sum of the "Quantity" fields in the
"OrderDetails" table:
Example
SELECT SUM(Quantity)
FROM OrderDetails;
The MAX() function returns the largest value of the selected column.
MIN() Syntax
SELECT MIN(column_name)
FROM table_name
WHERE condition;
MAX() Syntax
SELECT MAX(column_name)
FROM table_name
WHERE condition;
Demo Database
Below is a selection from the "Products" table in the Northwind sample database:
32
2 Chang 1 1 24 - 12 oz bottles
MIN() Example
The following SQL statement finds the price of the cheapest product:
Example
SELECT MIN(Price) AS SmallestPrice
FROM Products;
MAX() Example
The following SQL statement finds the price of the most expensive product:
Example
SELECT MAX(Price) AS LargestPrice
FROM Products;
33
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.
GROUP BY Syntax
SELECT column_name(s)
FROM table_name
WHERE condition
GROUP BY column_name(s)
ORDER BY column_name(s);
Demo Database
Below is a selection from the "Customers" table in the Northwind sample
database:
4 Around the Horn Thomas Hardy 120 Hanover Sq. London WA1 1DP
34
SQL GROUP BY Examples
The following SQL statement lists the number of customers in each country:
The following SQL statement lists the number of customers in each country,
sorted high to low:
Example
SELECT COUNT(CustomerID), Country
FROM Customers
GROUP BY Country
ORDER BY COUNT(CustomerID) DESC;
Demo Database
Below is a selection from the "Orders" table in the Northwind sample database:
10248 90 5 1996-07-04 3
10249 81 6 1996-07-05 1
10250 34 4 1996-07-08 2
35
ShipperID ShipperName
1 Speedy Express
2 United Package
3 Federal Shipping
Example
SELECT Shippers.ShipperName, COUNT(Orders.OrderID) AS NumberOfOrders FROM
Orders
LEFT JOIN Shippers ON Orders.ShipperID = Shippers.ShipperID
GROUP BY ShipperName;
HAVING Syntax
SELECT column_name(s)
FROM table_name
WHERE condition
GROUP BY column_name(s)
HAVING condition
ORDER BY column_name(s);
36
Demo Database
Below is a selection from the "Customers" table in the Northwind sample
database:
4 Around the Horn Thomas Hardy 120 Hanover Sq. London WA1 1DP
37
Example
SELECT COUNT(CustomerID), Country
FROM Customers
GROUP BY Country
HAVING COUNT(CustomerID) > 5;
The following SQL statement lists the number of customers in each country,
sorted high to low (Only include countries with more than 5 customers):
Example
SELECT COUNT(CustomerID), Country
FROM Customers
GROUP BY Country
HAVING COUNT(CustomerID) > 5
ORDER BY COUNT(CustomerID) DESC;
Example
SELECT Employees.LastName, COUNT(Orders.OrderID) AS NumberOfOrders
FROM (Orders
INNER JOIN Employees ON Orders.EmployeeID = Employees.EmployeeID)
GROUP BY LastName
HAVING COUNT(Orders.OrderID) > 10;
The following SQL statement lists if the employees "Davolio" or "Fuller" have
registered more than 25 orders:
Example
SELECT Employees.LastName, COUNT(Orders.OrderID) AS NumberOfOrders
FROM Orders
INNER JOIN Employees ON Orders.EmployeeID = Employees.EmployeeID
WHERE LastName = 'Davolio' OR LastName = 'Fuller'
GROUP BY LastName
HAVING COUNT(Orders.OrderID) > 25;
38
Test
WEEK -5
AIM
Nested Queries
Practicing Nested Queries using
UNION,
INTERSECT,
CONSTRAINTS
IN
Program:
Every SELECT statement within UNION must have the same number of
columns
The columns must also have similar data types
The columns in every SELECT statement must also be in the same order
UNION Syntax
SELECT column_name(s) FROM table1
UNION
SELECT column_name(s) FROM table2;
39
SELECT column_name(s) FROM table1
UNION ALL
SELECT column_name(s) FROM table2;
Note: The column names in the result-set are usually equal to the column names
in the first SELECT statement.
Demo Database
In this tutorial we will use the well-known Northwind sample database.
40
2 New Orleans Cajun Delights Shelley Burke P.O. Box 78934 New Orleans 70117
3 Grandma Kelly's Homestead Regina Murphy 707 Oxford Rd. Ann Arbor 48104
Note: If some customers or suppliers have the same city, each city will only be
listed once, because UNION selects only distinct values. Use UNION ALL to also select
duplicate values!
Example
SELECT City FROM Customers
UNION ALL
SELECT City FROM Suppliers
ORDER BY City;
41
SQL UNION With WHERE
The following SQL statement returns the German cities (only distinct values) from
both the "Customers" and the "Suppliers" table:
Example
SELECT City, Country FROM Customers
WHERE Country='Germany'
UNION
SELECT City, Country FROM Suppliers
WHERE Country='Germany'
ORDER BY City;
Example
SELECT City, Country FROM Customers
WHERE Country='Germany'
UNION ALL
SELECT City, Country FROM Suppliers
WHERE Country='Germany'
ORDER BY City;
Example
SELECT 'Customer' AS Type, ContactName, City, Country
FROM Customers
UNION
42
SELECT 'Supplier', ContactName, City, Country
FROM Suppliers;
Notice the "AS Type" above - it is an alias. SQL Aliases are used to give a table or
a column a temporary name. An alias only exists for the duration of the query. So,
here we have created a temporary column named "Type", that list whether the
contact person is a "Customer" or a "Supplier".
Syntax
CREATE TABLE table_name (
column1 datatype constraint,
column2 datatype constraint,
column3 datatype constraint,
....
);
SQL Constraints
SQL constraints are used to specify rules for the data in a table.
Constraints are used to limit the type of data that can go into a table. This ensures
the accuracy and reliability of the data in the table. If there is any violation
between the constraint and the data action, the action is aborted.
Constraints can be column level or table level. Column level constraints apply to a
column, and table level constraints apply to the whole table.
IN Syntax
SELECT column_name(s)
FROM table_name
WHERE column_name IN (value1, value2, ...);
or:
SELECT column_name(s)
FROM table_name
WHERE column_name IN (SELECT STATEMENT);
Demo Database
The table below shows the complete "Customers" table from the Northwind
sample database:
Ana Trujillo Emparedados y Ana Trujillo Avda. de la Constitución México 05021 Mexico
helados 2222 D.F.
44
Antonio Moreno Taquería Antonio Moreno Mataderos 2312 México 05023 Mexico
D.F.
Around the Horn Thomas Hardy 120 Hanover Sq. London WA1 1DP UK
IN Operator Examples
The following SQL statement selects all customers that are located in "Germany",
"France" or "UK":
The following SQL statement selects all customers that are NOT located in
"Germany", "France" or "UK":
Example
SELECT * FROM Customers
WHERE Country NOT IN ('Germany', 'France', 'UK');
The following SQL statement selects all customers that are from the same
countries as the suppliers:
Example
SELECT * FROM Customers
WHERE Country IN (SELECT Country FROM Suppliers);
45
WEEK -6
AIM
Program:
The EXISTS operator returns TRUE if the subquery returns one or more records.
EXISTS Syntax
SELECT column_name(s)
FROM table_name
WHERE EXISTS
(SELECT column_name FROM table_name WHERE condition);
Demo Database
Below is a selection from the "Products" table in the Northwind sample database:
2 Chang 1 1 24 - 12 oz bottles
46
3 Aniseed Syrup 1 2 12 - 550 ml bottles
2 New Orleans Cajun Delights Shelley Burke P.O. Box 78934 New Orleans 70117
3 Grandma Kelly's Homestead Regina Murphy 707 Oxford Rd. Ann Arbor 48104
Example
SELECT SupplierName
FROM Suppliers
47
WHERE EXISTS (SELECT ProductName FROM Products WHERE Products.SupplierID =
Suppliers.supplierID AND Price < 20);
The following SQL statement returns TRUE and lists the suppliers with a product
price equal to 22:
Example
SELECT SupplierName
FROM Suppliers
WHERE EXISTS (SELECT ProductName FROM Products WHERE Products.SupplierID =
Suppliers.supplierID AND Price = 22);
ANY means that the condition will be true if the operation is true for any of the
values in the range.
ANY Syntax
SELECT column_name(s)
FROM table_name
WHERE column_name operator ANY
(SELECT column_name
FROM table_name
WHERE condition);
Note: The operator must be a standard comparison operator (=, <>, !=, >, >=,
<, or <=).
48
The SQL ALL Operator
The ALL operator:
ALL means that the condition will be true only if the operation is true for all values
in the range.
Note: The operator must be a standard comparison operator (=, <>, !=, >, >=,
<, or <=).
Demo Database
Below is a selection from the "Products" table in the Northwind sample
database:
49
2 Chang 1 1 24 - 12 oz bottles
1 10248 11 12
2 10248 42 10
50
3 10248 72 5
4 10249 14 9
5 10249 51 40
6 10250 41 10
7 10250 51 35
8 10250 65 15
9 10251 22 6
10 10251 57 15
Example
SELECT ProductName
FROM Products
WHERE ProductID = ANY
(SELECT ProductID
51
FROM OrderDetails
WHERE Quantity = 10);
The following SQL statement lists the ProductName if it finds ANY records in the
OrderDetails table has Quantity larger than 99 (this will return TRUE because the
Quantity column has some values larger than 99):
Example
SELECT ProductName
FROM Products
WHERE ProductID = ANY
(SELECT ProductID
FROM OrderDetails
WHERE Quantity > 99);
The following SQL statement lists the ProductName if it finds ANY records in the
OrderDetails table has Quantity larger than 1000 (this will return FALSE because
the Quantity column has no values larger than 1000):
Example
SELECT ProductName
FROM Products
WHERE ProductID = ANY
(SELECT ProductID
FROM OrderDetails
WHERE Quantity > 1000);
52
WEEK -7
AIM
Join Queries
Practicing Join Queries using
Inner join
Outer join
Equi join
Natural join
Program:
SQL JOIN
A JOIN clause is used to combine rows from two or more tables, based on a related
column between them.
10308 2 1996-09-18
10309 37 1996-09-19
10310 77 1996-09-20
53
2 Ana Trujillo Emparedados y helados Ana Trujillo Mexico
Notice that the "CustomerID" column in the "Orders" table refers to the
"CustomerID" in the "Customers" table. The relationship between the two tables
above is the "CustomerID" column.
Then, we can create the following SQL statement (that contains an INNER JOIN),
that selects records that have matching values in both tables:
Example
SELECT Orders.OrderID, Customers.CustomerName, Orders.OrderDate
FROM Orders
INNER JOIN Customers ON Orders.CustomerID=Customers.CustomerID;
54
10278 Berglunds snabbköp 8/12/199
(INNER) JOIN: Returns records that have matching values in both tables
LEFT (OUTER) JOIN: Returns all records from the left table, and the matched
records from the right table
RIGHT (OUTER) JOIN: Returns all records from the right table, and the
matched records from the left table
FULL (OUTER) JOIN: Returns all records when there is a match in either left
or right table
10308 2 7 1996-09-18 3
10309 37 3 1996-09-19 1
10310 77 8 1996-09-20 2
56
2 Ana Trujillo Emparedados y Ana Trujillo Avda. de la Constitución México 05021
helados 2222 D.F.
Example
SELECT Orders.OrderID, Customers.CustomerName
FROM Orders
INNER JOIN Customers ON Orders.CustomerID = Customers.CustomerID;
Note: The INNER JOIN keyword selects all rows from both tables as long as there
is a match between the columns. If there are records in the "Orders" table that do
not have matches in "Customers", these orders will not be shown!
Example
SELECT Orders.OrderID, Customers.CustomerName, Shippers.ShipperName
FROM ((Orders
INNER JOIN Customers ON Orders.CustomerID = Customers.CustomerID)
INNER JOIN Shippers ON Orders.ShipperID = Shippers.ShipperID);
Demo Database
In this tutorial we will use the well-known Northwind sample database.
58
3 Antonio Moreno Taquería Antonio Mataderos 2312 México 05023
Moreno D.F.
10308 2 7 1996-09-18 3
10309 37 3 1996-09-19 1
10310 77 8 1996-09-20 2
Example
SELECT Customers.CustomerName, Orders.OrderID
FROM Customers
LEFT JOIN Orders ON Customers.CustomerID = Orders.CustomerID
ORDER BY Customers.CustomerName;
Note: The LEFT JOIN keyword returns all records from the left table (Customers),
even if there are no matches in the right table (Orders).
Demo Database
In this tutorial we will use the well-known Northwind sample database.
10308 2 7 1996-09-18 3
10309 37 3 1996-09-19 1
10310 77 8 1996-09-20 2
60
And a selection from the "Employees" table:
Example
SELECT Orders.OrderID, Employees.LastName, Employees.FirstName
FROM Orders
RIGHT JOIN Employees ON Orders.EmployeeID = Employees.EmployeeID
ORDER BY Orders.OrderID;
Note: The RIGHT JOIN keyword returns all records from the right table
(Employees), even if there are no matches in the left table (Orders).
Tip: FULL OUTER JOIN and FULL JOIN are the same.
61
FULL OUTER JOIN Syntax
SELECT column_name(s)
FROM table1
FULL OUTER JOIN table2
ON table1.column_name = table2.column_name
WHERE condition;
Note: FULL OUTER JOIN can potentially return very large result-sets!
Demo Database
In this tutorial we will use the well-known Northwind sample database.
62
Moreno D.F.
10308 2 7 1996-09-18 3
10309 37 3 1996-09-19 1
10310 77 8 1996-09-20 2
CustomerName OrderID
Null 10309
Null 10310
63
Alfreds Futterkiste Null
Note: The FULL OUTER JOIN keyword returns all matching records from both tables
whether the other table matches or not. So, if there are rows in "Customers" that
do not have matches in "Orders", or if there are rows in "Orders" that do not have
matches in "Customers", those rows will be listed as well.
Demo Database
In this tutorial we will use the well-known Northwind sample database.
64
1 Alfreds Futterkiste Maria Anders Obere Str. 57 Berlin 12209
Example
SELECT A.CustomerName AS CustomerName1,
B.CustomerName AS CustomerName2, A.City
FROM Customers A, Customers B
WHERE A.CustomerID <> B.CustomerID
AND A.City = B.City
ORDER BY A.City;
65
WEEK -8
AIM
Triggers
Practicing on Triggers - creation of trigger, Insertion using trigger, Deletion using trigger, Updating using trigger.
Program:
One of the most used scenarios for triggers is to maintain a log of changes in a given
table. In such case, there is no point on having three different triggers, each one firing on
INSERT, UPDATE and DELETE operations. Fortunately we have the chance to use one
single trigger for all of those operations. The only drawback is that you have to add logic to
know what event fired the trigger. With a bit of ingenuity and using the INSERTED and
DELETED pseudo tables we can know the type of operation that fired the trigger by
comparing the number of rows of each pseudo table.
To give you an example, suppose the INSERTED pseudo table contains rows and the
DELETED pseudo table is empty then we know that the event that fired the trigger was an
INSERT statement. In opposition, if the DELETED pseudo table has rows and the
INSERTED pseudo table is empty then the statement that fired the trigger was a
DELETE. But if both INSERTED and DELETED have rows then the statement that fired
the trigger was an UPDATE.
Now on the code section below you will see a simple trigger that has the logic to
determine which statement was responsible for firing the trigger and prints the statement
type.
UPDATE dbo.NestingTest
SET Test = 1
WHERE NestingTestID = 1;
Types of Triggers
SQL Server has three types of triggers:
DML Triggers allow us to execute code in response to data modification. In other words,
they allow us to run additional code in response of the execution of an insert, update or
delete statement.
DDL Triggers give us the possibility to execute code in response of changes in the
structure of a database, like dropping or creating a table; or a server event like when
someone logs in. DDL Triggers can be split into two different types according to where
they are scoped.
Logon Triggers are a particular case of Server Scoped DDL triggers that fire in response
to the LOGON event that's raised when a user's session is being established.
Additional Information
How to View Triggers in SQL Server Management Studio.
DML Triggers
This type of trigger is the most known and used by developers. As you may already
know, DML stands for Data Manipulation Language and refers to the SQL
instructions that changes data. Those instructions are INSERT, UPDATE and
DELETE. Basically, DML triggers can be defined as pieces of code written mostly
in Transact SQL language whose execution is not performed manually by the user
and instead is run automatically in response to DML events.
DML Triggers are associated to a table or view and to any of the DML events
(INSERT, UPDATE and DELETE). Something to remark is that a trigger can only
be associated with one single table or view, but can be associated to more than
one DML event. For instance, you could have a trigger that is associated with a
table that fires in response to INSERT and UPDATE events, we will see this further
on in the tutorial.
67
To create a trigger we need to use the CREATE TRIGGER statement.
In this code section you will see the basic CREATE TRIGGER syntax.
CREATE TRIGGER trigger_name
ON { Table name or view name }
{ FOR | AFTER | INSTEAD OF }
{ [INSERT], [UPDATE] , [DELETE] }
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,
FOR | AFTER | INSTEAD OF delete or update occurs. INSTEAD 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.
68
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.
SELECT * FROM dbo.Employees
GO
INSERT INTO dbo.Employees ( EmployeeName , EmployeeAddress ,MonthSalary )
VALUES ( 'Paul Martinez' , '22 Street 4217', 4000)
GO
SELECT * FROM dbo.Employees
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.
69
WEEK -9
AIM
Procedures
Procedures- Creation of Stored Procedures, Execution of Procedure, and Modification of Procedure
Program:
SQL Server builds an execution plan when the stored procedure is called the first time
and stores them in the cache memory. The plan is reused by SQL Server in subsequent
executions of the stored procedure, allowing it to run quickly and efficiently.
o Reduced Traffic: A stored procedure reduces network traffic between the application
and the database server, resulting in increased performance. It is because instead of
sending several SQL statements, the application only needs to send the name of the
stored procedure and its parameters.
o Stronger Security: The procedure is always secure because it manages which processes
and activities we can perform. It removes the need for permissions to be granted at the
database object level and simplifies the security layers.
o Reusable: Stored procedures are reusable. It reduces code inconsistency, prevents
unnecessary rewrites of the same code, and makes the code transparent to all
applications or users.
o Easy Maintenance: The procedures are easier to maintain without restarting or
deploying the application.
o Improved Performance: Stored Procedure increases the application performance. Once
we create the stored procedures and compile them the first time, it creates an execution
70
plan reused for subsequent executions. The procedure is usually processed quicker
because the query processor does not have to create a new plan.
o Types of Stored Procedures
o SQL Server categorizes the stored procedures mainly in two types:
o T-SQL Stored Procedures: Transact-SQL procedures are one of the most popular types
of SQL Server procedures. It takes parameters and returns them. These procedures
handle INSERT, UPDATE, and DELETE statements with or without parameters and output
row data.
o CLR Stored Procedures: The SQL Server procedures are a group of SQL commands, and
the CLR indicates the common language runtime. CLR stored procedures are made up of
the CLR and a stored procedure, which is written in a CLR-based language like VB.NET or
C#. CLR procedures are .Net objects that run in the SQL Server database's memory.
Parameter Explanations
The stored procedure syntax has the following parameters:
1. EXEC procedure_name;
2. Or,
3. EXECUTE procedure_name;
If we are using the SSMS, we need to use the below steps to execute stored procedures:
72
1. Navigate to the Programmability -> Stored Procedures.
2. Next, select the Stored Procedure menu and expand it. You will see the available stored
procedures.
3. Right-click on the stored procedure you want to execute and choose
the Execute Stored Procedure
4. The Execute Procedure window will appear. If the procedure has any parameters, we
must assign/pass them before clicking OK to execute it. If no parameters are defined,
click OK to run the procedure.
We will take a student table to demonstrate the stored procedure examples. This table
has the following data:
The below example uses the CREATE PROCEDURE SQL statement for creating a stored
procedure that displays the student's list in the increasing order of a salary from the
STUDENT table in the selected database:
73
In this syntax, the studentList is the name of the stored procedure, and the AS keyword
distinguishes the stored procedure's heading and body. The BEGIN and END keywords
that accompany a single statement in a stored procedure are optional. However, it's a
good idea to include them to make the code more understandable.
When we run this statement, and everything is correct, the following message will
appear: "Commands completed successfully." It indicates that the stored procedure
was successfully compiled and saved to the database system.
1. EXEC studentList;
If we are using the SSMS, use the following steps for creating the stored
procedure:
74
Step 2: Right-click on the Stored Procedures folder to open the menu and then select
the New -> Stored Procedure option as follows:
Step 3: When we select the New Stored Procedure option, we will get the new query
window containing the default Stored Procedure Template. Here, we can add the
procedure name, parameters (if any), and the SQL query we want to use.
Step 2: Expand the Stored Procedures folder, right-click on the stored procedure that
you want to modify, and then select the Modify option as follows:
75
Step 3: Once we click the Modify option, we will get a new query window with an
auto-generated ALTER PROCEDURE code. Here we can make changes as per our needs.
76
Let's run the procedure to check whether we have successfully updated
the studentList procedure or not. Using the EXECUTE statement, we will get the below
output where we can see that our stored procedure is successfully modified.
The best way for listing all user-defined stored procedures in a database is to use
the ROUTINES information schema view as below:
OR,
1. SELECT *
2. FROM db_name.INFORMATION_SCHEMA.ROUTINES
3. WHERE ROUTINE_TYPE = 'PROCEDURE'
Another way to return a list of stored procedures is to query the sys.objects system
catalog view.
1. SELECT
2. SCHEMA_NAME(schema_id) AS [Schema],
3. name
4. FROM sys.objects
5. WHERE type = 'P';
77
How to delete/drop stored procedures in SQL Server?
We can delete the stored procedure in SQL Server permanently. SQL Server removes the
stored procedure in two ways:
Step 2: Expand the Stored Procedures folder, right-click on the stored procedure that
you want to remove, and then select the Delete option as follows:
78
Step 3: Once we click the Delete option, we will get a Delete Object window. We can
check the dependencies by clicking on the Show Dependencies button and then click
OK to remove the stored procedure.
NOTE: It's a good idea to use IF OBJECT ID ('procedure name', 'P') IS NOT NULL to see if
the stored procedure exists in the database.
If we want to execute this stored procedure, we need to pass the value for
the @States parameter. We can pass the parameter value in any of the following ways:
80
Output Parameters in Stored Procedure
SQL Server enables us to provide many output parameters in a stored procedure. These
output parameters can be of any valid data type, such as integer, date, or character. We
can use the below syntax to create an output parameter in the stored procedure:
Let us understand how to use Output Parameters in a stored procedure with the help of
an example. The following statement will create a procedure called countStudent, in
which we will declare an integer type variable called @StudentCount and use
the OUTPUT keyword. The procedure uses the COUNT function to find the number of
students in the STUDENT table, and then the value is assigned to the output parameter.
Now, we will execute the stored procedure. Here, we need to pass the output
parameter @StudentaCouns as follows:
81
We will get the following output:
Local Temporary Stored Procedures: We can create this type of procedure by using
the # as prefix and accessed only in the session in which they were created. When the
connection is closed, this process is immediately terminated.
Global Temporary Stored Procedure: We can create this type of procedure by using
the ## as a prefix and accessed from any sessions. When the connection that was used
to create the procedure is closed, this procedure is automatically terminated.
82
WEEK -10
AIM
Cursors
Cursors- Declaring Cursor, Opening Cursor, Fetching the data, closing the cursor.
Program:
A cursor is a pointer to this context area. PL/SQL controls the context area through a
cursor. A cursor holds the rows (one or more) returned by a SQL statement. The set of
rows the cursor holds is referred to as the active set.
You can name a cursor so that it could be referred to in a program to fetch and process
the rows returned by the SQL statement, one at a time. There are two types of cursors −
Implicit cursors
Explicit cursors
Implicit Cursors
Implicit cursors are automatically created by Oracle whenever an SQL statement is
executed, when there is no explicit cursor for the statement. Programmers cannot control
the implicit cursors and the information in it.
Whenever a DML statement (INSERT, UPDATE and DELETE) is issued, an implicit
cursor is associated with this statement. For INSERT operations, the cursor holds the
data that needs to be inserted. For UPDATE and DELETE operations, the cursor
identifies the rows that would be affected.
In PL/SQL, you can refer to the most recent implicit cursor as the SQL cursor, which
always has attributes such as %FOUND, %ISOPEN, %NOTFOUND,
and %ROWCOUNT. The SQL cursor has additional
attributes, %BULK_ROWCOUNT and %BULK_EXCEPTIONS, designed for use with
the FORALL statement. The following table provides the description of the most used
attributes −
%FOUND
1 Returns TRUE if an INSERT, UPDATE, or DELETE statement affected one
or more rows or a SELECT INTO statement returned one or more rows.
Otherwise, it returns FALSE.
%NOTFOUND
2
The logical opposite of %FOUND. It returns TRUE if an INSERT, UPDATE,
or DELETE statement affected no rows, or a SELECT INTO statement
83
returned no rows. Otherwise, it returns FALSE.
%ISOPEN
3
Always returns FALSE for implicit cursors, because Oracle closes the SQL
cursor automatically after executing its associated SQL statement.
%ROWCOUNT
4
Returns the number of rows affected by an INSERT, UPDATE, or DELETE
statement, or returned by a SELECT INTO statement.
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
+----+----------+-----+-----------+----------+
The following program will update the table and increase the salary of each customer by
500 and use the SQL%ROWCOUNT attribute to determine the number of rows affected
−
DECLARE
total_rows number(2);
BEGIN
UPDATE customers
SET salary = salary + 500;
IF sql%notfound THEN
dbms_output.put_line('no customers selected');
ELSIF sql%found THEN
total_rows := sql%rowcount;
dbms_output.put_line( total_rows || ' customers selected ');
END IF;
END;
/
84
When the above code is executed at the SQL prompt, it produces the following result −
6 customers selected
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2500.00 |
| 2 | Khilan | 25 | Delhi | 2000.00 |
| 3 | kaushik | 23 | Kota | 2500.00 |
| 4 | Chaitali | 25 | Mumbai | 7000.00 |
| 5 | Hardik | 27 | Bhopal | 9000.00 |
| 6 | Komal | 22 | MP | 5000.00 |
+----+----------+-----+-----------+----------+
Explicit Cursors
Explicit cursors are programmer-defined cursors for gaining more control over
the context area. An explicit cursor should be defined in the declaration section of the
PL/SQL Block. It is created on a SELECT Statement which returns more than one row.
The syntax for creating an explicit cursor is −
CURSOR cursor_name IS select_statement;
Working with an explicit cursor includes the following steps −
85
Opening the cursor allocates the memory for the cursor and makes it ready for fetching
the rows returned by the SQL statement into it. For example, we will open the above
defined cursor as follows −
OPEN c_customers;
86
WEEK -11
AIM
PL/SQL Part 1
Practice PL/SQL –
block structure,
variables,
data types,
Program:
In PL/SQL, the code is not executed in single line format, but it is always
executed by grouping the code into a single element called Blocks. In this
tutorial, you are going to learn about these blocks.
Blocks contain both PL/SQL as well as SQL instruction. All these instruction will
be executed as a whole rather than executing a single instruction at a time.
Block Structure
PL/SQL blocks have a pre-defined structure in which the code is to be grouped.
Below are different sections of PL/SQL blocks.
1. Declaration section
2. Execution section
3. Exception-Handling section
The below picture illustrates the different PL/SQL block and their section order.
87
Declaration Section
This is the first section of the PL/SQL blocks. This section is an optional part.
This is the section in which the declaration of variables, cursors, exceptions,
subprograms, pragma instructions and collections that are needed in the block
will be declared. Below are few more characteristics of this part.
88
Testing Principles Software Testing05:01 Linux File Permissions
Commands with Examples13:29How to use Text tool in Photoshop CC
Execution Section
Execution part is the main and mandatory part which actually executes the
code that is written inside it. Since the PL/SQL expects the executable
statements from this block this cannot be an empty block, i.e., it should have at
least one valid executable code line in it. Below are few more characteristics of
this part.
Exception-Handling Section:
The exception is unavoidable in the program which occurs at run-time and to
handle this Oracle has provided an Exception-handling section in blocks. This
section can also contain PL/SQL statements. This is an optional section of the
PL/SQL blocks.
This is the section where the exception raised in the execution block is
handled.
This section is the last part of the PL/SQL block.
89
Control from this section can never return to the execution block.
This section starts with the keyword „EXCEPTION‟.
This section should always be followed by the keyword „END‟.
DECLARE --optional
<declarations>
BEGIN --mandatory
<executable statements. At least one executable statement is mandatory>
EXCEPTION --optional
<exception handles>
END; --mandatory
/
Note: A block should always be followed by „/‟ which sends the information to
the compiler about the end of the block.
90
Types of PL/SQL block
PL/SQL blocks are of mainly two types.
1. Anonymous blocks
2. Named Blocks
Anonymous blocks:
Anonymous blocks are PL/SQL blocks which do not have any names assigned
to them. They need to be created and used in the same session because they
will not be stored in the server as database objects.
Since they need not store in the database, they need no compilation steps.
They are written and executed directly, and compilation and execution happen
in a single process.
These blocks don‟t have any reference name specified for them.
These blocks start with the keyword „DECLARE‟ or „BEGIN‟.
Since these blocks do not have any reference name, these cannot be
stored for later purpose. They shall be created and executed in the same
session.
They can call the other named blocks, but call to anonymous block is not
possible as it is not having any reference.
It can have nested block in it which can be named or anonymous. It can
also be nested in any blocks.
These blocks can have all three sections of the block, in which execution
section is mandatory, the other two sections are optional.
Named blocks:
Named blocks have a specific and unique name for them. They are stored as
the database objects in the server. Since they are available as database
objects, they can be referred to or used as long as it is present on the server.
The compilation process for named blocks happens separately while creating
them as a database objects.
1. Procedure
2. Function
We will learn more about these named blocks in “Procedure” and “Function”
topics in later tutorial.
PL/SQL Variables
A variable is a meaningful name which facilitates a programmer to store data
temporarily during the execution of code. It helps you to manipulate data in PL/SQL
programs. It is nothing except a name given to a storage area. Each variable in the
PL/SQL has a specific data type which defines the size and layout of the variable's
memory.
A variable should not exceed 30 characters. Its letter optionally followed by more letters,
dollar signs, numerals, underscore etc.
1. It needs to declare the variable first in the declaration section of a PL/SQL block before
using it.
2. By default, variable names are not case sensitive. A reserved PL/SQL keyword cannot be
used as a variable name.
Here, variable_name is a valid identifier in PL/SQL and datatype must be valid PL/SQL
data type. A data type with size, scale or precision limit is called a constrained
declaration. The constrained declaration needs less memory than unconstrained
declaration.
Example:
92
Radius Number := 5;
Date_of_birth date;
Declaration Restrictions:
In PL/SQL while declaring the variable some restrictions hold.
o Forward references are not allowed i.e. you must declare a constant or variable before
referencing it in another statement even if it is a declarative statement.
val number := Total - 200;
Total number := 1000;
The first declaration is illegal because the TOTAL variable must be declared before using
it in an assignment expression.
o Variables belonging to the same datatype cannot be declared in the same statement.
N1, N2, N3 Number;
It is an illegal declaration.
1. counter binary_integer := 0;
2. greetings varchar2(20) DEFAULT 'Hello JavaTpoint';
You can also specify NOT NULL constraint to avoid NULL value. If you specify the NOT
NULL constraint, you must assign an initial value for that variable.
You must have a good programming skill to initialize variable properly otherwise,
sometimes program would produce unexpected result.
1. DECLARE
2. a integer := 30;
3. b integer := 40;
4. c integer;
5. f real;
6. BEGIN
7. c := a + b;
8. dbms_output.put_line('Value of c: ' || c);
9. f := 100.0/3.0;
10. dbms_output.put_line('Value of f: ' || f);
11. END;
Value of c: 70
Value of f: 33.333333333333333333
o Local Variable: Local variables are the inner block variables which are not accessible to
outer blocks.
94
o Global Variable: Global variables are declared in outermost block.
1. DECLARE
2. -- Global variables
3. num1 number := 95;
4. num2 number := 85;
5. BEGIN
6. dbms_output.put_line('Outer Variable num1: ' || num1);
7. dbms_output.put_line('Outer Variable num2: ' || num2);
8. DECLARE
9. -- Local variables
10. num1 number := 195;
11. num2 number := 185;
12. BEGIN
13. dbms_output.put_line('Inner Variable num1: ' || num1);
14. dbms_output.put_line('Inner Variable num2: ' || num2);
15. END;
16. END;
17. /
Variable Attributes:
When you declare a PL/SQL variable to hold the column values, it must be of correct
data types and precision, otherwise error will occur on execution. Rather than hard
coding the data type and precision of a variable. PL/SQL provides the facility to declare a
variable without having to specify a particular data type using %TYPE and %ROWTYPE
attributes. These two attributes allow us to specify a variable and have that variable data
type be defined by a table/view column or a PL/SQL package variable.
95
A % sign servers as the attribute indicator. This method of declaring variables has an
advantage as the user is not concerned with writing and maintaining code.
o %TYPE:
The %TYPE attribute is used to declare variables according to the already declared
variable or database column. It is used when you are declaring an individual variable, not
a record. The data type and precision of the variable declared using %TYPE attribute is
the same as that of the column that is referred from a given table. This is particularly
useful when declaring variables that will hold database values. When using the %TYPE
keyword, the name of the columns and the table to which the variable will correspond
must be known to the user. These are then prefixed with the variable name. If some
previously declared variable is referred then prefix that variable name to the %TYPE
attribute.
1. <var_name> <tab_name>.<column_name>%TYPE;
Consider a declaration.
1. This declaration will declare a variable SALARY that has the same data type as column S
DECLARE
2. SALARY EMP.SAL % TYPE;
3. ECODE EMP.empno % TYPE;
4. BEGIN
5. Ecode :=&Ecode;
6. Select SAL into SALARY from EMP where EMPNO = ECODE;
7. dbms_output.put_line('Salary of ' || ECODE || 'is = || salary');
8. END;
o %ROWTYPE:
96
The %ROWTYPE attribute is used to declare a record type that represents a row in a
table. The record can store an entire row or some specific data selected from the table. A
column in a row and corresponding fields in a record have the same name and data
types.
1. <var_name> <tab_name>.ROW%TYPE;
This declaration will declare a record named EMPLOYEE having fields with the same
name and data types as that of columns in the EMP table. You can access the elements
of EMPLOYEE record as
EMPLOYEE.SAL := 10000;
EMPLOYEE.ENAME := ‘KIRAN’;
Example:
1. DECLARE
2. EMPLOYEE EMP. % ROW TYPE;
3. BEGIN
4. EMPLOYEE.EMPNO := 2092;
5. 5 EMPLOYEE.ENAME := 'Sanju';
6. Insert into EMP where (EMPNO, ENAME) Values (employee.empno, employee.ename);
7. dbms_output.put_line('Row Inserted');
8. END;
Row Inserted
PL/SQL procedure successfully completed.
Advantages:
97
o If you don’t know the data type at the time of declaration. The data type assigned
to the associated variables will be determined dynamically at run time.
o If the data type of the variable you are referencing changes the %TYPE or
%ROWTYPE variable changes at run time without having to rewrite variable
declarations. For example: if the ENAME column of an EMP table is changed from
a VARCHAR2(10) to VRACHAR2(15) then you don’t need to modify the PL/SQL
code.
98
WEEK -12
AIM
PL/SQL Part 2
Practice PL/SQL –
operators,
control structures;
aseca
Program:
we will discuss operators in PL/SQL. An operator is a symbol that tells the compiler to
perform specific mathematical or logical manipulation. PL/SQL language is rich in built-in
operators and provides the following types of operators −
Arithmetic operators
Relational operators
Comparison operators
Logical operators
String operators
Here, we will understand the arithmetic, relational, comparison and logical operators one
by one. The String operators will be discussed in a later chapter − PL/SQL - Strings.
Arithmetic Operators
Following table shows all the arithmetic operators supported by PL/SQL. Let us
assume variable A holds 10 and variable B holds 5, then −
Show Examples
99
** Exponentiation operator, raises one operand to the A ** B will give
power of other 100000
Relational Operators
Relational operators compare two expressions or values and return a Boolean result.
Following table shows all the relational operators supported by PL/SQL. Let us
assume variable A holds 10 and variable B holds 20, then −
Show Examples
!=
Checks if the values of two operands are equal or not, if (A != B) is
<> values are not equal then condition becomes true. true.
~=
Checks if the value of left operand is greater than the value (A > B) is not
>
of right operand, if yes then condition becomes true. true.
Checks if the value of left operand is less than the value of (A < B) is
<
right operand, if yes then condition becomes true. true.
Comparison Operators
Comparison operators are used for comparing one expression to another. The result is
always either TRUE, FALSE or NULL.
Show Examples
100
Operator Description Example
If x = 10 then, x between 5
The BETWEEN operator tests whether a
and 20 returns true, x
value lies in a specified range. x
BETWEEN between 5 and 10 returns
BETWEEN a AND b means that x >= a
true, but x between 11 and 20
and x <= b.
returns false.
Logical Operators
Following table shows the Logical operators supported by PL/SQL. All these operators
work on Boolean operands and produce Boolean results. Let us assume variable
A holds true and variable B holds false, then −
Show Examples
Called the logical AND operator. If both the operands are (A and B) is
and
true then condition becomes true. false.
101
Called the logical NOT Operator. Used to reverse the not (A and B)
not logical state of its operand. If a condition is true then is true.
Logical NOT operator will make it false.
Operator Operation
** exponentiation
+, - identity, negation
*, / multiplication, division
comparison
AND conjunction
OR inclusion
102
Control Structures in PL/SQL
Procedural computer programs use the basic control structures.
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.
Want to know more about SQL? Read this extensive SQL Tutorial and enhance
your knowledge!
103
Using the IF-THEN Statement
Submit
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
104
than multiple Boolean expressions. A selector is an expression whose value is used to
select one of several alternatives.
Example: Using the CASE-WHEN Statement
DECLARE
grade CHAR(1);
BEGIN
grade := 'B';
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;
END;
/
The simplest form of LOOP statement is the basic loop, which encloses a sequence of
statements between the keywords LOOP and END LOOP, as follows:
LOOP
sequence_of_statements
END LOOP;
105
With each iteration of the loop, the sequence of statements is executed, then control
resumes at the top of the loop. You use an EXIT statement to stop looping and prevent an
infinite loop. You can place one or more EXIT statements anywhere inside a loop, but not
outside a loop. There are two forms of EXIT statements: EXIT and
EXIT-WHEN.
The EXIT statement forces a loop to complete unconditionally. When an EXIT statement
is encountered, the loop completes immediately and control passes to the next
statement.
The EXIT-WHEN statement lets a loop complete conditionally. When the EXIT statement
is encountered, the condition in the WHEN clause is evaluated. If the condition is true, the
loop completes and control passes to the next statement after the loop.
Like PL/SQL blocks, loops can be labeled. The optional label, an undeclared identifier
enclosed by double angle brackets, must appear at the beginning of the LOOP statement.
The label name can also appear at the end of the LOOP statement. When you nest
labeled loops, use ending label names to improve readability.
The WHILE-LOOP statement executes the statements in the loop body as long as a
condition is true:
WHILE condition LOOP
sequence_of_statements
106
END LOOP;
Check out the top PL/SQL Interview Questions to learn what is expected from
PL/SQL professionals!
The NULL statement does nothing and passes control to the next statement. Some
languages refer to such instruction as a no-op (no operation).
Example: Using the NULL Statement to Show No Action
DECLARE
v_job_id VARCHAR2(10);
v_emp_id NUMBER(6) := 110;
108
BEGIN
SELECT job_id INTO v_job_id FROM employees WHERE employee_id =
v_emp_id;
IF v_job_id = 'SA_REP' THEN
UPDATE employees SET commission_pct = commission_pct * 1.2;
ELSE
NULL; -- do nothing if not a sales representative
END IF;
END;
/
109