You are on page 1of 20

(/)

SQL in PL/SQL
In this tutorial, we are going to learn how to use SQL (/sql.html)in PL/SQL. SQL (/sql.html)is the
actual component that takes care of fetching and updating of data in the database whereas
PL/SQL is the component that processes these data. Further in this article we will also discuss
how to combine the SQL (/sql.html)within the PL/SQL block.

In this tutorial, you will learn-

DML Transactions in PL/SQL

CURSOR Concept in PL/SQL

Cursor Attributes

FOR Loop Cursor statement

BULK COLLECT in PL/SQL

TCL Statements in PL/SQL

Autonomous Transaction

DML Transac ons in PL/SQL


DML stands for Data Manipulation Language. These statements are mainly used to perform
the manipulation activity. It basically deals with the below operations.

Data Insertion
Data Update
Data Deletion
Data Projection/Fetching

In PL/SQL, we can do the data manipulation only by using the SQL (/sql.html)commands.

Data Inser on
In PL/SQL, we can insert the data into any table using the SQL (/sql.html)command INSERT
INTO. This command will take the table name, table column and column values as the input
and insert the value in the base table.

The INSERT command can also take the values directly from another table using 'SELECT'
statement rather than giving the values for each column. Through 'SELECT' statement, we can
insert as many rows as the base table contains.

(//cdn.guru99.com/images/PL-SQL/110215_1042_SQLinPLSQL1.png)

Syntax Explanation:

The above syntax shows the INSERT INTO command. The table name and values are
mandatory field, whereas column names are not mandatory if the insert statements have
values for all the column of the table.
The keyword 'VALUES' is mandatory if the values are given separately as shown above.

(//cdn.guru99.com/images/PL-SQL/110215_1042_SQLinPLSQL2.png)

Syntax Explanation:

The above syntax shows the INSERT INTO command that takes the values directly from the
<table_name2> using the SELECT command.
The keyword 'VALUES' should not be present in this case as the values are not given
separately.

Data Update
Data update simply means an update of the value of any column in the table. This can be done
using 'UPDATE' statement. This statement takes the table name, column name and value as
the input and updates the data.

(//cdn.guru99.com/images/PL-SQL/110215_1042_SQLinPLSQL3.png)

Syntax Explanation:

The above syntax shows the UPDATE. The keyword 'SET' instruct that PL/SQL engine to
update the value of the column with the value given.
'WHERE' clause is optional. If this clause is not given, then the value of the mentioned
column in the entire table will be updated.

Data Dele on
Data deletion means to delete one full record from the database table. The 'DELETE' command
is used for this purpose.

(//cdn.guru99.com/images/PL-SQL/110215_1042_SQLinPLSQL4.png)

Syntax Explanation:

The above syntax shows the DELETE command. The keyword 'FROM' is optional and with
or without 'FROM' clause the command behaves in the same way.
'WHERE' clause is optional. If this clause is not given, then the entire table will be deleted.

Data Projec on/Fetching


Data projection/fetching means to retrieve the required data from the database table. This can
be achieved by using the command 'SELECT' with 'INTO' clause. The 'SELECT' command will
fetch the values from the database, and 'INTO' clause will assign these values to the local
variable of the PL/SQL block.

Below are the points that need to be considered in 'SELECT' statement.


'SELECT' statement should return only one record while using 'INTO' clause as one variable
can hold only one value. If the 'SELECT' statement returns more than one value than
'TOO_MANY_ROWS' exception will be raised.
'SELECT' statement will assign the value to the variable in the 'INTO' clause, so it needs to
get at least one record from the table to populate the value. If it didn't get any record, then
the exception 'NO_DATA_FOUND' is raised.
The number of columns and their datatype in 'SELECT' clause should match with the
number of variables and their datatypes in the 'INTO' clause.
The values are fetched and populated in the same order as mentioned in the statement.
'WHERE' clause is optional that allows to have more restriction on the records that is going
to be fetched.
'SELECT' statement can be used in the 'WHERE' condition of other DML statements to
define the values of the conditions.
The 'SELECT' statement when using 'INSERT', 'UPDATE', 'DELETE' statements should not
have 'INTO' clause as it will not populate any variable in these cases.

(//cdn.guru99.com/images/PL-SQL/110215_1042_SQLinPLSQL5.png)

Syntax Explanation:

The above syntax shows the SELECT-INTO command. The keyword 'FROM' is mandatory
that identifies the table name from which the data needs to be fetched.
'WHERE' clause is optional. If this clause is not given, then the data from the entire table will
be fetched.

Example 1: In this example, we are going to see how to perform DML operations in PL/SQL.
We are going to insert the below 4 records into emp table.

EMP_NAME EMP_NO SALARY MANAGER

BBB 1000 25000 AAA

XXX 1001 10000 BBB

YYY 1002 10000 BBB

ZZZ 1003 7500 BBB

Then we are going to update the salary of 'XXX' to 15000, and we are going to delete the
employee record 'ZZZ'. Finally, we are going to project the details of the employee 'XXX'.
(//cdn.guru99.com/images/PL-SQL/110215_1042_SQLinPLSQL6.png)

(//cdn.guru99.com/images/PL-SQL/110215_1042_SQLinPLSQL7.png)

Code Explanation:

Code line 2-5: Declaring the variable.


Code line 7-14: Inserting the records into emp table.
Code line 15: Committing the insert transactions.
Code line 17-19: Updating the salary of the employee 'XXX' to 15000
Code line 20: Committing the update transaction.
Code line 22: Deleting the record of 'ZZZ'
Code line 23: Committing the delete transaction.
Code line 25-27: Selecting the record of 'XXX' and populating into the variable
l_emp_name, l_emp_no, l_salary, l_manager.
Code line 28-32: Displaying the fetched records value.

CURSOR Concept in PL/SQL


Oracle creates a memory area, known as context area, for processing an SQL
(/sql.html)statement, which contains all information about the statement, for example, number
of rows processed, etc. Cursor is nothing but a pointer to this context area.

PL/SQL allows the programmer to control the context area through the cursor. A cursor holds
the rows returned by the SQL (/sql.html)statement. The set of rows the cursor holds is referred
as active set. These cursors can also be named so that they can be referred from other place of
the code.

The cursor is of two types.

Implicit Cursor
Explicit Cursor

Implicit Cursor
Whenever any DML operations occur in the database, an implicit cursor is created that holds
the rows affected, in that particular operation. These cursors cannot be named and hence they
cannot be controlled or referred from other place of the code. We can refer only to the most
recent cursor through the cursor attributes.

Explicit Cursor
Programmers are allowed to create named context area to execute their DML operations to get
more control over it. The explicit cursor should be defined in the declaration section of the
PL/SQL block, and it is created for the 'SELECT' statement that needs to be used in the code.

Below are steps that involved in working with explicit cursors.

Declaring the cursor


Declaring the cursor simply means to create one named context area for the 'SELECT'
statement that is defined in the declaration part. The name of this context area is same as
the cursor name.

Opening Cursor
Opening the cursor will instruct the PL/SQL to allocate the memory for this cursor. It will
make the cursor ready to fetch the records.
Fetching Data from the Cursor
In this process, the 'SELECT' statement is executed and the rows fetched is stored in the
allocated memory. These are now called as active sets. Fetching data from the cursor is a
record-level activity that means we can access the data in record-by-record way.

Each fetch statement will fetch one active set and holds the information of that particular
record. This statement is same as 'SELECT' statement that fetches the record and assign to
the variable in the 'INTO' clause, but it will not throw any exceptions.

Closing the Cursor


Once all the record is fetched now we need to close the cursor so that the memory allocated
to this context area will be released.

(//cdn.guru99.com/images/PL-SQL/110215_1042_SQLinPLSQL8.png)

Syntax Explanation:

In the above syntax, the declaration part contains the declaration of the cursor and the
cursor variable in which the fetched data will be assigned.
The cursor is created for the 'SELECT' statement that is given in the cursor declaration.
In execution part, the declared cursor is opened, fetched and closed.

Cursor A ributes
Both Implicit cursor and the explicit cursor has certain attributes that can be accessed. These
attributes give more information about the cursor operations. Below are the different cursor
attributes and their usage.

Cursor Description
Attribute

%FOUND It returns the Boolean result 'TRUE' if the most recent fetch operation
fetched a record successfully, else it will return FALSE
%NOTFOUND This works in the opposite way to %FOUND it will return 'TRUE' if the most
recent fetch operation could not able to fetch any record.

%ISOPEN It returns Boolean result 'TRUE' if the given cursor is already opened, else it
returns 'FALSE'

%ROWCOUNT It returns the numerical value. It gives the actual count of records that got
affected by the DML activity.

Example 1: In this example, we are going to see how to declare, open, fetch and close the
explicit cursor.

We will project all the employees name from emp table using a cursor. We will also use cursor
attribute to set the loop to fetch all the record from the cursor.

(//cdn.guru99.com/images/PL-SQL/110215_1042_SQLinPLSQL9.png)

Code Explanation:

Code line 2: Declaring the cursor guru99_det for statement 'SELECT emp_name FROM
emp'.
Code line 3: Declaring variable lv_emp_name.
Code line 5: Opening the cursor guru99_det.
Code line 6: Setting the Basic loop statement to fetch all the records in the 'emp' table.
Code line 7: Fetches the guru99_det data and assign the value to lv_emp_name.
Code line 9: Using the cursor attribute '%NOTFOUND' to find whether all the record in the
cursor is fetched. If fetched then it will return 'TRUE' and control will exit from the loop, else
the control will keep on fetching the data from the cursor and print the data.
Code line 11: EXIT condition for the loop statement.
Code line 12: Print the fetched employee name.
Code line 14: Using the cursor attribute '%ROWCOUNT' to find the total number of records
that got affected/fetched in the cursor.
Code line 15: After exiting from the loop the cursor is closed and the memory allocated is
set free.

FOR Loop Cursor statement


"FOR LOOP" statement can be used for working with cursors. We can give the cursor name
instead of range limit in the FOR loop statement so that the loop will work from the first record
of the cursor to the last record of the cursor. The cursor variable, opening of cursor, fetching
and closing of the cursor will be done implicitly by the FOR loop.

(//cdn.guru99.com/images/PL-SQL/110215_1042_SQLinPLSQL10.png)

Syntax Explanation:

In the above syntax, the declaration part contains the declaration of the cursor.
The cursor is created for the 'SELECT' statement that is given in the cursor declaration.
In execution part, the declared cursor is setup in the FOR loop and the loop variable 'I' will
behave as cursor variable in this case.

Example 1: In this example, we will project all the employee name from emp table using a
cursor-FOR loop.
(//cdn.guru99.com/images/PL-SQL/110215_1042_SQLinPLSQL11.png)

Code Explanation:

Code line 2: Declaring the cursor guru99_det for statement 'SELECT emp_name FROM
emp'.
Code line 4: Constructing the 'FOR' loop for the cursor with the loop variable lv_emp_name.
Code line 5: Printing the employee name in each iteration of the loop.
Code line 8: Exit the loop

Note: In Cursor-FOR loop, cursor attributes cannot be used since opening, fetching and closing
of the cursor is done implicitly by FOR loop.

BULK COLLECT in PL/SQL


Oracle PL/SQL provides the functionality of fetching the records in bulk rather than fetching
one-by-one. This BULK COLLECT can be used in 'SELECT' statement to populate the records
in bulk or in fetching the cursor in bulk. Since the BULK COLLECT fetches the record in BULK,
the INTO clause should always contain a collection type variable. The main advantage of using
BULK COLLECT is it increases the performance by reducing the interaction between database
and PL/SQL engine.

(//cdn.guru99.com/images/PL-SQL/110215_1042_SQLinPLSQL12.png)

Syntax Explanation:

In the above syntax, BULK COLLECT is used in collect the data from 'SELECT' and
'FETCH' statement.
FORALL Clause
The FORALL allows to perform the DML operations on data in bulk. It is similar to that of FOR
loop statement except in FOR loop things happen at the record-level whereas in FORALL there
is no LOOP concept. Instead the entire data present in the given range is processed at the
same time.

(//cdn.guru99.com/images/PL-SQL/110215_1042_SQLinPLSQL13.png)

Syntax Explanation:

In the above syntax, the given DML operation will be executed for the entire data that is
present between lower and higher range.

LIMIT Clause
The bulk collect concept loads the entire data into the target collection variable as a bulk i.e. the
whole data will be populated into the collection variable in a single-go. But this is not advisable
when the total record that needs to be loaded is very large, because when PL/SQL tries to load
the entire data it consumes more session memory. Hence, it is always good to limit the size of
this bulk collect operation.

However, this size limit can be easily achieved by introducing the ROWNUM condition in the
'SELECT' statement, whereas in the case of cursor this is not possible.

To overcome this Oracle has provided 'LIMIT' clause that defines the number of records that
needs to be included in the bulk.

(//cdn.guru99.com/images/PL-SQL/110215_1042_SQLinPLSQL14.png)

Syntax Explanation:

In the above syntax, the cursor fetch statement uses BULK COLLECT statement along with
the LIMIT clause.

BULK COLLECT A ributes


Similar to cursor attributes BULK COLLECT has %BULK_ROWCOUNT(n) that returns the
number of rows affected in the nth DML statement of the FORALL statement, i.e. it will give the
count of records affected in the FORALL statement for every single value from the collection
variable. The term 'n' indicates the sequence of value in the collection, for which the row count
is needed.
Example 1: In this example, we will project all the employee name from emp table using BULK
COLLECT and we are also going to increase the salary of all the employees by 5000 using
FORALL.

(//cdn.guru99.com/images/PL-SQL/110215_1042_SQLinPLSQL15.png)

Code Explanation:

Code line 2: Declaring the cursor guru99_det for statement 'SELECT emp_name FROM
emp'.
Code line 3: Declaring lv_emp_name_tbl as table type of VARCHAR2(50)
Code line 4: Declaring lv_emp_name as lv_emp_name_tbl type.
Code line 6: Opening the cursor.
Code line 7: Fetching the cursor using BULK COLLECT with the LIMIT size as 5000 intl
lv_emp_name variable.
Code line 8-11: Setting up FOR loop to print all the record in the collection lv_emp_name.
Code line 12: Using FORALL updating the salary of all the employee by 5000.
Code line 14: Committing the transaction.

TCL Statements in PL/SQL


TCL stands for Transaction Control Statements. It will either save the pending transactions or
roll back the pending transaction. These statements play the vital role because unless the
transaction is saved the changes through DML statements will not be saved in the database.
Below are the different TCL statements.
COMMIT Saves all the pending transaction

ROLLBACK Discard all the pending transaction

SAVEPOINT Creates a point in the transaction till which rollback can be done later

ROLLBACK TO Discard all the pending transaction till the specified <save point>

The transaction will be complete under the following scenarios.

When any of the above statements is issued (except SAVEPOINT)


When DDL statements is issued. (DML are auto-commit statements)
WHEN DCL statements is issued. (DCL are auto-commit statements)

Autonomous Transac on
In PL/SQL, all the modifications done on data will be termed as a transaction. A transaction is
considered as complete when the save/discard is applied to it. If no save/discard is given, then
the transaction will not be considered as complete and the modifications done on the data will
not be made permanent in the server.

Irrespective of a number of modifications done during a session, PL/SQL will treat the whole
modification as a single transaction and saving/discard this transaction affects to the entire
pending changes in that session. Autonomous Transaction provides a functionality to the
developer in which it allows to do changes in a separate transaction and to save/discard that
particular transaction without affecting the main session transaction.

This autonomous transaction can be specified at subprogram level.


To make any subprogram to work in a different transaction, the keyword 'PRAGMA
AUTONOMOUS_TRANSATION' should be given in the declarative section of that block.
It will instruct that compiler to treat this as the separate transaction and saving/discarding
inside this block will not reflect in the main transaction.
Issuing COMMIT or ROLLBACK is mandatory before going out of this autonomous
transaction to the main transaction because at any time only one transaction can be active.
So once we made an autonomous transaction we need to save it and complete the
transaction then only we can move back to the main transaction.
(//cdn.guru99.com/images/PL-SQL/110215_1042_SQLinPLSQL16.png)

Syntax Explanation:

In the above syntax, the block has been made as an autonomous transaction.

Example 1: In this example, we are going to understand how the autonomous transaction is
working.

(//cdn.guru99.com/images/PL-SQL/110215_1042_SQLinPLSQL17.png)

(//cdn.guru99.com/images/PL-SQL/110215_1042_SQLinPLSQL18.png)
Code Explanation:

Code line 2: Declaring l_salary as NUMBER.


Code line 3: Declaring nested_block procedure
Code line 4: Making nested_block procedure as 'AUTONOMOUS_TRANSACTION'.
Code line 7-9: Increasing the salary for employee number 1002 by 15000.
Code line 10: Committing the transaction.
Code line 13-16: Printing the salary details of employee 1001 and 1002 before changes.
Code line 17-19: Increasing the salary for employee number 1001 by 5000.
Code line 20: Calling the nested_block procedure;
Code line 21: Discarding the main transaction.
Code line 22-25: Printing the salary details of employee 1001 and 1002 after changes.
The salary increase for employee number 1001 is not reflected because the main
transaction has been discarded. The salary increase for employee number 1002 is reflected
because that block has been made as a separate transaction and saved at the end.
So irrespective of the save/discard at main transaction the changes at autonomous
transaction has been saved without affecting the main transaction changes.

Summary
In this tutorial, we have learnt how to combine the SQL (/sql.html)in PL/SQL for data
manipulation, Cursor Concepts, Cursor-FOR loop and Bulk collect usages. We have also
discussed the TCL statements and how to save/discard transactions separately.

Prev (/exception-handling-pl-sql.html) Report a Bug (/contact-us.html)

Next (/packages-pl-sql.html)

YOU MIGHT LIKE:

PL-SQL PL-SQL PL-SQL

(/pl-sql-first-program- (/pl-sql-identifiers.html) (/loops-pl-sql.html)


helloworld.html)

(/pl-sql- (/loops-pl-

identifiers.html) sql.html)
PL/SQL Iden ers Loops in PL/SQL
(/pl-sql-identifiers.html) (/loops-pl-sql.html)
(/pl-sql-first-
Identifiers are nothing but a In this chapter, we are going
name that is given for a to see the loop concept in
program-helloworld.html) PL/SQL object. The object PL/SQL and flow of control in
could be... loops. You...
PL SQL First Program: Hello
World Read more Read more

(/pl-sql-first-program-
helloworld.html)
In this tutorial, we will
introduce SQL (/sql.html)plus
and learn how to connect it to
the database. After...
Read more

PL-SQL PL-SQL PL-SQL

(/dynamic-sql-pl-sql.html) (/triggers-pl-sql.html) (/pl-sql-data-types.html)

(/dynamic- (/triggers-pl- (/pl-sql-

sql-pl-sql.html) sql.html) data-types.html)


Dynamic SQL in PL/SQL Triggers in PL/SQL PL/SQL Data Types
(/dynamic-sql-pl-sql.html) (/triggers-pl-sql.html) (/pl-sql-data-types.html)
Dynamic SQL (/sql.html)is a In programs sometimes it is In oracle, each value or
programming methodology required to execute certain constant is assigned with a
for generating and running code followed by certain data type. Any data type is
statements at run-time. It is events and this... associated with the...
mainly... Read more Read more
Read more

PL/SQL Tutorials
Introduction to PL/SQL (/introduction-pl-sql.html)

Blocks in PL/SQL (/blocks-pl-sql.html)

PL/SQL First Program (/pl-sql-first-program-helloworld.html)


PL/SQL First Program (/pl-sql-first-program-helloworld.html)

PL/SQL Data Types (/pl-sql-data-types.html)

Complex Data Types in PL/SQL (/complex-data-types-pl-sql.html)

Decision Making Statements (/pl-sql-decision-making-statements.html)

Loops in PL/SQL (/loops-pl-sql.html)

Procedures and Functions (/subprograms-procedures-functions-pl-sql.html)

Exception Handling in PL/SQL (/exception-handling-pl-sql.html)

SQL in PL/SQL (/sql-pl-sql.html)

Packages in PL/SQL (/packages-pl-sql.html)

Triggers in PL/SQL (/triggers-pl-sql.html)

Object Types in PL/SQL (/object-types-pl-sql.html)

Dynamic SQL in PL/SQL (/dynamic-sql-pl-sql.html)

Nested Blocks in Pl/Sql (/nested-blocks-pl-sql.html)

PL/SQL Identifiers (/pl-sql-identifiers.html)

About
About us (/about-us.html)
Advertise with Us (/advertise-us.html)
Jobs (/freelancing.html)
Privacy Policy (/privacy-policy.html)

Contact Us
Contact us (/contact-us.html)
FAQ (/faq.html)
Write For Us (/become-an-instructor.html)

Follow Us

(https://www.facebook.com/guru99com/)

(https://twitter.com/guru99com)
(https://forms.aweber.com/form/46/724807646.htm)
(https://play.google.com/store/apps/details?
id=com.vector.guru99&hl=en)

Cer ca ons
ISTQB Certification (/istqb.html)
MySQL Certification (/mysql-certification-guide.html)
QTP Certification (/qtp-quality-center-certification-
details.html) Testing Certification (/software-testing-
certification.html)
CTAL Exam (/ctal-certified-exam-preparation.html)

Execute online
Execute Java Online (/try-java-editor.html)
Execute Javascript (/execute-javascript-online.html)
Execute HTML (/execute-html-online.html)
Execute Python (/execute-python-online.html)

Interes ng
Books to Read! (/books.html)
Quiz (/tests.html)

Copyright - Guru99 2017

You might also like