0% found this document useful (0 votes)
26 views

DBMS LAB MANUAL 2025 (1)

The document is a lab manual for a Database Management Systems course, detailing weekly topics and exercises for students in the II B.Tech II Semester. It covers various SQL commands including DDL, DML, and PL/SQL, along with practical examples for creating, altering, and dropping tables, as well as executing queries and managing data. Additionally, it includes case studies related to college management, enterprise organization, and library management systems.

Uploaded by

ayeshakausar2014
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
26 views

DBMS LAB MANUAL 2025 (1)

The document is a lab manual for a Database Management Systems course, detailing weekly topics and exercises for students in the II B.Tech II Semester. It covers various SQL commands including DDL, DML, and PL/SQL, along with practical examples for creating, altering, and dropping tables, as well as executing queries and managing data. Additionally, it includes case studies related to college management, enterprise organization, and library management systems.

Uploaded by

ayeshakausar2014
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 109

A

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)

HOLY MARY INSTITUTE OF TECHNOLOGY & SCIENCE


(UGC AUTONOMOUS)
Bogaram (V), Keesara (M), Medchal (D), T.S - 501301

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,

Apply constraint on aggregation using


 GROUP BY,
 HAVING,VIEWS Create, Modify and Drop
5 WEEK -5
Nested Queries
Practicing Nested Queries using
 UNION,
 INTERSECT,
 CONSTRAINTS
 IN
6 WEEK -6
Co- Related Nested Queries
Practicing Co – Related Nested Queries using
 EXISTS
 ,NOT EXISTS. ANY, ALL
7 WEEK -7
Join Queries
Practicing Join Queries using
 Inner join
 Outer join
2
 Equi join
 Natural join
8 WEEK -8
Triggers
Practicing on Triggers - creation of trigger, Insertion using trigger, Deletion using trigger,
Updating using trigger.

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

Case study 1: College Management


Case study 2: An Enterprise/Organization
Case study 3: Library Management system
Case study 4: Sailors and shipment system

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:

Syntax of SELECT DML command

1. SELECT column_Name_1, column_Name_2, ….., column_Name_N FROM Name_of_table;

Here, column_Name_1, column_Name_2, ….., column_Name_N are the names of


those columns whose data we want to retrieve from the table.

If we want to retrieve the data from all the columns of the table, we have to use the
following SELECT command:

1. SELECT * FROM table_name;

Examples of SELECT Command


Example 1: This example shows all the values of every column from the table.

1. SELECT * FROM Student;

This SQL statement displays the following values of the student table:

Student_ID Student_Name Student_Marks

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.

1. SELECT Emp_Id, Emp_Salary FROM Employee;

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.

Let's take the following Student table:

Student_ID Student_Name Student_Marks

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:

1. SELECT * FROM Student WHERE Stu_Marks = 80;

The above SQL query shows the following table in result:

Student_ID Student_Name Student_Marks

BCA1001 Abhay 80

BCA1003 Bheem 80

BCA1005 Sumit 80

INSERT DML Command


INSERT is another most important data manipulation command in Structured Query
Language, which allows users to insert data in database tables.

Syntax of INSERT Command

1. INSERT INTO TABLE_NAME ( column_Name1 , column_Name2 , column_Name3 , .... column_Na


meN ) VALUES (value_1, value_2, value_3, .... value_N ) ;

Examples of INSERT Command


Example 1: This example describes how to insert the record in the database table.

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);

UPDATE DML Command


UPDATE is another most important data manipulation command in Structured Query
Language, which allows users to update or modify the existing data in database tables.

Syntax of UPDATE Command

1. UPDATE Table_name SET [column_name1= value_1, ….., column_nameN = value_N] WHERE CO


NDITION;

Here, 'UPDATE', 'SET', and 'WHERE' are the SQL keywords, and 'Table_name' is the name
of the table whose values you want to update.

Examples of the UPDATE command


Example 1: This example describes how to update the value of a single field.

Let's take a Product table consisting of the following records:

Product_Id Product_Name Product_Price Product_Quantity

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:

1. UPDATE Product SET Product_Price = 80 WHERE Product_Id = 'P102' ;

Example 2: This example describes how to update the value of multiple fields of
the database table.

Let's take a Student table consisting of the following records:

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 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;

DELETE DML Command


13
DELETE is a DML command which allows SQL users to remove single or multiple existing
records from the database tables.

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.

Syntax of DELETE Command

1. DELETE FROM Table_Name WHERE condition;

Examples of DELETE Command


Example 1: This example describes how to delete a single record from the table.

Let's take a Product table consisting of the following records:

Product_Id Product_Name Product_Price Product_Quantity

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:

1. DELETE FROM Product WHERE Product_Id = 'P202' ;

Example 2: This example describes how to delete the multiple records or rows
from the database table.

Let's take a Student table consisting of the following records:

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:

1. DELETE FROM Student WHERE Stu_Marks > 70 ;

15
WEEK -3
AIM:

Selection Queries
Practicing Select command using following operations
 AND, OR
 ORDER BY
 BETWEEN
 LIKE
 Apply CHECK constraint
PROGRAM:

The SQL AND, OR and NOT Operators


The WHERE clause can be combined with AND, OR, and NOT operators.

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.

The NOT operator displays a record if the condition(s) is NOT 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:

Custome CustomerN ContactN Address City PostalC Country


rID ame ame ode

1 Alfreds Maria Obere Str. Berlin 12209 German


Futterkiste Anders 57 y

2 Ana Trujillo Ana Trujillo Avda. de la México 05021 Mexico


Emparedado Constituci D.F.
s y helados ón 2222

3 Antonio Antonio Mataderos México 05023 Mexico


Moreno Moreno 2312 D.F.
Taquería

4 Around the Thomas 120 London WA1 1DP UK


Horn Hardy Hanover
Sq.

5 Berglunds Christina Berguvsvä Luleå S-958 22 Sweden


snabbköp Berglund gen 8

6 Blauer See Hanna Forsterstr. Mannhei 68306 German


Delikatessen Moos 57 m y

17
7 Blondel père Frédérique 24, place Strasbo 67000 France
et fils Citeaux Kléber urg

8 Bólido Martín C/ Araquil, Madrid 28023 Spain


Comidas Sommer 67
preparadas

9 Bon app' Laurence 12, rue Marseill 13008 France


Lebihans des e
Bouchers

10 Bottom-Dolla Elizabeth 23 Tsawass T2F 8M4 Canada


r Marketse Lincoln Tsawassen en
Blvd.

11 B's Victoria Fauntleroy London EC2 5NT UK


Beverages Ashworth Circus

12 Cactus Patricio Cerrito Buenos 1010 Argentin


Comidas Simpson 333 Aires a
para llevar

13 Centro Francisco Sierras de México 05022 Mexico


comercial Chang Granada D.F.
Moctezuma 9993

14 Chop-suey Yang Wang Hauptstr. Bern 3012 Switzerl


Chinese 29 and

15 Comércio Pedro Av. dos São 05432-0 Brazil


Lusíadas,
18
Mineiro Afonso 23 Paulo 43

AND Example
The following SQL statement selects all fields from "Customers" where country is
"Germany" AND city is "Berlin":

ExampleGet your own SQL Server


SELECT * FROM Customers
WHERE Country='Germany' AND City='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 SQL ORDER BY Keyword


The ORDER BY keyword is used to sort the result-set in ascending or descending
order.

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

1 Alfreds Futterkiste Maria Anders Obere Str. 57 Berlin 12209 Germany

2 Ana Trujillo Ana Trujillo Avda. de la México 05021 Mexico


Emparedados y Constitución 2222 D.F.
helados

3 Antonio Moreno Antonio Mataderos 2312 México 05023 Mexico


Taquería Moreno D.F.

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;

ORDER BY DESC Example


The following SQL statement selects all customers from the "Customers" table,
sorted DESCENDING by the "Country" column:

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:

ProductID ProductName SupplierID CategoryID Unit Price

1 Chais 1 1 10 boxes x 20 bags 18

2 Chang 1 1 24 - 12 oz bottles 19

3 Aniseed Syrup 1 2 12 - 550 ml bottles 10

4 Chef Anton's Cajun Seasoning 1 2 48 - 6 oz jars 22

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;

NOT BETWEEN Example


To display the products outside the range of the previous example, use NOT
BETWEEN:

Example
SELECT * FROM Products
WHERE Price NOT BETWEEN 10 AND 20;

BETWEEN with IN Example


The following SQL statement selects all products with a price between 10 and 20.
In addition; do not show products with a CategoryID of 1,2, or 3:

Example
SELECT * FROM Products
WHERE Price BETWEEN 10 AND 20
AND CategoryID NOT IN (1,2,3);

BETWEEN Text Values Example


The following SQL statement selects all products with a ProductName between
Carnarvon Tigers and Mozzarella di Giovanni:

Example
SELECT * FROM Products
WHERE ProductName BETWEEN 'Carnarvon Tigers' AND 'Mozzarella di Giovanni'
ORDER BY ProductName;

NOT BETWEEN Text Values Example


The following SQL statement selects all products with a ProductName not between
Carnarvon Tigers and Mozzarella di Giovanni:

23
Example
SELECT * FROM Products
WHERE ProductName NOT BETWEEN 'Carnarvon Tigers' AND 'Mozzarella di
Giovanni'
ORDER BY ProductName;

BETWEEN Dates Example


The following SQL statement selects all orders with an OrderDate between
'01-July-1996' and '31-July-1996':

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';

The SQL LIKE Operator


The LIKE operator is used in a WHERE clause to search for a specified pattern in a
column.

There are two wildcards often used in conjunction with the LIKE operator:

 The percent sign (%) represents zero, one, or multiple characters


 The underscore sign (_) represents one, single character

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:

LIKE Operator Description

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

SQL LIKE Examples

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%';

SQL CHECK Constraint


The CHECK constraint is used to limit the value range that can be placed in a
column.

If you define a CHECK constraint on a 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.

SQL CHECK on CREATE TABLE


The following SQL creates a CHECK constraint on the "Age" column when the
"Persons" table is created. The CHECK constraint ensures that the age of a person
must be 18, or older:

MySQL:

CREATE TABLE Persons (


ID int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int,
CHECK (Age>=18)
);

SQL Server / Oracle / MS Access:

CREATE TABLE Persons (


ID int NOT NULL,
LastName varchar(255) NOT NULL,
27
FirstName varchar(255),
Age int CHECK (Age>=18)
);

To allow naming of a CHECK constraint, and for defining a CHECK constraint on


multiple columns, use the following SQL syntax:

MySQL / SQL Server / Oracle / MS Access:

CREATE TABLE Persons (


ID int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int,
City varchar(255),
CONSTRAINT CHK_Person CHECK (Age>=18 AND City='Sandnes')
);

SQL CHECK on ALTER TABLE


To create a CHECK constraint on the "Age" column when the table is already
created, use the following SQL:

MySQL / SQL Server / Oracle / MS Access:

ALTER TABLE Persons


ADD CHECK (Age>=18);

To allow naming of a CHECK constraint, and for defining a CHECK constraint on


multiple columns, use the following SQL syntax:

MySQL / SQL Server / Oracle / MS Access:

ALTER TABLE Persons


ADD CONSTRAINT CHK_PersonAge CHECK (Age>=18 AND City='Sandnes'

DROP a CHECK Constraint


To drop a CHECK constraint, use the following SQL:

SQL Server / Oracle / MS Access:

ALTER TABLE Persons


DROP CONSTRAINT CHK_PersonAge;

MySQL:

28
WEEK -4
AIM

Aggregate Functions and Views


Practice Queries using following functions
 COUNT,
 SUM,
 AVG,
 MAX,
 MIN,

Apply constraint on aggregation using


 GROUP BY,
 HAVING, VIEWS Create, Modify and Drop
PROGRAM:

The SQL COUNT(), AVG() and SUM()


Functions
The COUNT() function returns the number of rows that matches a specified
criterion.

COUNT() Syntax
SELECT COUNT(column_name)
FROM table_name
WHERE condition;

The AVG() function returns the average value of a numeric column.

AVG() Syntax
SELECT AVG(column_name)
FROM table_name
WHERE condition;

The SUM() function returns the total sum of a numeric column.

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:

ProductID ProductName SupplierID CategoryID Unit Price

1 Chais 1 1 10 boxes x 20 bags 18

2 Chang 1 1 24 - 12 oz bottles 19

3 Aniseed Syrup 1 2 12 - 550 ml bottles 10

4 Chef Anton's Cajun Seasoning 2 2 48 - 6 oz jars 22

5 Chef Anton's Gumbo Mix 2 2 36 boxes 21.35

COUNT() Example
The following SQL statement finds the number of products:

Example
SELECT COUNT(ProductID)
FROM Products;

Note: NULL values are not counted.

30
AVG() Example
The following SQL statement finds the average price of all products:

Example
SELECT AVG(Price)
FROM Products;

Note: NULL values are ignored.

Demo Database
Below is a selection from the "OrderDetails" table in the Northwind sample
database:

OrderDetailID OrderID ProductID Quantity

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;

Note: NULL values are ignored.

The SQL MIN() and MAX() Functions


The MIN() function returns the smallest value of the selected column.

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:

ProductID ProductName SupplierID CategoryID Unit

1 Chais 1 1 10 boxes x 20 bags

32
2 Chang 1 1 24 - 12 oz bottles

3 Aniseed Syrup 1 2 12 - 550 ml bottles

4 Chef Anton's Cajun Seasoning 2 2 48 - 6 oz jars

5 Chef Anton's Gumbo Mix 2 2 36 boxes

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;

The SQL GROUP BY Statement


The GROUP BY statement groups rows that have the same values into summary
rows, like "find the number of customers in each country".

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:

CustomerID CustomerName ContactName Address City PostalCode

1 Alfreds Futterkiste Maria Anders Obere Str. 57 Berlin 12209

2 Ana Trujillo Emparedados y Ana Trujillo Avda. de la Constitución México 05021


helados 2222 D.F.

3 Antonio Moreno Taquería Antonio Mataderos 2312 México 05023


Moreno D.F.

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:

ExampleGet your own SQL Server


SELECT COUNT(CustomerID), Country
FROM Customers
GROUP BY 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:

OrderID CustomerID EmployeeID OrderDate ShipperID

10248 90 5 1996-07-04 3

10249 81 6 1996-07-05 1

10250 34 4 1996-07-08 2

And a selection from the "Shippers" table:

35
ShipperID ShipperName

1 Speedy Express

2 United Package

3 Federal Shipping

GROUP BY With JOIN Example


The following SQL statement lists the number of orders sent by each shipper:

Example
SELECT Shippers.ShipperName, COUNT(Orders.OrderID) AS NumberOfOrders FROM
Orders
LEFT JOIN Shippers ON Orders.ShipperID = Shippers.ShipperID
GROUP BY ShipperName;

The SQL HAVING Clause


The HAVING clause was added to SQL because the WHERE keyword cannot be used
with aggregate functions.

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:

CustomerID CustomerName ContactName Address City PostalCode

1 Alfreds Futterkiste Maria Anders Obere Str. 57 Berlin 12209

2 Ana Trujillo Emparedados y Ana Trujillo Avda. de la Constitución México 05021


helados 2222 D.F.

3 Antonio Moreno Taquería Antonio Moreno Mataderos 2312 México 05023


D.F.

4 Around the Horn Thomas Hardy 120 Hanover Sq. London WA1 1DP

5 Berglunds snabbköp Christina Berguvsvägen 8 Luleå S-958 22


Berglund

SQL HAVING Examples


The following SQL statement lists the number of customers in each country. Only
include countries with more than 5 customers:

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;

More HAVING Examples


The following SQL statement lists the employees that have registered more than
10 orders:

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:

The SQL UNION Operator


The UNION operator is used to combine the result-set of two or
more SELECT statements.

 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;

UNION ALL Syntax


The UNION operator selects only distinct values by default. To allow duplicate
values, use UNION ALL:

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.

Below is a selection from the "Customers" table:

CustomerID CustomerName ContactName Address City PostalCode

1 Alfreds Futterkiste Maria Anders Obere Str. 57 Berlin 12209

2 Ana Trujillo Emparedados y Ana Trujillo Avda. de la Constitución México 05021


helados 2222 D.F.

3 Antonio Moreno Taquería Antonio Mataderos 2312 México 05023


Moreno D.F.

And a selection from the "Suppliers" table:

SupplierID SupplierName ContactName Address City PostalCode

1 Exotic Liquid Charlotte Cooper 49 Gilbert St. London EC1 4SD

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

SQL UNION Example


The following SQL statement returns the cities (only distinct values) from both the
"Customers" and the "Suppliers" table:

ExampleGet your own SQL Server


SELECT City FROM Customers
UNION
SELECT City FROM Suppliers
ORDER BY City;

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!

SQL UNION ALL Example


The following SQL statement returns the cities (duplicate values also) from both
the "Customers" and the "Suppliers" table:

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;

SQL UNION ALL With WHERE


The following SQL statement returns the German cities (duplicate values also)
from both the "Customers" and the "Suppliers" table:

Example
SELECT City, Country FROM Customers
WHERE Country='Germany'
UNION ALL
SELECT City, Country FROM Suppliers
WHERE Country='Germany'
ORDER BY City;

Another UNION Example


The following SQL statement lists all customers and suppliers:

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".

SQL Create Constraints


Constraints can be specified when the table is created with the CREATE
TABLE statement, or after the table is created with the ALTER TABLE statement.

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.

The following constraints are commonly used in SQL:

 NOT NULL - Ensures that a column cannot have a NULL value


 UNIQUE - Ensures that all values in a column are different
 PRIMARY KEY - A combination of a NOT NULL and UNIQUE. Uniquely identifies
each row in a table
 FOREIGN KEY - Prevents actions that would destroy links between tables
 CHECK - Ensures that the values in a column satisfies a specific condition
 DEFAULT - Sets a default value for a column if no value is specified
43
 CREATE INDEX - Used to create and retrieve data from the database very
quickly

The SQL IN Operator


The IN operator allows you to specify multiple values in a WHERE clause.

The IN operator is a shorthand for multiple OR conditions.

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:

tomerID CustomerName ContactName Address City PostalCode Country

Alfreds Futterkiste Maria Anders Obere Str. 57 Berlin 12209 Germany

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

Berglunds snabbköp Christina Berguvsvägen 8 Luleå S-958 22 Sw


Berglund

IN Operator Examples
The following SQL statement selects all customers that are located in "Germany",
"France" or "UK":

ExampleGet your own SQL Server


SELECT * FROM Customers
WHERE Country IN ('Germany', 'France', '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

Co- Related Nested Queries


Practicing Co – Related Nested Queries using
 EXISTS
 ,NOT EXISTS. ANY, ALL

Program:

The SQL EXISTS Operator


The EXISTS operator is used to test for the existence of any record in a subquery.

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:

ProductID ProductName SupplierID CategoryID Unit

1 Chais 1 1 10 boxes x 20 bags

2 Chang 1 1 24 - 12 oz bottles

46
3 Aniseed Syrup 1 2 12 - 550 ml bottles

4 Chef Anton's Cajun Seasoning 2 2 48 - 6 oz jars

5 Chef Anton's Gumbo Mix 2 2 36 boxes

And a selection from the "Suppliers" table:

SupplierID SupplierName ContactName Address City PostalCode

1 Exotic Liquid Charlotte Cooper 49 Gilbert St. London EC1 4SD

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

4 Tokyo Traders Yoshi Nagase 9-8 Sekimai Musashino-shi Tokyo 100

SQL EXISTS Examples


The following SQL statement returns TRUE and lists the suppliers with a product
price less than 20:

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);

The SQL ANY and ALL Operators


The ANY and ALL operators allow you to perform a comparison between a single
column value and a range of other values.

The SQL ANY Operator


The ANY operator:

 returns a boolean value as a result


 returns TRUE if ANY of the subquery values meet the condition

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:

 returns a boolean value as a result


 returns TRUE if ALL of the subquery values meet the condition
 is used with SELECT, WHERE and HAVING statements

ALL means that the condition will be true only if the operation is true for all values
in the range.

ALL Syntax With SELECT


SELECT ALL column_name(s)
FROM table_name
WHERE condition;

ALL Syntax With WHERE or HAVING


SELECT column_name(s)
FROM table_name
WHERE column_name operator ALL
(SELECT column_name
FROM table_name
WHERE condition);

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:

ProductID ProductName SupplierID CategoryID Unit

1 Chais 1 1 10 boxes x 20 bags

49
2 Chang 1 1 24 - 12 oz bottles

3 Aniseed Syrup 1 2 12 - 550 ml bottles

4 Chef Anton's Cajun Seasoning 2 2 48 - 6 oz jars

5 Chef Anton's Gumbo Mix 2 2 36 boxes

6 Grandma's Boysenberry Spread 3 2 12 - 8 oz jars

7 Uncle Bob's Organic Dried Pears 3 7 12 - 1 lb pkgs.

8 Northwoods Cranberry Sauce 3 2 12 - 12 oz jars

9 Mishi Kobe Niku 4 6 18 - 500 g pkgs.

And a selection from the "OrderDetails" table:

OrderDetailID OrderID ProductID Quantity

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

SQL ANY Examples


The following SQL statement lists the ProductName if it finds ANY records in the
OrderDetails table has Quantity equal to 10 (this will return TRUE because the
Quantity column has some values of 10):

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.

Let's look at a selection from the "Orders" table:

OrderID CustomerID OrderDate

10308 2 1996-09-18

10309 37 1996-09-19

10310 77 1996-09-20

Then, look at a selection from the "Customers" table:

CustomerID CustomerName ContactName Countr

1 Alfreds Futterkiste Maria Anders Germa

53
2 Ana Trujillo Emparedados y helados Ana Trujillo Mexico

3 Antonio Moreno Taquería Antonio Moreno Mexico

Notice that the "CustomerID" column in the "Orders" table refers to the
"CustomerID" in the "Customers" table. The relationship between the two tables
above is the "CustomerID" column.

Then, we can create the following SQL statement (that contains an INNER JOIN),
that selects records that have matching values in both tables:

Example
SELECT Orders.OrderID, Customers.CustomerName, Orders.OrderDate
FROM Orders
INNER JOIN Customers ON Orders.CustomerID=Customers.CustomerID;

and it will produce something like this:

OrderID CustomerName OrderDa

10308 Ana Trujillo Emparedados y helados 9/18/199

10365 Antonio Moreno Taquería 11/27/19

10383 Around the Horn 12/16/19

10355 Around the Horn 11/15/19

54
10278 Berglunds snabbköp 8/12/199

Different Types of SQL JOINs


Here are the different types of the JOINs in SQL:

 (INNER) JOIN: Returns records that have matching values in both tables
 LEFT (OUTER) JOIN: Returns all records from the left table, and the matched
records from the right table
 RIGHT (OUTER) JOIN: Returns all records from the right table, and the
matched records from the left table
 FULL (OUTER) JOIN: Returns all records when there is a match in either left
or right table

SQL INNER JOIN Keyword


The INNER JOIN keyword selects records that have matching values in both tables.

INNER JOIN Syntax


SELECT column_name(s)
FROM table1
INNER JOIN table2
ON table1.column_name = table2.column_name;
55
Demo Database
In this tutorial we will use the well-known Northwind sample database.

Below is a selection from the "Orders" table:

OrderID CustomerID EmployeeID OrderDate ShipperID

10308 2 7 1996-09-18 3

10309 37 3 1996-09-19 1

10310 77 8 1996-09-20 2

And a selection from the "Customers" table:

CustomerID CustomerName ContactName Address City PostalCode

1 Alfreds Futterkiste Maria Anders Obere Str. 57 Berlin 12209

56
2 Ana Trujillo Emparedados y Ana Trujillo Avda. de la Constitución México 05021
helados 2222 D.F.

3 Antonio Moreno Taquería Antonio Mataderos 2312 México 05023


Moreno D.F.

SQL INNER JOIN Example


The following SQL statement selects all orders with customer information:

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!

JOIN Three Tables


The following SQL statement selects all orders with customer and shipper
information:

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);

SQL LEFT JOIN Keyword


57
The LEFT JOIN keyword returns all records from the left table (table1), and the
matching records from the right table (table2). The result is 0 records from the
right side, if there is no match.

LEFT JOIN Syntax


SELECT column_name(s)
FROM table1
LEFT JOIN table2
ON table1.column_name = table2.column_name;

Note: In some databases LEFT JOIN is called LEFT OUTER JOIN.

Demo Database
In this tutorial we will use the well-known Northwind sample database.

Below is a selection from the "Customers" table:

CustomerID CustomerName ContactName Address City PostalCode

1 Alfreds Futterkiste Maria Anders Obere Str. 57 Berlin 12209

2 Ana Trujillo Emparedados y Ana Trujillo Avda. de la Constitución México 05021


helados 2222 D.F.

58
3 Antonio Moreno Taquería Antonio Mataderos 2312 México 05023
Moreno D.F.

And a selection from the "Orders" table:

OrderID CustomerID EmployeeID OrderDate ShipperID

10308 2 7 1996-09-18 3

10309 37 3 1996-09-19 1

10310 77 8 1996-09-20 2

SQL LEFT JOIN Example


The following SQL statement will select all customers, and any orders they might
have:

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).

SQL RIGHT JOIN Keyword


59
The RIGHT JOIN keyword returns all records from the right table (table2), and the
matching records from the left table (table1). The result is 0 records from the left
side, if there is no match.

RIGHT JOIN Syntax


SELECT column_name(s)
FROM table1
RIGHT JOIN table2
ON table1.column_name = table2.column_name;

Note: In some databases RIGHT JOIN is called RIGHT OUTER JOIN.

Demo Database
In this tutorial we will use the well-known Northwind sample database.

Below is a selection from the "Orders" table:

OrderID CustomerID EmployeeID OrderDate ShipperID

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:

EmployeeID LastName FirstName BirthDate Photo

1 Davolio Nancy 12/8/1968 EmpID1.pic

2 Fuller Andrew 2/19/1952 EmpID2.pic

3 Leverling Janet 8/30/1963 EmpID3.pic

SQL RIGHT JOIN Example


The following SQL statement will return all employees, and any orders they might
have placed:

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).

SQL FULL OUTER JOIN Keyword


The FULL OUTER JOIN keyword returns all records when there is a match in left
(table1) or right (table2) table records.

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.

Below is a selection from the "Customers" table:

CustomerID CustomerName ContactName Address City PostalCode

1 Alfreds Futterkiste Maria Anders Obere Str. 57 Berlin 12209

2 Ana Trujillo Emparedados y Ana Trujillo Avda. de la Constitución México 05021


helados 2222 D.F.

3 Antonio Moreno Taquería Antonio Mataderos 2312 México 05023

62
Moreno D.F.

And a selection from the "Orders" table:

OrderID CustomerID EmployeeID OrderDate ShipperID

10308 2 7 1996-09-18 3

10309 37 3 1996-09-19 1

10310 77 8 1996-09-20 2

SQL FULL OUTER JOIN Example


The following SQL statement selects all customers, and all orders:

SELECT Customers.CustomerName, Orders.OrderID


FROM Customers
FULL OUTER JOIN Orders ON Customers.CustomerID=Orders.CustomerID
ORDER BY Customers.CustomerName;

A selection from the result set may look like this:

CustomerName OrderID

Null 10309

Null 10310

63
Alfreds Futterkiste Null

Ana Trujillo Emparedados y helados 10308

Antonio Moreno Taquería 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.

SQL Self Join


A self join is a regular join, but the table is joined with itself.

Self Join Syntax


SELECT column_name(s)
FROM table1 T1, table1 T2
WHERE condition;

T1 and T2 are different table aliases for the same table.

Demo Database
In this tutorial we will use the well-known Northwind sample database.

Below is a selection from the "Customers" table:

CustomerID CustomerName ContactName Address City PostalCode

64
1 Alfreds Futterkiste Maria Anders Obere Str. 57 Berlin 12209

2 Ana Trujillo Emparedados y Ana Trujillo Avda. de la Constitución México 05021


helados 2222 D.F.

3 Antonio Moreno Taquería Antonio Mataderos 2312 México 05023


Moreno D.F.

SQL Self Join Example


The following SQL statement matches customers that are from the same city:

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.

Let's create a table to use in this example.

CREATE TABLE NestingTest


(
NestingTestID INT IDENTITY(1, 1),
Test INT NULL
);

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.

CREATE OR ALTER TRIGGER TR_IUD_NestingTest ON NestingTest


FOR INSERT, UPDATE, DELETE
AS
DECLARE @Operation VARCHAR(15)

IF EXISTS (SELECT 0 FROM inserted)


BEGIN
IF EXISTS (SELECT 0 FROM deleted)
BEGIN
SELECT @Operation = 'UPDATE'
END ELSE
BEGIN
SELECT @Operation = 'INSERT'
END
END ELSE
BEGIN
SELECT @Operation = 'DELETE'
END
PRINT @Operation
66
To test the trigger we can use the code below.

INSERT INTO dbo.NestingTest


(Test) VALUES (0);

UPDATE dbo.NestingTest
SET Test = 1
WHERE NestingTestID = 1;

DELETE FROM dbo.NestingTest


WHERE NestingTestID = 1;

Types of Triggers
SQL Server has three types of triggers:

 DML (Data Manipulation Language) Triggers


 DDL (Data Definition Language) Triggers
 Logon 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.

 Database Scoped DDL Triggers


 Server Scoped DDL Triggers

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.

 Let's create a sample table, so we can create our first trigger.


 USE [SampleDB]
 GO

 CREATE TABLE Employees(
 EmployeeID INT IDENTITY(1,1) PRIMARY KEY,
 EmployeeName VARCHAR(50) NOT NULL,
 EmployeeAddress VARCHAR(50) NOT NULL,
 MonthSalary NUMERIC(10,2) NOT NULL
 )

 INSERT INTO dbo.Employees
 (
 EmployeeName,
 EmployeeAddress,
 MonthSalary
 )
 VALUES
 ( 'Mark Smith',
 'Ocean Dr 1234',
 10000
 ),
 ( 'Joe Wright',
 'Evergreen 1234',
 10000
 ),
 ( 'John Doe',
 'International Dr 1234',
 10000
 ),
 ( 'Peter Rodriguez',
 '74 Street 1234',
 10000
 );

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:

Stored Procedure in SQL Server


A stored procedure is a group of one or more pre-compiled SQL statements into a
logical unit. It is stored as an object inside the database server. It is a subroutine or a
subprogram in the common computing language that has been created and stored in
the database. Each procedure in SQL Server always contains a name, parameter lists,
and Transact-SQL statements. The SQL Database Server stores the stored procedures
as named objects. We can invoke the procedures by using triggers, other procedures,
and applications such as Java, Python, PHP, etc. It can support almost all relational
database systems.

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.

Features of Stored Procedures in SQL Server


The following are the features of stored procedure in SQL Server:

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:

1. User-defined Stored Procedures


2. System Stored Procedures

User-defined Stored Procedures


Database developers or database administrators build user-defined stored
procedures. These procedures provide one or more SQL statements for selecting,
updating, or removing data from database tables. A stored procedure specified by the
user accepts input parameters and returns output parameters. DDL and DML commands
are used together in a user-defined procedure.

We can further divide this procedure into 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.

System Stored Procedures


The server's administrative tasks depend primarily on system stored procedures. When
SQL Server is installed, it creates system procedures. The system stored procedures
prevent the administrator from querying or modifying the system and database catalog
tables directly. Developers often ignore system stored procedures.

SQL Server Stored Procedures Syntax


The following are the basic syntax to create stored procedures in SQL Server:

1. CREATE PROCEDURE [schema_name].procedure_name


2. @parameter_name data_type,
71
3. ....
4. parameter_name data_type
5. AS
6. BEGIN
7. -- SQL statements
8. -- SELECT, INSERT, UPDATE, or DELETE statement
9. END

Parameter Explanations
The stored procedure syntax has the following parameters:

Schema_name: It is the name of your database or schema. By default, a procedure is


associated with the current database, but we can also create it into another database by
specifying the DB name.

Procedure_Name: It represents the name of your stored procedure that should be


meaningful names so that you can identify them quickly. It cannot be the system
reserved keywords.

Parameter_Name: It represents the number of parameters. It may be zero or more


based upon the user requirements. We must ensure that we used the appropriate data
type. For example, @Name VARCHAR(50).

SET NOCOUNT ON in Stored Procedure


In some cases, we use the SET NOCOUNT ON statement in the stored procedure. This
statement prevents the message that displays the number of rows affected by SQL
queries from being shown. NOCOUNT denotes that the count is turned off. It means
that if SET NOCOUNT ON is set, no message would appear indicating the number of
rows affected.

How to execute/call a stored procedure?


We can use the EXEC command to call/execute stored procedures in SQL Server. The
following syntax illustrates the execution of a stored procedure:

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.

Stored Procedure Simple Example


We can create a stored procedure in SQL Server in two ways:

o Using T-SQL Query


o Using SQL Server Management Studio

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:

1. CREATE PROCEDURE studentList


2. AS
3. BEGIN
4. SELECT name, age, salary
5. FROM STUDENT
6. ORDER BY salary;
7. END;

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.

We can execute this procedure by using the below command:

1. EXEC studentList;

It will return the output as follows:

If we are using the SSMS, use the following steps for creating the stored
procedure:

Step 1: Select the Database -> Programmability -> Stored Procedures.

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.

How to rename stored procedures in SQL Server?


SQL Server does not allow us to change the name of a stored procedure. Because
renaming a stored procedure does not modify the name of the corresponding object in
the sys.sql_modules. Therefore, if we need to change the existing stored procedure,
simply DROP and recreate it with a new name.

o Using T-SQL Query


o Using SQL Server Management Studio

Modify Stored Procedures using SSMS


The following steps help to learn how we can modify or make changes in stored
procedures:

Step 1: Navigate to the Database -> Programmability -> Stored Procedures.

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.

Modify Stored Procedures using T-SQL Query


SQL Server provides an ALTER PROCEDURE statement to make modifications in the
existing stored procedures. If we want to modify the above created stored procedure,
we can write the ALTER PROCEDURE statement as follows:

1. ALTER PROCEDURE [dbo].[studentList]


2. AS
3. BEGIN
4. SET NOCOUNT ON;
5. SELECT name, salary
6. FROM STUDENT
7. ORDER BY salary;
8. END;

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.

How to list all stored procedures in SQL Server?


When we have several procedures, it is very important to list all procedures. Because
sometimes the procedure names are the same in many databases. In that case, this
query is very useful. We can list all stored procedure in the current database as follows:

1. SELECT * FROM sys.procedures;

The best way for listing all user-defined stored procedures in a database is to use
the ROUTINES information schema view as below:

1. SELECT ROUTINE_SCHEMA, ROUTINE_NAME


2. FROM INFORMATION_SCHEMA.ROUTINES
3. WHERE ROUTINE_TYPE = 'PROCEDURE';

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:

o Using T-SQL Query


o Using SQL Server Management Studio

DROP Stored Procedures using SSMS


The following steps help to learn how we can delete stored procedures:

Step 1: Go to the Database -> Programmability -> Stored Procedures.

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.

Delete Stored Procedures using T-SQL Query


SQL Server provides a DROP PROCEDURE statement to remove the existing stored
procedures. We can write the DROP PROCEDURE statement as follows:

1. IF OBJECT_ID ('procedure_name', 'P') IS NOT NULL


2. DROP PROCEDURE procedure_name;

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.

Input Parameters in Stored Procedure


SQL Server allows us to create input parameters stored procedures. This type of stored
procedure can enable us to pass one or more parameters to get the filtered result. Let us
understand it with the help of an example. Consider the following 'customer' table:
79
The below statement creates a stored procedure with an input parameter:

1. CREATE PROCEDURE getEmployeeDetails (@States VARCHAR(50))


2. AS
3. BEGIN
4. SET NOCOUNT ON;
5. SELECT c_name, email, state
6. FROM customer
7. WHERE state = @States
8. END

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:

1. EXEC [dbo].[getEmployeeDetails] 'California';


2.
3. --OR we can write
4.
5. EXEC [dbo].[getEmployeeDetails] @States = 'New York';

We will get the output as below:

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:

1. parameter_name data_type OUTPUT

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.

1. CREATE PROCEDURE countStudent (@StudentCount INT OUTPUT)


2. AS
3. BEGIN
4. SELECT @StudentCount = COUNT(Id)FROM STUDENT;
5. END;

Now, we will execute the stored procedure. Here, we need to pass the output
parameter @StudentaCouns as follows:

1. -- Declare an Int Variable that corresponds to the Output parameter in SP


2. DECLARE @TotalStudents INT
3.
4. -- Don't forget to use the keyword OUTPUT
5. EXEC [dbo].[countStudent] @TotalStudents OUTPUT
6.
7. -- Print the result
8. PRINT @TotalStudents

81
We will get the following output:

Temporary Stored Procedure


We can create temporary procedures in the same way as we can create temporary
tables. The tempdb database is used to create these procedures. We can divide the
temporary procedures into two types:

o Local Temporary Stored Procedures


o Global Temporary Procedures.

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.

Here's an example of how to create a local temporary procedure:

1. CREATE PROCEDURE #Temp


2. AS
3. BEGIN
4. PRINT 'Local temp procedure'
5. END

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.

Here's an example of how to create a global temporary procedure:

1. CREATE PROCEDURE ##TEMP


2. AS
3. BEGIN
4. PRINT 'Global temp procedure'
5. END

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 −

S.No Attribute & Description

%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.

Any SQL cursor attribute will be accessed as sql%attribute_name as shown below in


the example.
Example
We will be using the CUSTOMERS table we had created and used in the previous
chapters.
Select * from customers;

+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
+----+----------+-----+-----------+----------+
The following program 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

PL/SQL procedure successfully completed.


If you check the records in customers table, you will find that the rows have been updated

Select * from customers;

+----+----------+-----+-----------+----------+
| 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 −

 Declaring the cursor for initializing the memory


 Opening the cursor for allocating the memory
 Fetching the cursor for retrieving the data
 Closing the cursor to release the allocated memory

Declaring the Cursor


Declaring the cursor defines the cursor with a name and the associated SELECT
statement. For example −
CURSOR c_customers IS
SELECT id, name, address FROM customers;

Opening the Cursor

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;

Fetching the Cursor


Fetching the cursor involves accessing one row at a time. For example, we will fetch rows
from the above-opened cursor as follows −
FETCH c_customers INTO c_id, c_name, c_addr;

Closing the Cursor


Closing the cursor means releasing the allocated memory. For example, we will close the
above-opened cursor as follows −
CLOSE c_customers;
Example
Following is a complete example to illustrate the concepts of explicit cursors &minua;
DECLARE
c_id customers.id%type;
c_name customers.name%type;
c_addr customers.address%type;
CURSOR c_customers is
SELECT id, name, address FROM customers;
BEGIN
OPEN c_customers;
LOOP
FETCH c_customers into c_id, c_name, c_addr;
EXIT WHEN c_customers%notfound;
dbms_output.put_line(c_id || ' ' || c_name || ' ' || c_addr);
END LOOP;
CLOSE c_customers;
END;
/
When the above code is executed at the SQL prompt, it produces the following result −
1 Ramesh Ahmedabad
2 Khilan Delhi
3 kaushik Kota
4 Chaitali Mumbai
5 Hardik Bhopal
6 Komal MP

PL/SQL procedure successfully completed.

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.

In this tutorial, you will learn:

 What is PL/SQL block?


 Block Structure
 PL/SQL Block Syntax
 Types of PL/SQL block

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.

EXPLORE MORELearn Java Programming with Beginners Tutorial08:32

Linux Tutorial for Beginners: Introduction to Linux


Operating...01:35What is Integration Testing Software Testing
Tutorial03:04What is JVM (Java Virtual Machine) with Architecture
JAVA...02:24How to write a TEST CASE Software Testing Tutorial01:08Seven

88
Testing Principles Software Testing05:01 Linux File Permissions
Commands with Examples13:29How to use Text tool in Photoshop CC

Tutorial08:32 What is NoSQL Database Tutorial02:00 Important


Linux Commands for Beginners Linux Tutorial15:03

 This particular section is optional and can be skipped if no declarations


are needed.
 This should be the first section in a PL/SQL block, if present.
 This section starts with the keyword „DECLARE‟ for triggers and
anonymous block. For other subprograms, this keyword will not be
present. Instead, the part after the subprogram name definition marks the
declaration section.
 This section should always be followed by execution section.

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.

 This can contain both PL/SQL code and SQL code.


 This can contain one or many blocks inside it as a nested block.
 This section starts with the keyword „BEGIN‟.
 This section should be followed either by „END‟ or Exception-Handling
section (if present)

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‟.

The Keyword „END‟ marks the end of PL/SQL block.

PL/SQL Block Syntax


Below is the syntax of the PL/SQL block structure.

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.

Below are few more characteristics of Anonymous blocks.

 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.

Below are few more characteristics of Named blocks.

 These blocks can be called from other blocks.


 The block structure is same as an anonymous block, except it will never
start with the keyword „DECLARE‟. Instead, it will start with the keyword
„CREATE‟ which instruct the compiler to create it as a database object.
91
 These blocks can be nested within other blocks. It can also contain
nested blocks.
 Named blocks are basically of two types:

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.

How to declare variable in PL/SQL


You must declare the PL/SQL variable in the declaration section or in a package as a
global variable. After the declaration, PL/SQL allocates memory for the variable's value
and the storage location is identified by the variable name.

Following is the syntax for declaring variable:

1. variable_name [CONSTANT] datatype [NOT NULL] [:= | DEFAULT initial_value]

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.

Naming rules for PL/SQL variables


The variable in PL/SQL must follow some naming rules like other programming
languages.

o The variable_name should not exceed 30 characters.


o Variable name should not be the same as the table table's column of that block.
o The name of the variable must begin with ASCII letter. The PL/SQL is not case sensitive so
it could be either lowercase or uppercase. For example: v_data and V_DATA refer to the
same variables.
o You should make your variable easy to read and understand, after the first character, it
may be any number, underscore (_) or dollar sign ($).
o NOT NULL is an optional specification on the variable.

Initializing Variables in PL/SQL


Evertime you declare a variable, PL/SQL defines a default value NULL to it. If you want to
initialize a variable with other value than NULL value, you can do so during the
declaration, by using any one of the following methods.

o The DEFAULT keyword


93
o The assignment operator

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.

Example of initilizing variable


Let's take a simple example to explain it well:

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;

After the execution, this will produce the following result:

Value of c: 70
Value of f: 33.333333333333333333

PL/SQL procedure successfully completed.

Variable Scope in PL/SQL:


PL/SQL allows nesting of blocks. A program block can contain another inner block. If you
declare a variable within an inner block, it is not accessible to an outer block. There are
two types of variable scope:

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.

Example of Local and Global variables


Let's take an example to show the usage of Local and Global variables in its simple form:

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. /

After the execution, this will produce the following result:

Outer Variable num1: 95


Outer Variable num2: 85
Inner Variable num1: 195
Inner Variable num2: 185

PL/SQL procedure successfully completed.

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.

Following are the types of Variable Attributes in PL/SQL.

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.

The syntax for declaring a variable with %TYPE is:

1. <var_name> <tab_name>.<column_name>%TYPE;

Where <column_name> is the column defined in the <tab_name>.

Consider a declaration.

SALARY EMP.SAL % TYPE;

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;

After the execution, this will produce the following result:

Enter value for ecode: 7499


Salary of 7499 is = 1600
PL/SQL procedure successfully completed.

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.

The syntax for declaring a variable with %ROWTYPE is:

1. <var_name> <tab_name>.ROW%TYPE;

Where <variable_name> is the variable defined in the <tab_name>.

AL of the EMP table.

EMPLOYEE EMP. % 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;

After the execution, this will produce the following result:

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

Case study 1: College Management


Case study 2: An Enterprise/Organization
Case study 3: Library Management system
Case study 4: Sailors and shipment system

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

Operator Description Example

+ Adds two operands A + B will give 15

- Subtracts second operand from the first A - B will give 5

* Multiplies both operands A * B will give 50

/ Divides numerator by de-numerator A / B will give 2

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

Operator Description Example

Checks if the values of two operands are equal or not, if (A = B) is not


=
yes then condition becomes true. true.

!=
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.

Checks if the value of left operand is greater than or equal (A >= B) is


>= to the value of right operand, if yes then condition becomes not true.
true.

Checks if the value of left operand is less than or equal to (A <= B) is


<= the value of 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

The LIKE operator compares a


If 'Zara Ali' like 'Z% A_i'
character, string, or CLOB value to a
returns a Boolean true,
LIKE pattern and returns TRUE if the value
whereas, 'Nuha Ali' like 'Z%
matches the pattern and FALSE if it does
A_i' returns a Boolean false.
not.

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.

If x = 'm' then, x in ('a', 'b', 'c')


The IN operator tests set membership. x
returns Boolean false but x in
IN IN (set) means that x is equal to any
('m', 'n', 'o') returns Boolean
member of set.
true.

The IS NULL operator returns the


BOOLEAN value TRUE if its operand is
If x = 'm', then 'x is null'
IS NULL NULL or FALSE if it is not NULL.
returns Boolean false.
Comparisons involving NULL values
always yield NULL.

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

Operator Description Examples

Called the logical AND operator. If both the operands are (A and B) is
and
true then condition becomes true. false.

Called the logical OR Operator. If any of the two operands (A or B) is


or
is true then condition becomes true. true.

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.

PL/SQL Operator Precedence


Operator precedence determines the grouping of terms in an expression. This affects
how an expression is evaluated. Certain operators have higher precedence than others;
for example, the multiplication operator has higher precedence than the addition
operator.
For example, x = 7 + 3 * 2; here, x is assigned 13, not 20 because operator * has higher
precedence than +, so it first gets multiplied with 3*2 and then adds into 7.
Here, operators with the highest precedence appear at the top of the table, those with the
lowest appear at the bottom. Within an expression, higher precedence operators will be
evaluated first.
The precedence of operators goes as follows: =, <, >, <=, >=, <>, !=, ~=, ^=, IS NULL,
LIKE, BETWEEN, IN.
Show Examples

Operator Operation

** exponentiation

+, - identity, negation

*, / multiplication, division

+, -, || addition, subtraction, concatenation

comparison

NOT logical negation

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!

Testing Conditions: IF and CASE Statements


The IF statement executes a sequence of statements depending on the value of a
condition. There are three forms of IF statements: IF-THEN, IF-THEN-ELSE, and
IF-THEN-ELSIF.
The CASE statement is a compact way to evaluate a single condition and choose
between many alternative actions. It makes sense to use CASE when there are three or
more alternatives to choose from.

103
 Using the IF-THEN Statement

The simplest form of IF statement associates a condition with a sequence of statements


enclosed by the keywords THEN and END IF (not ENDIF)
The sequence of statements is executed only if the condition is TRUE. If the condition is
FALSE or NULL, the IF statement does nothing. In either case, control passes to the next
statement.
Example: Using a Simple IF-THEN Statement
DECLARE
sales NUMBER(8,2) := 10100;
quota NUMBER(8,2) := 10000;
bonus NUMBER(6,2);
emp_id NUMBER(6) := 120;
BEGIN
IF sales > (quota + 200) THEN
bonus := (sales - quota)/4;
UPDATE employees SET salary = salary + bonus WHERE employee_id =
emp_id;
END IF;
END;
/

Get 100% Hike!


Master Most in Demand Skills Now !

Submit

 Using CASE Statements

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;
/

Controlling Loop Iterations: LOOP and EXIT


Statements
LOOP statements execute a sequence of statements multiple times. There are three
forms of LOOP statements: LOOP, WHILE-LOOP, and FOR-LOOP.

 Using the LOOP Statement

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.

 Using the EXIT Statement

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.

 Using the EXIT-WHEN 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.

 Labeling a PL/SQL 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.

 Using the WHILE-LOOP Statement

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;

Come to Intellipaat’s Community if you have queries!

Using the FOR-LOOP Statement


Simple FOR loops iterate over a specified range of integers. The number of iterations is
known before the loop is entered. A double dot (..) serves as the range operator. The
range is evaluated when the FOR loop is first entered and is never re-evaluated. If the
lower bound equals the higher bound, the loop body is executed once.
Example: Using a Simple FOR LOOP Statement
DECLARE
p NUMBER := 0;
BEGIN
FOR k IN 1..500 LOOP -- calculate pi with 500 terms
p := p + ( ( (-1) ** (k + 1) ) / ((2 * k) - 1) );
END LOOP;
p := 4 * p;
DBMS_OUTPUT.PUT_LINE( 'pi is approximately : ' || p ); -- print result
END;
/

Sequential Control: GOTO and NULL Statements


The GOTO statement is seldom needed. Occasionally, it can simplify logic enough to
warrant its use. The NULL statement can improve readability by making the meaning and
action of conditional statements clear.
Overuse of GOTO statements can result in code that is hard to understand and maintain.
Use GOTO statements sparingly. For example, to branch from a deeply nested structure
to an error-handling routine, raise an exception rather than use a GOTO statement.

 Using the GOTO Statement


107
The GOTO statement branches to a label unconditionally. The label must be unique
within its scope and must precede an executable statement or a PL/SQL block. When
executed, the GOTO statement transfers control to the labeled statement or block. The
labeled statement or block can be down or up in the sequence of statements.
Example: Using a Simple GOTO Statement
DECLARE
p VARCHAR2(30);
n PLS_INTEGER := 37; -- test any integer > 2 for prime
BEGIN
FOR j in 2..ROUND(SQRT(n)) LOOP
IF n MOD j = 0 THEN -- test for prime
p := ' is not a prime number'; -- not a prime number
GOTO print_now;
END IF;
END LOOP;
p := ' is a prime number';
<<print_now>>
DBMS_OUTPUT.PUT_LINE(TO_CHAR(n) || p);
END;
/

Check out the top PL/SQL Interview Questions to learn what is expected from
PL/SQL professionals!

 Using the NULL Statement

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

You might also like