0% found this document useful (0 votes)
37 views65 pages

DBMS List of Practicals AND MANUAL

Uploaded by

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

DBMS List of Practicals AND MANUAL

Uploaded by

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

GOVINDRAO WANJARI COLLEGE OF ENGINEERING

& TECHNOLOGY, NAGPUR


DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

NAME OF LABORATORY: MARTIN LAB

NAME OF SUBJECT – DATABASE SYSTEM

SEMESTER – 5th SEM SUBJECT CODE – BTCOL506

COURSE OUTCOMES
After competition of the course students will be able to:

CO 1
CO 2
CO 3

LIST OF EXPERIMENTS

Sr. No. Name of Experiment COs


1 To study and execute the DDL commands.
2 To study and execute DML command (Data Manipulation
Command)
3 To study and execute Primary key and foreign key concept.

To study and execute aggregate function. (MIN, MAX,


4 SUM, Count &AVG)
5 To perform queries based on Group By, Having By clause.

To study & execute join operation. (Inner join, Left join,


6 Right join , Outer join, Natural join, Equal join, Cartesian
join operation)
7 To study and execute set operation (union, insert, minus)
8 To study and execute views.
9 To study about PL-SQL & execute a PL-SQL simple
program of If-else condition.
10 A) To study and execute PL/SQL procedure.
B) To study and execute PL/SQL stored function.

Dept. CSE[ 3RD YR 2023-2024] Page1


GOVINDRAO WANJARI COLLEGE OF ENGINEERING
& TECHNOLOGY, NAGPUR
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

NAME OF SUBJECT – DATABASE SYSTEM

SEMESTER – 5th SEM

SUBJECT CODE – BTCOL506

INDEX

Sr. No. Name of Practical Page No.


1 To study and execute the DDL commands. 3
2 To study and execute DML command (Data Manipulation Command) 8
3 To study and execute Primary key and foreign key concept. 13
4 To study and execute aggregate function. (MIN, MAX, SUM, Count 17
&AVG)
5 To perform queries based on Group By, Having By clause. 24
6 To study & execute join operation. (Inner join, Left join, Right join , 31
Outer join, Natural join, Equal join, Cartesian join operation)
7 To study and execute set operation (union, insert, minus) 39
8 To study and execute views. 44
9 To study about PL-SQL & execute a PL-SQL simple program of If-else 53
condition.
10 A) To study and execute PL/SQL procedure. 55
B) To study and execute PL/SQL stored function.

Dept. CSE[ 3RD YR 2023-2024] Page2


GOVINDRAO WANJARI COLLEGE OF ENGINEERING
& TECHNOLOGY, NAGPUR
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

PRACTICAL NO: 1

AIM:- To study and execute the DDL commands.

THEORY:- Data Definition Language (DDL) o DDL changes the structure of the table like creating a table,
deleting a table, altering a table, etc. All the command of DDL are auto-committed that means it permanently save
all the changes in the database. Here are some commands that come under

DDL: A)CREATE B)ALTER C) DROP D) TRUNCATE

a. CREATE: It is used to create a new table in the database.


Syntax :-CREATE TABLE TABLE_NAME (COLUMN_NAME DATATYPES[,....]);
Example: CREATE TABLE EMPLOYEE(Name VARCHAR2(20), Email VARCHAR2(100), DOB
DATE);
b. DROP: It is used to delete both the structure and record stored in the table.
Syntax:- DROP TABLE ;
Example DROP TABLE EMPLOYEE;
c. ALTER: It is used to alter the structure of the database. This change could be either to modify the
characteristics of an existing attribute or probably to add a new attribute.
Syntax: To add a new column in the table ALTER TABLE table_name ADD column_name COLUMN-
definition;
To modify existing column in the table: ALTER TABLE MODIFY(COLUMN DEFINITION....);
EXAMPLE
1. ALTER TABLE STU_DETAILS ADD(ADDRESS VARCHAR2(20));
2. ALTER TABLE STU_DETAILS MODIFY (NAME VARCHAR2(20));

d. TRUNCATE: It is used to delete all the rows from the table and free the space containing the table.
Syntax: TRUNCATE TABLE table_name;

EXAMPLE:- TRUNCATE TABLE EMPLOYEE;


CREATE:
The CREATE query is used to create a database or objects such as tables, views, stored procedures, etc.

Dept. CSE[ 3RD YR 2023-2024] Page3


GOVINDRAO WANJARI COLLEGE OF ENGINEERING
& TECHNOLOGY, NAGPUR
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

Creating a database The following example demonstrates how the CREATE query can be used to create a
database in MS SQL Server:
1 CREATE DATABASE LibraryDB
The script above creates a database named “LibraryDB” in MS SQL Server.

Creating a table
The CREATE query is also used to add tables in an existing database as shown in the following script:
1 USE LibraryDB
CREATE TABLE Books(Id INT PRIMARY KEY IDENTITY(1,1), Name VARCHAR (50) NOT
NULL, Price INT )
The above script creates a table named “Books” in the “LibraryDB” database that we created earlier.
The “Books” table contains three columns: Id, Name, and Price. The Id column is the primary key
column and it cannot be NULL. A column with a PRIMARY KEY constraint must contain unique
values. However, since we have set the IDENTITY property for the Id column, every time a new
record is added in the Books table, the value of the Id column will be incremented by 1, starting from
1. You need to specify the values for the Name column as well as it cannot have NULL. Finally, the
Price column can have NULL values. To view all the tables in the LibraryDB, execute the following
QL DDL script:
USE LibraryDB
GO
SELECT * FROM INFORMATION_SCHEMA.TABLES
GO
You should see the following output:

Similarly, to see all the columns in the Books table, run the following script:
Dept. CSE[ 3RD YR 2023-2024] Page4
GOVINDRAO WANJARI COLLEGE OF ENGINEERING
& TECHNOLOGY, NAGPUR
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

1 SELECT COLUMN_NAME, DATA_TYPE2


2 FROM INFORMATION_SCHEMA.COLUMNS
3 WHERE TABLE_NAME='Books'
Here is the output:

You can see how the CREATE query can be used to define the structure of a table and the type of
data that will be stored in a table. Note, we have not added any record to the Books table yet as
SQL DDL commands are only concerned with the structure of the database and not with the
database records. The SQL DML commands are used for inserting, modifying and deleting
database records.
ALTER
The ALTER command in SQL DDL is used to modify the structure of an already existing table.
Adding a new column
For example, if we want to add a new column e.g. ISBN to the existing Books table in the
LibraryDB database, the ALTER command can be used as follows:
1 USE LibraryDB
2 ALTER TABLE Books
3 ADD ISBN INT NOT NULL;
The syntax of the ALTER command is straightforward. The ALTER statement is used followed by the
object type and the name of the object, which in this case are TABLE and Books, respectively. Next,
you need to specify the operation that you need to perform, which is ADD in our case. Let’s now again
SELECT the columns from the Books table and see if the ISBN column has been added to the Books
table:
1 SELECT COLUMN_NAME, DATA_TYPE

Dept. CSE[ 3RD YR 2023-2024] Page5


GOVINDRAO WANJARI COLLEGE OF ENGINEERING
& TECHNOLOGY, NAGPUR
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

2 FROM INFORMATION_SCHEMA.
3 COLUMNS WHERE TABLE_NAME='Books'
Here is the result set:

In the output, you can see the newly added ISBN column. Modifying an existing column Let’s see
another case where ALTER command can be useful. Suppose, instead of adding a new column to a
table, you want to modify an existing column.
For example, you want to change the data type of the ISBN column from INT to VARCHAR (50). The
ALTER query can be used as follows:
1 USE LibraryDB ALTER TABLE Books ALTER COLUMN ISBN VARCHAR(50);
You can see that to modify an existing column within a table, we first have to use the ALTER
command with the table name and then another ALTER command with the name of the column that is
to be modified. If you again select the column names, you will see the updated data type (VARCHAR)
for the ISBN column.
DROP
The DROP command is a type of SQL DDL command, that is used to delete an existing database or
an object within a database.
Deleting a database The following DROP command deletes the LibraryDB database that we created
earlier:
1 DROP DATABASE LibraryDB
Note: If you execute the above command, the LibraryDB database will be deleted. To execute the rest
of the queries in this article, you will again need to CREATE the LibraryDB database, along with the
Books table.
Deleting a table The DROP command is a type of SQL DDL command that is used to delete an
existing table.
RD
Dept. CSE[ 3 YR 2023-2024] Page6
GOVINDRAO WANJARI COLLEGE OF ENGINEERING
& TECHNOLOGY, NAGPUR
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

For instance, the following command will delete the Books table:
1 DROP TABLE Books
Deleting a column
To delete a column within a database, the DROP query is used in combination with the ALTER query.
The ALTER query specifies the table that you want to delete whereas the DROP query specifies the
column to delete within the table specified by the ALTER query. Let’s drop the ISBN column from the
Books:
1 ALTER TABLE Books
2 DROP COLUMN ISBN
TRUNCATE
The TRUNCATE command in SQL DDL is used to remove all the records from a table. Let’s insert a
few records in the Books table:
INSERT INTO Books VALUES ('Book-A', 100), ('Book-B', 200), ('Book-C', 150)
Let’s see if the records have been actually inserted:
1 SELECT * FROM Books
Here is the result set:

You can see the three records that we inserted in the Books table.
The TRUNCATE command will remove all the records from the Books table as shown below:
1 TRUNCATE TABLE Books
If you again select all the records from the Books table, you will see that the table is empty.
RESULT:
Hence, we execute the DDL (Data Definition Command) command successfully.

Dept. CSE[ 3RD YR 2023-2024] Page7


GOVINDRAO WANJARI COLLEGE OF ENGINEERING
& TECHNOLOGY, NAGPUR
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

PRACTICAL NO: 2

AIM: To study and execute DML command (Data Manipulation Command).

THEORY:

Data Manipulation Language (DML) commands in SQL deals with manipulation of data records stored within

the database tables. It does not deal with changes to database objects and its structure. The commonly

known DML commands are INSERT, UPDATE and DELETE. Liberally speaking, we can consider even SELECT

statement as a part of DML commands. Albeit, it strictly forms part of the Data Query Language (DQL)

command. Commands of DML

1. SELECT SELECT command or statement in SQL is used to fetch data records from the database table and present it
in the form of a result set. It is usually considered as a DQL command but it can also be considered as DML.
The basic syntax for writing a SELECT query in SQL is as follows :
SELECT column_name1, column_name2, … FROM table_name WHERE condition_ expression;
The parameters used in the above syntax are as follows :
• column_name1, column_name2, … : Specify the column_names which have to be fetched or selected for the final
result set.
• table_name: Specify the name of the database table from which these results have to be fetched.
• condition_expression: Specify the condition expression for filtering records for the final result set.
Here are a few examples to illustrate the use of SELECT command.
SELECT customer_id, sale_date, order_id, store_state FROM customers;
The query returns the following output.

Dept. CSE[ 3RD YR 2023-2024] Page8


GOVINDRAO WANJARI COLLEGE OF ENGINEERING
& TECHNOLOGY, NAGPUR
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

In this example, we have fetched fields such as customer_id, sale_date, order_id and store_state from
customers table. Next, suppose if we want to fetch all the records from the customers table. This can be
achieved by a simple query as shown below.
SELECT * FROM customers;
The query returns the following output.

Dept. CSE[ 3RD YR 2023-2024] Page9


GOVINDRAO WANJARI COLLEGE OF ENGINEERING
& TECHNOLOGY, NAGPUR
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

2. INSERT
INSERT commands in SQL are used to insert data records or rows in a database table. In an INSERT statement, we
specify both the column_names for which the entry has to be made along with the data value that has to be
inserted.
The basic syntax for writing INSERT statements in SQL is as follows :
INSERT INTO table_name (column_name_1, column_name_2, column_name_3, ...) VALUES (value1, value2,
value3, ...)
By VALUES, we mean the value of the corresponding columns.
Here are a few examples to further illustrate the INSERT statement.
INSERT INTO public.customers( customer_id, sale_date, sale_amount, salesperson, store_state, order_id) VALUES
(1005,'2019-12-12',4200,'R K Rakesh','MH','1007');

Here we have tried to insert a new row in the Customers table using the INSERT command. The query accepts
two sets of arguments, namely field names or column names and their corresponding values.
Suppose if we have to insert values into all the fields of the database table, then we need not specify the
column names, unlike the previous query.
Follow the following query for further illustration.
INSERT INTO customers VALUES ('1006','2020-03-04',3200,'DL', '1008');

Dept. CSE[ 3RD YR 2023-2024] Page10


GOVINDRAO WANJARI COLLEGE OF ENGINEERING
& TECHNOLOGY, NAGPUR
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

1. UPDATE
UPDATE command or statement is used to modify the value of an existing column in a database table.

The syntax for writing an UPDATE statement is as follows :

UPDATE table_name
SET column_name_1 = value1, column_name_2 = value2, ...
WHERE condition;

Having learnt the syntax, let us now try an example based on the UPDATE statement in SQL.

UPDATE customers
SET store_state = 'DL'
WHERE store_state = 'NY';
1.DELETE
DELETE statement in SQL is used to remove one or more rows from the database table. It

does not delete the data records permanently. We can always perform a rollback operation

to undo a DELETE command. With DELETE statements we can use the WHERE clause for

filtering specific rows.

The syntax for writing an DELETE statement is as follows :

Dept. CSE[ 3RD YR 2023-2024] Page11


GOVINDRAO WANJARI COLLEGE OF ENGINEERING
& TECHNOLOGY, NAGPUR
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

DELETE FROM table_name WHERE condition;

Having learnt the syntax, we are all set to try an example based on the DELETE command in SQL.
DELETE FROM customers
WHERE store_state = 'MH'
AND customer_id = '1001';

Dept. CSE[ 3RD YR 2023-2024] Page12


GOVINDRAO WANJARI COLLEGE OF ENGINEERING
& TECHNOLOGY, NAGPUR
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

RESULT:

Hence, we executed the DML (Data Manipulation Command) command successfully.


PRACTICAL NO:-3

AIM:- To study and execute Primary key and foreign key concept.

Theory:-

Primary Key:- Primary key is a unique column we set in a table to easily identify and locate data in

queries. A table can have only one primary key. The primary key column has a unique value and doesn’t store
repeating values. A Primary key can never take NULL values.

For example, in the case of a student when identification needs to be done in the class, the roll number of the
student plays the role of Primary key.
Similarly, when we talk about employees in a company, the employee ID is functioning as the Primary key for
identification.

Let us now understand the Syntax of creating the table with the Primary key specified.

Syntax:
CREATE TABLE tableName (
col1 int NOT NULL,
col2 varchar(50) NOT NULL,
col3 int,
…………….
PRIMARY KEY (col1)
);

Foreign key :-

A Foreign key is beneficial when we connect two or more tables so that data from both can be put to use
parallelly.

A foreign key is a field or collection of fields in a table that refers to the Primary key of the other table. It is
responsible for managing the relationship between the tables.

The table which contains the foreign key is often called the child table, and the table whose primary key is being
referred by the foreign key is called the Parent Table.

For example: When we talk about students and the courses they have enrolled in, now if we try to store all the
data in a single table, the problem of redundancy arises.
Dept. CSE[ 3RD YR 2023-2024] Page13
GOVINDRAO WANJARI COLLEGE OF ENGINEERING
& TECHNOLOGY, NAGPUR
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

To solve this table, we make two tables, one the student detail table and the other department table. In the student
table, we store the details of students and the courses they have enrolled in.

And in the department table, we store all the details of the department. Here the courseId acts as the Primary key
for the department table whereas it acts as the Foreign key in the student table.

Let us now look at the syntax of creating a table with a foreign key.

Syntax:
CREATE TABLE childTable (

col1 int NOT NULL,

col2 int NOT NULL,

col3 int,

………...

PRIMARY KEY (col1),

FOREIGN KEY (col3) REFERENCES parentTable(parent_Primary_key)

);

Understanding Primary and Foreign Key in detail with Examples

1. Creation of Parent Table DataFlair

Query:
CREATE TABLE DataFlair(

emp_id varchar(5) NOT NULL,

name varchar(50),

location varchar(50),

experience int,

PRIMARY KEY(emp_id));

Output:

Dept. CSE[ 3RD YR 2023-2024] Page14


GOVINDRAO WANJARI COLLEGE OF ENGINEERING
& TECHNOLOGY, NAGPUR
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

2. Creation of Child Table Location

Query:
CREATE TABLE location(

location_id varchar(5) NOT NULL,

location varchar(50) NOT NULL,

office_size int,

PRIMARY KEY(location_id),

FOREIGN KEY(location) REFERENCES dataflair(location));

Output:

Dept. CSE[ 3RD YR 2023-2024] Page15


GOVINDRAO WANJARI COLLEGE OF ENGINEERING
& TECHNOLOGY, NAGPUR
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

RESULT: Hence, we executed the Primary key and foreign key concept.

Dept. CSE[ 3RD YR 2023-2024] Page16


GOVINDRAO WANJARI COLLEGE OF ENGINEERING
& TECHNOLOGY, NAGPUR
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

PRACTICAL NO:4

AIM:- To study and execute aggregate function. (MIN, MAX, SUM, Count &AVG).

Theory:-

o SQL aggregation function is used to perform the calculations on multiple rows of a single column
of a table. It returns a single value.
o It is also used to summarize the data.

1. COUNT FUNCTION
o COUNT function is used to Count the number of rows in a database table. It can work on both
numeric and non-numeric data types.
o COUNT function uses the COUNT(*) that returns the count of all the rows in a specified table.
COUNT(*) considers duplicate and Null.

Syntax

1. COUNT(*)
2. or
3. COUNT( [ALL|DISTINCT] expression )

Sample table: PRODUCT_MAST

Dept. CSE[ 3RD YR 2023-2024] Page17


GOVINDRAO WANJARI COLLEGE OF ENGINEERING
& TECHNOLOGY, NAGPUR
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

Example: COUNT()

1. SELECT COUNT(*)
2. FROM PRODUCT_MAST;

Output:

10

Example: COUNT with WHERE

1. SELECT COUNT(*)
2. FROM PRODUCT_MAST;
3. WHERE RATE>=20;

Output:
7

Example: COUNT() with DISTINCT

1. SELECT COUNT(DISTINCT COMPANY)


2. FROM PRODUCT_MAST;

Output:

Dept. CSE[
3 3RD YR 2023-2024] Page18
GOVINDRAO WANJARI COLLEGE OF ENGINEERING
& TECHNOLOGY, NAGPUR
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

Example: COUNT() with GROUP BY

1. SELECT COMPANY, COUNT(*)


2. FROM PRODUCT_MAST
3. GROUP BY COMPANY;

Output:

Com1 Com2
5 Com3
3
2

Example: COUNT() with HAVING

1. SELECT COMPANY, COUNT(*)


2. FROM PRODUCT_MAST
3. GROUP BY COMPANY
4. HAVING COUNT(*)>2;

Output:

Com1 Com2
5
3

3. SUM Function

Sum function is used to calculate the sum of all selected columns. It works on numeric fields only.

Syntax

1. SUM()
2. or
3. SUM( [ALL|DISTINCT] expression )

Example: SUM()

Dept. CSE[ 3RD YR 2023-2024] Page19


GOVINDRAO WANJARI COLLEGE OF ENGINEERING
& TECHNOLOGY, NAGPUR
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

1. SELECT SUM(COST)
2. FROM PRODUCT_MAST;

Output:

670

Example: SUM() with WHERE

1. SELECT SUM(COST)
2. FROM PRODUCT_MAST
3. WHERE QTY>3;

Output:

320

Example: SUM() with GROUP BY

1. SELECT SUM(COST)
2. FROM PRODUCT_MAST
3. WHERE QTY>3
4. GROUP BY COMPANY;

Output:

Com1 Com2
150
170

Example: SUM() with HAVING

1. SELECT COMPANY, SUM(COST)


2. FROM PRODUCT_MAST
3. GROUP BY COMPANY
4. HAVING SUM(COST)>=170;

Output:

Com1 Com3
335
170

Dept. CSE[ 3RD YR 2023-2024] Page20


GOVINDRAO WANJARI COLLEGE OF ENGINEERING
& TECHNOLOGY, NAGPUR
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

3. AVG function

The AVG function is used to calculate the average value of the numeric type. AVG function returns the
average of all non-Null values.

Syntax

1. AVG()
2. or
3. AVG( [ALL|DISTINCT] expression )

Example:

1. SELECT AVG(COST)
2. FROM PRODUCT_MAST;

67.00
Output:

Dept. CSE[ 3RD YR 2023-2024] Page21


GOVINDRAO WANJARI COLLEGE OF ENGINEERING
& TECHNOLOGY, NAGPUR
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

4. MAX Function

MAX function is used to find the maximum value of a certain column. This function
determines the largest value of all selected values of a column.

Syntax

1. MAX()
2. or
3. MAX( [ALL|DISTINCT] expression )

Examples:

1. SELECT MAX(RATE)
2. FROM PRODUCT_MAST;

30

5. MIN Function

MIN function is used to find the minimum value of a certain column. This function
determines the smallest value of all selected values of a column.

Syntax

1. MIN()
2. or
3. MIN( [ALL|DISTINCT] expression )

Example:

1. SELECT MIN(RATE)
2. FROM PRODUCT_MAST;

Output:

10

RESULT: Hence, we executed the Aggregate function (MIN, MAX, SUM, Count & AVG).

Dept. CSE[ 3RD YR 2023-2024] Page22


GOVINDRAO WANJARI COLLEGE OF ENGINEERING
& TECHNOLOGY, NAGPUR
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

PRACTICAL NO: 5

AIM:- To perform queries based on Group By, Having By, Order By clause.

Dept. CSE[ 3RD YR 2023-2024] Page23


GOVINDRAO WANJARI COLLEGE OF ENGINEERING
& TECHNOLOGY, NAGPUR
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

Theory:-

SQL Clauses

The following are the various SQL clauses:

1. GROUP BY

o SQL GROUP BY statement is used to arrange identical data into groups. The GROUP BY statement is used
with the SQL SELECT statement.
o The GROUP BY statement follows the WHERE clause in a SELECT statement and precedes the ORDER BY
clause.
o The GROUP BY statement is used with aggregation function.

Syntax

1. SELECT column
2. FROM table_name
3. WHERE conditions
4. GROUP BY column
5. ORDER BY column
Dept. CSE[ 3RD YR 2023-2024] Page24
GOVINDRAO WANJARI COLLEGE OF ENGINEERING
& TECHNOLOGY, NAGPUR
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

Sample table:

PRODUCT_MAST

PRODUCT COMPANY QTY RATE COST

Item1 Com1 2 10 20

Item2 Com2 3 25 75

Item3 Com1 2 30 60

Item4 Com3 5 10 50

Item5 Com2 2 20 40

Item6 Cpm1 3 25 75

Item7 Com1 5 30 150

Item8 Com1 3 10 30

Item9 Com2 2 25 50

Item10 Com3 4 30 120

Example:

1. SELECT COMPANY, COUNT(*)


Dept. CSE[ 3RD YR 2023-2024] Page25
GOVINDRAO WANJARI COLLEGE OF ENGINEERING
& TECHNOLOGY, NAGPUR
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

2. FROM PRODUCT_MAST
3. GROUP BY COMPAN
Output:

Com1 5

Com2 3

2. HAVING

o HAVING clause is used to specify a search condition for a group or an aggregate.


o Having is used in a GROUP BY clause. If you are not using GROUP BY clause then you can use HAVING
function like a WHERE clause.

Syntax:

1. SELECT column1, column2


2. FROM table_name
3. WHERE conditions
4. GROUP BY column1, column2
5. HAVING conditions
6. ORDER BY column1, column2;

Example:

1. SELECT COMPANY, COUNT(*)


2. FROM PRODUCT_MAST
3. GROUP BY COMPANY
4. HAVING COUNT(*)>2;

Output:

Com1 5

Com2 3
3. ORDER BY
Dept. CSE[ 3RD YR 2023-2024] Page26
GOVINDRAO WANJARI COLLEGE OF ENGINEERING
& TECHNOLOGY, NAGPUR
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

o The ORDER BY clause sorts the result-set in ascending or descending order.


o It sorts the records in ascending order by default. DESC keyword is used to sort the records in
descending order.

Syntax:

1. SELECT column1, column2


2. FROM table_name
3. WHERE condition
4. ORDER BY column1, column2... ASC|DESC;

Where

ASC: It is used to sort the result set in ascending order by expression.

DESC: It sorts the result set in descending order by expression.

Example: Sorting Results in Ascending Order

Table:

CUSTOM

ER

CUSTOMER_ID NAME ADDRESS

12 Kathrin US

23 David Bangkok

Dept. CSE[ 3RD YR 2023-2024] Page27


GOVINDRAO WANJARI COLLEGE OF ENGINEERING
& TECHNOLOGY, NAGPUR
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

34 Alina Dubai

45 John UK

56 Harry US

Dept. CSE[ 3RD YR 2023-2024] Page28


GOVINDRAO WANJARI COLLEGE OF ENGINEERING
& TECHNOLOGY, NAGPUR
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

Enter the following SQL statement:

1. SELECT *
2. FROM CUSTOMER
3. ORDER BY NAME;

Output:

CUSTOMER_ID NAME ADDRESS

34 Alina Dubai

23 David Bangkok

56 Harry US

45 John UK

12 Kathrin US

Example: Sorting Results in Descending Order

Using the above CUSTOMER table

1. SELECT *
2. FROM CUSTOMER
3. ORDER BY NAME DESC;

Dept. CSE[ 3RD YR 2023-2024] Page29


GOVINDRAO WANJARI COLLEGE OF ENGINEERING
& TECHNOLOGY, NAGPUR
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

Output:

CUSTOMER_ID NAME ADDRESS

12 Kathrin US

45 John UK

56 Harry US

23 David Bangkok

34 Alina Dubai

RESULT:

Hence, we executed group by and order by operation successfully.

PRACTICAL NO:-6

Dept. CSE[ 3RD YR 2023-2024] Page30


GOVINDRAO WANJARI COLLEGE OF ENGINEERING
& TECHNOLOGY, NAGPUR
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

AIM:- To study & execute join operation. (Inner join, Left join, Right join , Outer join, Natural join, Equal
join, Cartesian join operation).

Theory:-

SQL join is used to fetch data from two or more tables, which is joined to appear as single set of data.
Sql join is used for combining column from two or more tables by using values common to both tables. Minimum
required condition for joining tables, is (n-1) where n is number of tables.

STUDENT
ID NAME
1 Abhi
2 Neha
3 Renu

STUDENT 1
ID ADDRESS
1 Mumbai
2 Nagpur
3 Akola

Types of join:

 Inner
 Outer
 Left
 Right

Cross join or Cartesian product:

In this type of join returns the Cartesian product of rows from the tables in join. It will return a table which consist
of records which combines each row from the 1st table with each row of 2nd table.

Syntax:
SELECT column_ name_ list

From table_ name 1

CROSS JOIN Table_ name 2;

Dept. CSE[ 3RD YR 2023-2024] Page31


GOVINDRAO WANJARI COLLEGE OF ENGINEERING
& TECHNOLOGY, NAGPUR
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

Ex:

SELECT *

From student,

CROSS JOIN student 1;


ID NAME ID ADDRESS
1 Abhi 1 Mumbai
2 Neha 1 Mumbai
4 Renu 1 Mumbai
1 Abhi 2 Nagpur
2 Neha 2 Nagpur
4 Renu 2 Nagpur
1 Abhi 3 Akola
2 Neha 3 Akola
4 Renu 3 Akola

Dept. CSE[ 3RD YR 2023-2024] Page32


GOVINDRAO WANJARI COLLEGE OF ENGINEERING
& TECHNOLOGY, NAGPUR
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

INNER JOIN OR EQUAL JOIN:

This is a simple JOIN in which the result is based on matched data as per the equality condition specified in the
query.

Syntax:

SELECT column_ name_ list

From table_ name 1

INNER JOIN

Table_ name 2

Where table_ name 1. Column _ name= table_ name 2. Column _ name;

Ex:

SELECT* from student

Student 1 where

Stu_ id = student_ id;

Dept. CSE[ 3RD YR 2023-2024] Page33


GOVINDRAO WANJARI COLLEGE OF ENGINEERING
& TECHNOLOGY, NAGPUR
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

ID NAME ID ADDRESS

1 Abhi 1 Mumbai
2 Neha 2 Nagpur
3 Renu 3 Akola

NATURAL JOIN:

Natural join is a type of Inner join which is based on column having same name and same datatype present
in both the tables to be joined.

Syntax:

SELECT* from table_ name 1

NATURAL JOIN

Table_ name 2;

Ex:

SELECT* from student

NATURAL JOIN

Student1;

ID NAME ADDRESS
1 Abhi Mumbai
2 Neha Nagpur
3 Renu Akola

OUTER JOIN:

Outer join is based on both matched and unmatched data. Outer joins subdivide further into
Dept. CSE[ 3RD YR 2023-2024] Page34
GOVINDRAO WANJARI COLLEGE OF ENGINEERING
& TECHNOLOGY, NAGPUR
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

 Left outer join


 Right outer join
 Full outer join

Dept. CSE[ 3RD YR 2023-2024] Page35


GOVINDRAO WANJARI COLLEGE OF ENGINEERING
& TECHNOLOGY, NAGPUR
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

Left outer join:

The left outer join returns a result table with the matched data of two tables then remaining rows of the left
table and null for the right tables column.

Syntax:

SELECT column_ name_ list

From table_ name 1

LEFT OUTER JOIN

Table_ name 2

On table_ name 1.column_ name =table_ name2.column_ name;

Ex:

SELECT* from student

LEFT OUTER JOIN

Student 1 ON (stud _ id=student_ id);

ID NAME ID ADDRESS
1 Abhi 1 Mumbai
2 Neha 2 Nagpur
3 Renu 3 Akola
4 Pihu Null Null
5 Sona Null Null

RIGHT OUTER JOIN:

The right outer join returns a result table with the matched data of two tables then remaining rows of the

Right table and null for the left tables columns.

Dept. CSE[ 3RD YR 2023-2024] Page36


GOVINDRAO WANJARI COLLEGE OF ENGINEERING
& TECHNOLOGY, NAGPUR
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

Syntax:

SELECT column_ name_ list

From table_ name 1

RIGHT OUTER JOIN


Table_ name 2

On table_ name 1. Column_ name= table_ name 2.column_ name;

Ex:

SELECT* from student

RIGHT OUTER JOIN

Student 1 ON (stud _ id=student_ id);

ID NAME ID ADDRESS
1 Abhi 1 Mumbai
2 Neha 2 Nagpur
3 Renu 3 Akola
NULL NULL 7 Pune
NULL NULL 8 amravati

FULL OUTER JOIN:

The full outer join returns a result table with the matched data of two table then remaining rows of both left
table & then the right tables.

Syntax:

SELECT column_ name_ list

From table_ name 1

FULL OUTER JOIN


Dept. CSE[ 3RD YR 2023-2024] Page37
GOVINDRAO WANJARI COLLEGE OF ENGINEERING
& TECHNOLOGY, NAGPUR
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

Table_ name 2

On table_ name 1. Column_ name= table_ name 2.column_ name;

Ex:

SELECT* from student

FULL OUTER JOIN

Student 1 ON (stud _ id=student_ id);

ID NAME ID ADDRESS
1 Abhi 1 Mumbai
2 Neha 2 Nagpur
3 Renu 3 Akola
4 Pihu Null null
NULL NULL 7 pune

RESULT:
Hence, we successfully execute join operation. (Inner join, Left join, Right join, Outer join, Natural join,
Equal join, Cartesian join operation

Dept. CSE[ 3RD YR 2023-2024] Page38


GOVINDRAO WANJARI COLLEGE OF ENGINEERING
& TECHNOLOGY, NAGPUR
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

PRACTICAL:-7
AIM:- To study and execute set operation (union, insert, minus).

THEORY:

SQL Set Operation:

The SQL Set operation is used to combine the two or more SQL SELECT statements.

Types of Set Operation

Union

Intersect

Minus

1. Union

o The SQL Union operation is used to combine the result of two or more SQL SELECT queries.
o In the union operation, all the number of datatype and columns must be same in both the tables on which
UNION operation is being applied.
o The union operation eliminates the duplicate rows from its resultset.

Syntax

1. SELECT column_name FROM table1


2. UNION
3. SELECT column_name FROM table2;
4. Example:

The First table

Dept. CSE[ 3RD YR 2023-2024] Page39


GOVINDRAO WANJARI COLLEGE OF ENGINEERING
& TECHNOLOGY, NAGPUR
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

ID NAME

1 Jack

2 Harry

3 Jackson

The Second table

ID NAME

3 Jackson

4 Stephan

5 Davi
d

Union SQL query will be:


Difference between JDK, JRE, and JVM

SELECT * FROM First


UNION
SELECT * FROM Second;

The result set table will look like:

Dept. CSE[ 3RD YR 2023-2024] Page40


GOVINDRAO WANJARI COLLEGE OF ENGINEERING
& TECHNOLOGY, NAGPUR
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

ID NAME

1 Jack

2 Harry

3 Jackson

4 Stephan

5 Davi
d

2. Intersect

o It is used to combine two SELECT statements. The Intersect operation returns the common rows

from both the SELECT statements.

o In the Intersect operation, the number of datatype and columns must be the same.
o It has no duplicates and it arranges the data in ascending order by default.

Syntax

SELECT column_name FROM


table1 INTERSECT
SELECT column_name FROM table2;
Example:

Using the above First and Second table.

Intersect query will be:

Dept. CSE[ 3RD YR 2023-2024] Page41


GOVINDRAO WANJARI COLLEGE OF ENGINEERING
& TECHNOLOGY, NAGPUR
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

SELECT * FROM
First INTERSECT

SELECT * FROM Second;

The resultset table will look like:

ID NAME

3 Jackso
n

3. Minus

o It combines the result of two SELECT statements. Minus operator is used to display the rows

which are present in the first query but absent in the second query.

o It has no duplicates and data arranged in ascending order by default.

Syntax:

SELECT column_name FROM


table1 MINUS
SELECT column_name FROM table2;

Example

Using the above First and Second table.

Minus query will be:

SELECT * FROM
First MINUS
SELECT * FROM Second;
Dept. CSE[ 3RD YR 2023-2024] Page42
GOVINDRAO WANJARI COLLEGE OF ENGINEERING
& TECHNOLOGY, NAGPUR
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

The result set table will look like:

ID NAME

1 Jack

2 Harr
y

RESULT:

Hence, we executed set operation (union, insert, minus) successfully.

PRACTICAL NO:-8

AIM:- To study and execute views.

THEORY:
Views in SQL are kind of virtual tables. A view also has rows and columns as they are in a
Dept. CSE[ 3RD YR 2023-2024] Page43
GOVINDRAO WANJARI COLLEGE OF ENGINEERING
& TECHNOLOGY, NAGPUR
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

real table in the database. We can create a view by selecting fields from one or more tables
present in the database. A View can either have all the rows of a table or specific rows
based on certain condition.
In this article we will learn about creating , deleting and updating Views.

Sample Tables:

Student Details

Student Marks

CREATING VIEWS

We can create View using CREATE VIEW statement. A View can be created from a single table or multiple
tables.

Syntax:

CREATE VIEW view_name AS


SELECT column1,
column2.....
FROM
table_name
WHERE
Dept. CSE[ 3RD YR 2023-2024] Page44
GOVINDRAO WANJARI COLLEGE OF ENGINEERING
& TECHNOLOGY, NAGPUR
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

condition;

view_name: Name for the View

table_name: Name of the table

condition: Condition to select rows

Examples:

 Creating View from a single table:

 In this example we will create a View named DetailsView from the table
StudentDetails. Query:
 CREATE VIEW DetailsView AS
 SELECT NAME, ADDRESS
 FROM StudentDetails
 WHERE S_ID < 5;
To see the data in the View, we can query the view in the same manner as we
query a table.
SELECT * FROM DetailsView;

Output:

Dept. CSE[ 3RD YR 2023-2024] Page45


GOVINDRAO WANJARI COLLEGE OF ENGINEERING
& TECHNOLOGY, NAGPUR
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

 In this example, we will create a view named StudentNames from


the table StudentDetails.
Query:

CREATE VIEW StudentNames


AS SELECT S_ID, NAME
FROM
StudentDetails
ORDER BY NAME;
If we now query the view as,
SELECT * FROM StudentNames;
Output:

Creating View from multiple tables:

In this example we will create a View named MarksView from two tables Student Details and
Student Marks. To create a View from multiple tables we can simply include multiple tables in
the SELECT statement. Query:
CREATE VIEW Marks View AS
SELECT StudentDetails.NAME, StudentDetails.ADDRESS,

Dept. CSE[ 3RD YR 2023-2024] Page46


GOVINDRAO WANJARI COLLEGE OF ENGINEERING
& TECHNOLOGY, NAGPUR
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

StudentMarks.MARKS FROM StudentDetails, StudentMarks


WHERE StudentDetails.NAME = StudentMarks.NAME;

To display data of View MarksView:


SELECT * FROM MarksView;

Output:

DELETING VIEWS

We have learned about creating a View, but what if a created View is not needed any
more? Obviously we will want to delete it. SQL allows us to delete an existing View. We can
delete or drop a View using the DROP statement.

Syntax:

DROP VIEW view_name;


view_name: Name of the View which we want to delete.

For example, if we want to delete the View MarksView, we can do this as:

DROP VIEW MarksView;

UPDATING VIEWS

There are certain conditions needed to be satisfied to update a view. If any one of these conditions is not met, then
we will not be allowed to update the view.

The SELECT statement which is used to create the view should not include GROUP BY clause or ORDER BY clause.

Dept. CSE[ 3RD YR 2023-2024] Page47


GOVINDRAO WANJARI COLLEGE OF ENGINEERING
& TECHNOLOGY, NAGPUR
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

The SELECT statement should not have the DISTINCT keyword.

The View should have all NOT NULL values.

The view should not be created using nested queries or complex queries.

The view should be created from a single table. If the view is created using multiple tables then we will not be
allowed to update the view.

We can use the CREATE OR REPLACE VIEW statement to add or remove fields from a view.

Syntax:

CREATE OR REPLACE VIEW view_name AS

SELECT column1,coulmn2,..

FROM table_name

WHERE condition;

For example, if we want to update the view MarksView and add the field AGE to
this View from StudentMarks Table, we can do this as:

CREATE OR REPLACE VIEW MarksView AS

SELECT StudentDetails.NAME, StudentDetails.ADDRESS, StudentMarks.MARKS, StudentMarks.AGE

FROM StudentDetails, StudentMarks

WHERE StudentDetails.NAME = StudentMarks.NAME;

If we fetch all the data from MarksView now as:


SELECT * FROM MarksView;

Output:

Dept. CSE[ 3RD YR 2023-2024] Page48


GOVINDRAO WANJARI COLLEGE OF ENGINEERING
& TECHNOLOGY, NAGPUR
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

Inserting a row in a view:


We can insert a row in a View in a same way as we do in a table. We can use the INSERT INTO statement of SQL to
insert a row in a View.Syntax:

INSERT INTO view_name(column1, column2 , column3,..)

VALUES(value1, value2, value3..);

view_name: Name of the View

Example:

In the below example we will insert a new row in the View DetailsView which we have created above in the
example of “creating views from a single table”.

INSERT INTO DetailsView(NAME, ADDRESS)

VALUES("Suresh","Gurgaon");

If we fetch all the data from DetailsView now as,

SELECT * FROM DetailsView;

Output:

Deleting a row from a View:

Deleting rows from a view is also as simple as deleting rows from a table. We can use the DELETE statement of SQL
to delete rows from a view. Also deleting a row from a view first delete the row from the actual table and the
change is then reflected in the view.Syntax:

DELETE FROM

view_name WHERE

Dept. CSE[ 3RD YR 2023-2024] Page49


GOVINDRAO WANJARI COLLEGE OF ENGINEERING
& TECHNOLOGY, NAGPUR
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

condition;

view_name:Name of view from where we want to delete rows

condition: Condition to select rows

Example:
In this example we will delete the last row from the view DetailsView which we just added in the above example of
inserting rows.

DELETE FROM

DetailsView WHERE

NAME="Suresh";

If we fetch all the data from DetailsView now as,

SELECT * FROM DetailsView;

Output:

WITH CHECK OPTION

The WITH CHECK OPTION clause in SQL is a very useful clause for views. It is applicable to a updatable
view. If the view is not updatable, then there is no meaning of including this clause in the CREATE VIEW
statement.

The WITH CHECK OPTION clause is used to prevent the insertion of rows in the view where the condition
in the WHERE clause in CREATE VIEW statement is not satisfied.

Dept. CSE[ 3RD YR 2023-2024] Page50


GOVINDRAO WANJARI COLLEGE OF ENGINEERING
& TECHNOLOGY, NAGPUR
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

If we have used the WITH CHECK OPTION clause in the CREATE VIEW statement, and if the UPDATE or
INSERT clause does not satisfy the conditions then they will return an error.

Example:

In the below example we are creating a View SampleView from StudentDetails Table with WITH CHECK OPTION
clause.

CREATE VIEW SampleView

AS SELECT S_ID, NAME

FROM StudentDetails

WHERE NAME IS NOT

NULL WITH CHECK

OPTION;

In this View if we now try to insert a new row with null value in the NAME column then it will give an error because
the view is created with the condition for NAME column as NOT NULL.
For example,though the View is updatable but then also the below query for this View is not valid:

INSERT INTO

SampleView(S_ID)

VALUES(6);

NOTE: The default value of NAME column is null.

Uses of a View :

A good database should contain views due to the given reasons:

Restricting data access –


Views provide an additional level of table security by restricting access to a predetermined set of rows and columns
of a table.

Dept. CSE[ 3RD YR 2023-2024] Page51


GOVINDRAO WANJARI COLLEGE OF ENGINEERING
& TECHNOLOGY, NAGPUR
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

Hiding data complexity –


A view can hide the complexity that exists in a multiple table join.

Simplify commands for the user –


Views allows the user to select information from multiple tables without requiring the users to actually know how
to perform a join.

Store complex queries –


Views can be used to store complex queries.

Rename Columns –
Views can also be used to rename the columns without affecting the base tables provided the number of columns
in view must match the number of columns specified in select statement. Thus, renaming helps to to hide the
names of the columns of the base tables.

Multiple view facility –


Different views can be created on the same table for different user

RESULT:

Hence, we successfully studied and executed views.

Dept. CSE[ 3RD YR 2023-2024] Page52


GOVINDRAO WANJARI COLLEGE OF ENGINEERING
& TECHNOLOGY, NAGPUR
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

PRACTICAL NO. 9

AIM: To study about PL-SQL & execute a PL-SQL simple program of IF-else command.

THEORY:

PL_SQL

The PL/SQL programming language was developed by oracle corporation in the late 1980s as procedural
extension language for SQL & the oracle relational data.

The If-Then-else statement allows you to choose between several alternatives. An if-then statement can be
followed by an optional else If-else statement. The ELSIF clause lets you add additional condition.

Syntax:

The syntax of an IF-THEN-ELSIF statement PL/SQL programming language is :-

If (Boolean. Expression 1) THEN

S1;….executes when the Boolean expression 1 is true.

ELSIF (Boolean. Expression 2) THEN

S2;….. executes when the Boolean expression 2 is true.

ELSIF (Boolean. Expression 3) THEN

S3;….. executes when the Boolean expression 3 is true.

ELSE

S4;….. executes when the none of the above condition is true.

END IF;
Dept. CSE[ 3RD YR 2023-2024] Page53
GOVINDRAO WANJARI COLLEGE OF ENGINEERING
& TECHNOLOGY, NAGPUR
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

Following are certain notable facts about PL/SQL.

1) PL/SQL is a completely portable high performance transaction processing language.


2) PL/SQL provides a built-in interpreted & os independent programming environment.
3) PL/SQL cam also directly be called from the command line SQL*plus interface.
4) Direct call can also be made from external programming language calls to database.
5) PL/SQL’s general syntax is based on that of ADA and pascal programming language.
6) Apart from oracle, PL/SQL is available in times ten in memory database & IBMDB 2.
Advantages of PL/SQL:

1) PL/SQL allows sending an entire block of statements to the database at one time. This reduce network
traffic & provides high performance for the application.
2) PL/SQL gives high productivity to programmers as it can query transform & update data in a database.

Program:

DECLARE

a number(3):=100;

BEGIN

If (a=10) THEN

dbms_ output.put _line (“value of a is 10”);

ELSIF (a=20) THEN

dbms_output.put_line(“value of a is 20”);

ELSIF (a=30) THEN

dbms_output.put_line(“value of a is 30”);

ELSE

Dbms_output.put_lines(“none of the value is matching”);

END IF;

dbms_ output.put_line(“exact value of a is =100”);

END;

Dept. CSE[ 3RD YR 2023-2024] Page54


GOVINDRAO WANJARI COLLEGE OF ENGINEERING
& TECHNOLOGY, NAGPUR
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

OUTPUT:
None of the values is matching

Exact value of a is : 100

RESULT:

Hence, we successfully study and executed the PL/SQL simple program of IF-else command.

PRACTICAL NO. 10

AIM: To study and execute PL/SQL procedure.

To study and execute PL/SQL stored function.

THEORY:

A subprogram is a program module that perform a particular task. These subprograms are combined to larger
programs. A subprogram can be involved by another subprogram are program which is called the calling program.

A subprogram can be created

 At schema level:

A schema level subprogram is standalone subprogram. It is created with CREATE PROCEDURE OR DROP FUNCTION
statement. It is deleted with the DROP PROCEDURE OR DROP FUNCTION statement.

 Inside a package:
A subprogram created inside a package is a packaged subprogram. It is stored in the database & can be
deleted only when the package is deleted with the DROP PACKAGE statement.

PL/SQL provide two kinds of subprogram:

 Function: There subprogram return a single value, mainly used to compute & return a value.
 Procedure: There subprogram do not return a value directly, mainly used to perform an action.

Creating a procedure:

A procedure is created with the CREATE OR REPLACE PROCEDURE statement.


Dept. CSE[ 3RD YR 2023-2024] Page55
GOVINDRAO WANJARI COLLEGE OF ENGINEERING
& TECHNOLOGY, NAGPUR
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

Syntax:

CREATE [OR REPLACE] PROCEDURE procedure_ name

[C parameter_ name [IN OUT/ IN OUT] type[,…]]

{ IS /AS}

BEGIN

< procedure _ body>

END procedure_ name;

 Procedure_ name specifies the name of the procedure.


 [OR REPLACE ] option allow modifying an existing procedure.
 The optional parameter contains name, mode & byte type of the parameters. IN represents that value will
be passed from outside & OUT represents that this parameter will be used to return a value outside of the
procedure.
 Procedure_ body containts the executable part.

Ex:

CREATE OR REPLACE PROCEDURE greetings

AS

BEGIN

dbms_output.put_ine (‘hello world’);

END;

RESULT:

Procedure created.

Methods for passing parameter:

Actual parameter could be passed in 3 ways.


Dept. CSE[ 3RD YR 2023-2024] Page56
GOVINDRAO WANJARI COLLEGE OF ENGINEERING
& TECHNOLOGY, NAGPUR
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

1. Positional notation:
In the positional notation , you can call the procedure.
Find min(a, b, c, d );
In positional notation the first actual parameter is substituted for the first formal parameter;
The 2nd actual parameter is substituted for the 2nd formal parameter, & so on.
So a is substituted for x, b is substituted for y, c is substituted for z.

2. Named notation:
In named notation , the actual parameter is associated with the formal parameter using the arrow
symbol => so the procedure call would look like :
Find min(x=>a, y=>b, z=>c, m=>d).

3. Mixed notation:
In mixed notation, you can mixed both notation in procedure call ;
However the positional notation should proceed the named notation.
Find min(a, b, c, m=>d).
4. Functions
A PL/SQL function is same as a procedure except that it returns a value.

Creating function :

A standalone function is created using the CREATE FUNCTION statement. The simplified syntax the create
or replace procedure.

Syntax:

CREATE [OR REPLACE] FUNCTION function_

name [C parameter_ name [IN OUT/ IN OUT] type [,

…]] RETURN return _ datatype

{ IS

/AS}

BEGIN

< function _ body>

END [ function_

name];
Dept. CSE[ 3RD YR 2023-2024] Page57
GOVINDRAO WANJARI COLLEGE OF ENGINEERING
& TECHNOLOGY, NAGPUR
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

Ex:

CREATE OR REPLACE FUNCTION total EMP

RETURN number IS

Total number (2):=0;

BEGIN

SELECT count (*) into

total FROM EMP;

RETURN total;

END;

/
OUTPUT:

SELECT* FROM EMP;

ID NAME AGE SALARY


1 Pooja 25 2000
2 Abhi 23 8500
3 Anjali 20 6500
4 jelly 22 4500

Function created.

Calling function :

A calling function performs defined task and when its return statement is executed or when it last end statement is
reached, it returns program control back to the main program.

Ex:

DECLARE

a number;

b number;

c number;
Dept. CSE[ 3RD YR 2023-2024] Page58
GOVINDRAO WANJARI COLLEGE OF ENGINEERING
& TECHNOLOGY, NAGPUR
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

FUNCTION find max (x IN number, y IN number)

RETURN number

IS

z number;

BEGIN

IF X>Y THEN

Z=X;

ELSE

Z=Y;

Dept. CSE[ 3RD YR 2023-2024] Page59


GOVINDRAO WANJARI COLLEGE OF ENGINEERING
& TECHNOLOGY, NAGPUR
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

END IF ;

RETURN Z ;

END ;

BEGIN

a:=23;

b:=45;

c:= find max (a,b) ;

dbms_output_put_line (“maximum of (23, 45):” 114);

END;

Output:

Maximum of (23, 45)=45

PL/SQL procedure successfully completed.

PL/SQL recursive function

We have seen that a program or subprogram may call another subprogram. when a subprogram call itself , it
is referred to as a recursive call & the process is known as recursion.

Calculate the factorial program:

DECLARE

Num number;

Factorial number;

FUNCTION fact (x number)

RETURN number

IS

F number;

BEGIN
Dept. CSE[ 3RD YR 2023-2024] Page60
GOVINDRAO WANJARI COLLEGE OF ENGINEERING
& TECHNOLOGY, NAGPUR
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

IF x=0 THEN

F:=1

Dept. CSE[ 3RD YR 2023-2024] Page61


GOVINDRAO WANJARI COLLEGE OF ENGINEERING
& TECHNOLOGY, NAGPUR
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

ELSE

F:=X* fact (x-1);

END IF;

RETURN F;

END;

BEGIN

num:=6

Factorial :=fact(num);

Dbms_output_put_line(“factorial”|| num||’is” || factorial);

END;

Output:

Factorial 6 is 720

PL/SQL procedure successfully completed.

RESULT:

Hence, we successfully execute PL/SQL procedure and PL/SQL stored function.

Dept. CSE[ 3RD YR 2023-2024] Page62


GOVINDRAO WANJARI COLLEGE OF ENGINEERING
& TECHNOLOGY, NAGPUR
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

Dept. CSE[ 3RD YR 2023-2024] Page63


GOVINDRAO WANJARI COLLEGE OF ENGINEERING
& TECHNOLOGY, NAGPUR
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

Dept. CSE[ 3RD YR 2023-2024] Page64


GOVINDRAO WANJARI COLLEGE OF ENGINEERING
& TECHNOLOGY, NAGPUR
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

Dept. CSE[ 3RD YR 2023-2024]


Page65

You might also like