dbms unit5
dbms unit5
Introduction to SQL
Structure Query Language(SQL) is a database query language used for storing and managing
data in Relational DBMS. SQL was the first commercial language introduced for E.F
Codd's Relational model of database. Today almost all RDBMS(MySql, Oracle, Infomix,
Sybase, MS Access) use SQL as the standard database query language. SQL is used to perform
all types of data operations in RDBMS.
SQL Command
SQL defines following ways to manipulate data stored in an RDBMS.
DDL: Data Definition Language
This includes changes to the structure of the table like creation of table, altering table, deleting a
table etc.
All DDL commands are auto-committed. That means it saves all the changes permanently in the
database.
Comman Description
d
Comman Description
d
Comman Description
d
Comman Description
d
3
Command Description
Creating a Database
To create a database in RDBMS, create command is used. Following is the syntax,
CREATE DATABASE <DB_NAME>;
The above command will create a database named Test, which will be an empty schema
without any table.
To create tables in this newly created database, we can again use the create command.
Creating a Table
create command can also be used to create tables. Now when we create a table, we have
to specify the details of the columns of the tables too. We can specify
the names and datatypes of various columns in the create command itself.
create table command will tell the database system to create a new table with the given
table name and column information.
The above command will create a new table with name Student in the current database
with 3 columns, namely student_id, name and age. Where the column student_id will only
store integer, name will hold upto 100 characters and age will again store only integer value.
If you are currently not logged into your database in which you want to create the table then
you can also add the database name along with table name, using a dot operator .
For example, if we have a database with name Test and we want to create a
table Student in it, then we can do so using the following query:
CREATE TABLE Test.Student(
student_id INT,
name VARCHAR(100),
age INT);
Datatype Use
VARCHA used for columns which will be used to store characters and integers, basically a string.
R
CHAR used for columns which will store char values(single character).
TEXT used for columns which will store text which is generally long in length. For example, if you
create a table for storing profile information of a social networking website, then for about
me section you can have a column of type TEXT.
);
The above command will add a new column address to the table student, which will hold data
of type varchar which is nothing but string, of length 200.
ALTER command can also be used to modify data type of any existing column. Following is the
syntax,
ALTER TABLE table_name modify(
column_name datatype
);
Here is an Example for this,
ALTER TABLE student MODIFY(
address varchar(300));
Remember we added a new column address in the beginning? The above command will modify
the address column of the student table, to now hold upto 300 characters.
TRUNCATE command
8
TRUNCATE command removes all the records from a table. But this command will not destroy
the table's structure. When we use TRUNCATE command on a table its (auto-increment)
primary key is also initialized. Following is its syntax,
TRUNCATE TABLE table_name
Here is an example explaining it,
TRUNCATE TABLE student;
The above query will delete all the records from the table student.
In DML commands, we will study about the DELETE command which is also more or less
same as the TRUNCATE command. We will also learn about the difference between the two in
that tutorial.
DROP command
DROP command completely removes a table from the database. This command will also
destroy the table structure and the data stored in it. Following is its syntax,
DROP TABLE table_name
Here is an example explaining it,
DROP TABLE student;
The above query will delete the Student table completely. It can also be used on
Databases, to delete the complete database. For example, to drop a database,
DROP DATABASE Test;
The above query will drop the database with name Test from the system.
RENAME query
RENAME command is used to set a new name for any existing table. Following is the syntax,
RENAME TABLE old_table_name to new_table_name
Here is an example explaining it.
RENAME TABLE student to students_info;
The above query will rename the table student to students_info.
INSERT command
9
Insert command is used to insert data into a table. Following is its general syntax,
INSERT INTO table_name VALUES(data1, data2, ...)
Lets see an example,
Consider a table student with the following fields.
101 Adam 15
101 Adam 15
102 Alex
10
101 Adam 15
102 Alex
103 chris 14
Suppose the column age in our tabel has a default value of 14.
Also, if you run the below query, it will insert default value into the age column, whatever the
default value may be.
INSERT INTO Student VALUES(103,'Chris')
UPDATE command
UPDATE command is used to update any record of data in a table. Following is its general syntax,
UPDATE table_name SET column_name = new_value WHERE some_condition;
WHERE is used to add a condition to any SQL query, we will soon study about it in detail.
101 Adam 15
102 Alex
11
103 chris 14
101 Adam 15
102 Alex 18
103 chris 14
In the above statement, if we do not use the WHERE clause, then our update query will update age
for all the columns of the table to 18.
101 Ada 15
m
102 Alex 18
103 Abhi 17
When we have to update any integer value in a table, then we can fetch and update the value in
the table in a single statement.
For example, if we have to update the age column of student table every year for every student,
then we can simply run the following UPDATE statement to perform the following operation:
UPDATE student SET age = age+1;
As you can see, we have used age = age + 1 to increment the value of age by 1.
NOTE: This style only works for integer values.
DELETE command
DELETE command is used to delete data from a table.
101 Ada 15
m
102 Alex 18
103 Abhi 17
In our student table if we want to delete a single record, we can use the WHERE clause to provide a
condition in our DELETE statement.
DELETE FROM student WHERE s_id=103;
The above command will delete the record where s_id is 103 from the table student.
101 Adam 15
102 Alex 18
COMMIT command
COMMIT command is used to permanently save any transaction into the database.
When we use any DML command like INSERT, UPDATE or DELETE, the changes made by these
commands are not permanent, until the current session is closed, the changes made by
these commands can be rolled back.
To avoid that, we use the COMMIT command to mark the changes as permanent.
Following is commit command's syntax,
COMMIT;
14
ROLLBACK command
This command restores the database to last commited state. It is also used
with SAVEPOINT command to jump to a savepoint in an ongoing transaction.
If we have used the UPDATE command to make some changes into the database, and realise
that those changes were not required, then we can use the ROLLBACK command to rollback
those changes, if they were not commited using the COMMIT command.
Following is rollback command's syntax,
ROLLBACK TO savepoint_name;
SAVEPOINT command
SAVEPOINT command is used to temporarily save a transaction so that you can rollback to
that point whenever required.
Following is savepoint command's syntax,
SAVEPOINT savepoint_name;
In short, using this command we can name the different states of our data in any table and
then rollback to that state using the ROLLBACK command whenever required.
i name
d
1 Abhi
2 Adam
4 Alex
Lets use some SQL queries on the above table and see the results.
INSERT INTO class VALUES(5, 'Rahul');
COMMIT;
SAVEPOINT A;
SAVEPOINT B;
SAVEPOINT C;
i name
d
1 Abhi
2 Adam
4 Alex
5 Abhijit
6 Chris
7 Bravo
Now let's use the ROLLBACK command to roll back the state of data to the savepoint B.
ROLLBACK TO B;
16
id name
1 Abhi
2 Adam
4 Alex
5 Abhijit
6 Chris
Now let's again use the ROLLBACK command to roll back the state of data to the savepoint A
ROLLBACK TO A;
id name
1 Abhi
2 Adam
4 Alex
5 Abhijit
So now you know how the commands COMMIT, ROLLBACK and SAVEPOINT works.
17
System: This includes permissions for creating session, table, etc and all types of other
system privileges.
Object: This includes permissions for any command or query to perform any operation
on the database tables.
GRANT: Used to provide any user access privileges or other priviliges for the database.
sysdba is a set of priviliges which has all the permissions in it. So if we want to provide all
the privileges to any user, we can simply grant them the sysdba permission.
GRANT sysdba TO username
Now we will use the SELECT statement to display data of the table, based on a condition,
which we will add to our SELECT query using WHERE clause.
Let's write a simple SQL query to display the record for student with s_id as 101.
SELECT s_id,
name,
age,
address
FROM student WHERE s_id = 101;
Following will be the result of the above query.
Operator Description
= Equal to
!= Not Equal to
ORDER BY Clause
Order by clause is used with SELECT statement for arranging retrieved data in sorted order.
The Order by clause by default sorts the retrieved data in ascending order. To sort the data in
descending order DESC keyword is used with Order by clause.
21
Syntax of Order By
SELECT column-list|* FROM table-name ORDER BY ASC | DESC;
40 Roha 34 6000
3 n
40 Shane 29 8000
2
40 Tiger 35 8000
5
22
40 Anu 22 9000
1
40 Scott 44 10000
4
40 Scott 44 10000
4
40 Anu 22 9000
1
40 Tiger 35 8000
5
40 Shane 29 8000
2
40 Roha 34 6000
3 n
23
Group By Clause
Group by clause is used to group the results of a SELECT query based on one or more
columns. It is also used with SQL functions to group the result from one or more tables.
Syntax for using Group by in a statement.
SELECT column_name, function(column_name)
FROM table_name
WHERE condition
GROUP BY column_name
Here we want to find name and age of employees grouped by their salaries or in other
words, we will be grouping employees based on their salaries, hence, as a result, we will
get a data set, with unique salaries listed, along side the first employee's name and age to
have that salary.
group by is used to group different row of data together based on any one column.
name age
Rohan 34
Shane 29
Anu 22
name salary
25
Rohan 6000
Shane 8000
Scott 9000
You must remember that Group By clause will always come at the end of the SQL query, just
like the Order by clause.
HAVING Clause
Having clause is used with SQL Queries to give more precise condition for a statement. It is
used to mention condition in Group by based SQL queries, just like WHERE clause is used
with SELECT query.
Syntax for HAVING clause is,
SELECT column_name, function(column_name)
FROM table_name
WHERE column_name condition
GROUP BY column_name
HAVING function(column_name) condition
Suppose we want to find the customer whose previous_balance sum is more than 3000.
We will use the below SQL query,
SELECT *
FROM sale GROUP BY customer
HAVING sum(previous_balance) > 3000
Result will be,
The main objective of the above SQL query was to find out the name of the customer who has
had a previous_balance more than 3000, based on all the previous sales made to the customer,
hence we get the first row in the table for customer Alex.
DISTINCT keyword
The distinct keyword is used with SELECT statement to retrieve unique values from the
table. Distinct removes all the duplicate records while retrieving records from any table in the
database.
40 Anu 22 5000
27
40 Shane 29 8000
2
40 Roha 34 10000
3 n
40 Scott 44 10000
4
40 Tiger 35 8000
5
salary
5000
8000
10000
28
SQL Index
Index in sql is created on existing tables to retrieve the rows quickly.
When there are thousands of records in a table, retrieving information will take a
long time. Therefore indexes are created on columns which are accessed
frequently, so that the information can be retrieved quickly. Indexes can be created
on a single column or a group of columns. When a index is created, it first sorts the
data and then it assigns a ROWID for each row.
Syntax to create Index:
CREATE INDEX index_name
ON table_name (column_name1,column_name2...);
Syntax to create SQL unique Index:
CREATE UNIQUE INDEX index_name
ON table_name (column_name1,column_name2...);
index_name is the name of the INDEX.
table_name is the name of the table to which the indexed column belongs.
column_name1, column_name2.. is the list of columns which make up the
INDEX.
In Oracle there are two types of SQL index namely, implicit and explicit.
Implicit Indexes:
They are created when a column is explicity defined with PRIMARY KEY, UNIQUE
KEY Constraint.
Explicit Indexes:
They are created using the "create index.. " syntax.
SQL Notes:
29
1) Even though sql indexes are created to access the rows in the table quickly,
they slow down DML operations like INSERT, UPDATE, DELETE on the table,
because the indexes and tables both are updated along when a DML operation is
performed. So use indexes only on columns which are used to search the table
frequently.
2) Is is not required to create indexes on table which have less data.
3) In oracle database you can define up to sixteen (16) columns in an INDEX.
Views
A VIEW is a virtual table, through which a selective portion of the data from one or
more tables can be seen. Views do not contain data of their own. They are used to
restrict access to the database or to hide data complexity. A view is stored as a
SELECT statement in the database. DML operations on a view like INSERT,
UPDATE, DELETE affects the data in the original table upon which the view is
based.
The Syntax to create a sql view is
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.
1. The SELECT statement which is used to create the view should not include
GROUP BY clause or ORDER BY clause.
2. The SELECT statement should not have the DISTINCT keyword.
3. The View should have all NOT NULL values.
4. The view should not be created using nested queries or complex queries.
5. 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,..
30
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:
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.
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.
Dropping Views
Obviously, where you have a view, you need a way to drop the view if it is
no longer needed. The syntax is very simple and is given below −
DROP VIEW view_name;
View resolution
Tables and Views both have definitions such as the columns of the table, or the columns in a view. All columns have given
data types.
Tables hold row data for a given set of columns spread across the physical pages stored on a disk.
Views have definitions similar to tables. However, they do not hold row data. The data found in a view is populated by an
underlying query that is reading from tables that hold row data.
33
When you read from a view, or join a view to an existing query the SQL server will then execute the query in the view and
join it to your data set. When it does that, that would be view resolution.
Here unlike views, materialized views mv_Design_Emp and mv_Test_Emp are two separate
copies of tables and stored in the different data block of memory.
We can have SELECT query on materialized views as we do with any other tables. Since this
view is created and stored in advance, it might not have latest records from the table. That means
if any records are inserted into the table after a materialized view is created and that inserted
record is a valid candidate to be in materialized view, then it will not be shown in the
materialized view. Materialized view needs to be refreshed to get the latest record.
Views can be created referencing tables and views only in the current database.
A view name must not be the same as any table owned by that user.
You can build views on other views and on procedures that reference views.
Rules or DEFAULT definitions can't be associated with views.
Only INSTEAD OF triggers can be associated with views.
The query that defines the view cannot include the ORDER BY, COMPUTE, or COMPUTE BY clauses
You cannot define full-text index definitions for views.
You cannot create temporary views
You cannot create views on temporary tables.
- Since a view is a virtual table – columns of the view cannot be renamed. To change anything in the v
dropped and create again.
- The select statement on the view cannot contain ORDER BY or INTO TEMP
- When a table or view is dropped, any views in the same database are also dropped.
- It is not possible to create an index on a view
- It is not possible to use DELETE to update a view that is defined as a join.
A database view allows you to simplify complex queries: a database view is defined
by an SQL statement that associates with many underlying tables. You can use
database view to hide the complexity of underlying tables to the end-users and
external applications. Through a database view, you only have to use simple SQL
statements instead of complex ones with many joins.
A database view helps limit data access to specific users. You may not want a subset
of sensitive data can be queryable by all users. You can use a database view to
expose only non-sensitive data to a specific group of users.
A database view provides extra security layer. Security is a vital part of any relational
database management system. The database view offers additional protection for a
database management system. The database view allows you to create the read-only
view to expose read-only data to specific users. Users can only retrieve data in read-
only view but cannot update it.
A database view enables backward compatibility. Suppose you have a central
database, which many applications are using it. One day, you decide to redesign the
database to adapt to the new business requirements. You remove some tables and
create new tables, and you don’t want the changes to affect other applications. In this
scenario, you can create database views with the same schema as the legacy tables
that you will remove.
Performance: querying data from a database view can be slow especially if the view is
created based on other views.
Tables dependency: you create a view based on underlying tables of the database.
Whenever you change the structure of these tables that view associated with, you
have to change the view as well.
The ANY operator returns true if any of the subquery values meet the condition.
The ALL operator returns true if all of the subquery values meet the condition.
ANY Syntax
SELECT column_name(s)
FROM table_name
WHERE column_name operator ANY
(SELECT column_name FROM table_name WHERE condition);
ALL Syntax
SELECT column_name(s)
FROM table_name
WHERE column_name operator ALL
(SELECT column_name FROM table_name WHERE condition);
SQL | EXISTS
The EXISTS condition in SQL is used to check whether the result of a correlated nested query is empty (contains no
tuples) or not. The result of EXISTS is a boolean value True or False. It can be used in a SELECT, UPDATE,
INSERT or DELETE statement.
Syntax:
SELECT column_name(s)
FROM table_name
WHERE EXISTS
(SELECT column_name(s)
FROM table_name
WHERE condition);
Examples:
Consider the following two relation “Customers” and “Orders”.
37
Queries
1. Using EXISTS condition with SELECT statement
To fetch the first and last name of the customers who placed atleast one order.
Output:
Output
Integrity Constraints
o Integrity constraints are a set of rules. It is used to maintain the quality of information.
o Integrity constraints ensure that the data insertion, updating, and other processes have to be performed in such
a way that data integrity is not affected.
o Thus, integrity constraint is used to guard against accidental damage to the database.
1. Domain constraints
o Domain constraints can be defined as the definition of a valid set of values for an attribute.
o The data type of domain includes string, character, integer, time, date, currency, etc. The value of the attribute
must be available in the corresponding domain.
Example:
40
Example:
Example:
41
4. Key constraints
o Keys are the entity set that is used to identify an entity within its entity set uniquely.
o An entity set can have multiple keys, but out of which one key will be the primary key. A primary key can contain
a unique and null value in the relational table.
Example:
Transaction
o The transaction is a set of logically related operation. It contains a group of tasks.
42
o A transaction is an action or series of actions. It is performed by a single user to perform operations for accessing
the contents of the database.
Example: Suppose an employee of bank transfers Rs 800 from X's account to Y's account. This small transaction contains
several low-level tasks:
X's Account
1. Open_Account(X)
2. Old_Balance = X.balance
3. New_Balance = Old_Balance - 800
4. X.balance = New_Balance
5. Close_Account(X)
Y's Account
1. Open_Account(Y)
2. Old_Balance = Y.balance
3. New_Balance = Old_Balance + 800
4. Y.balance = New_Balance
5. Close_Account(Y)
Operations of Transaction:
Following are the main operations of transaction:
Read(X): Read operation is used to read the value of X from the database and stores it in a buffer in main memory.
Write(X): Write operation is used to write the value back to the database from the buffer.
Let's take an example to debit transaction from an account which consists of following operations:
1. 1. R(X);
2. 2. X = X - 500;
3. 3. W(X);
o The first operation reads X's value from database and stores it in a buffer.
o The second operation will decrease the value of X by 500. So buffer will contain 3500.
o The third operation will write the buffer's value to the database. So X's final value will be 3500.
But it may be possible that because of the failure of hardware, software or power, etc. that transaction may fail before
finished all the operations in the set.
For example: If in the above transaction, the debit transaction fails after executing operation 2 then X's value will remain
4000 in the database which is not acceptable by the bank.
PL/SQL Introduction
PL/SQL is a block structured language that enables developers to combine the power of
SQL with procedural statements. All the statements of a block are passed to oracle
engine all at once which increases processing speed and decreases the traffic.
Disadvantages of SQL:
SQL doesn’t provide the programmers with a technique of condition checking, looping and
branching.
SQL statements are passed to Oracle engine one at a time which increases traffic and
decreases speed.
SQL has no facility of error checking during manipulation of data.
Features of PL/SQL:
1. PL/SQL is basically a procedural language, which provides the functionality of decision
making, iteration and many more features of procedural programming languages.
2. PL/SQL can execute a number of queries in one block using single command.
3. One can create a PL/SQL unit such as procedures, functions, packages, triggers, and
types, which are stored in the database for reuse by applications.
4. PL/SQL provides a feature to handle the exception which occurs in PL/SQL block known
as exception handling block.
5. Applications written in PL/SQL are portable to computer hardware or operating system
where Oracle is operational.
6. PL/SQL Offers extensive error checking.
44
SQL is a single query that is used to perform DML PL/SQL is a block of codes that used to write the
It is declarative, that defines what needs to be PL/SQL is procedural that defines how the things
Typically, each block performs a logical action in the program. A block has the
following structure:
DECLARE
declaration statements;
BEGIN
executable statements
EXCEPTIONS
exception handling statements
45
END;
Declare section starts with DECLARE keyword in which variables, constants, records as
cursors can be declared which stores data temporarily. It basically consists definition of
PL/SQL identifiers. This part of the code is optional.
Execution section starts with BEGIN and ends with END keyword.This is a mandatory
section and here the program logic is written to perform any task like loops and conditional
statements. It supports all DML commands, DDL commands and SQL*PLUS built-in
functions as well.
Exception section starts with EXCEPTION keyword.This section is optional which contains
statements that are executed when a run-time error occurs. Any exceptions can be
handled in this section.
PL/SQL identifiers
There are several PL/SQL identifiers such as variables, constants, procedures, cursors,
triggers etc.
1. Variables:
Like several other programming languages, variables in PL/SQL must be declared
prior to its use. They should have a valid name and data type as well.
Syntax for declaration of variables:
variable_name datatype [NOT NULL := value ];
Example to show how to declare variables in PL/SQL :
SQL> SET SERVEROUTPUT ON;
SQL> DECLARE
var1 INTEGER;
var2 REAL;
var3 varchar2(20) ;
BEGIN
null;
END;
Output:
PL/SQL procedure successfully completed.
Explanation:
SET SERVEROUTPUT ON: It is used to display the buffer used by the dbms_output.
var1 INTEGER : It is the declaration of variable, named var1 which is of integer type.
There are many other data types that can be used like float, int, real, smallint, long
46
etc. It also supports variables used in SQL as well like NUMBER(prec, scale),
varchar, varchar2 etc.
PL/SQL procedure successfully completed.: It is displayed when the code is
compiled and executed successfully.
Slash (/) after END;: The slash (/) tells the SQL*Plus to execute the block.
SQL> DECLARE
var1 INTEGER := 2 ;
BEGIN
null;
END;
Output:
PL/SQL procedure successfully completed.
Explanation:
Assignment operator (:=) : It is used to assign a value to a variable.
2. Displaying Output:
The outputs are displayed by using DBMS_OUTPUT which is a built-in package
that enables the user to display output, debugging information, and send
messages from PL/SQL blocks, subprograms, packages, and triggers.
Let us see an example to see how to display a message using PL/SQL :
SQL> SET SERVEROUTPUT ON;
SQL> DECLARE
BEGIN
dbms_output.put_line(var);
END;
47
Output:
I love DBMS
3. Using Comments:
Like in many other programming languages, in PL/SQL also, comments can be put
within the code which has no effect in the code. There are two syntaxes to create
comments in PL/SQL :
Single Line Comment: To create a single line comment , the symbol – – is used.
Multi Line Comment: To create comments that span over several lines, the
symbol /* and */ is used.
Example to show how to create comments in PL/SQL :
_
SQL> SET SERVEROUTPUT ON;
SQL> DECLARE
BEGIN
dbms_output.put_line(var);
END;
Output:
I love DBMS
SQL> DECLARE
a number := &a;
b varchar2(30) := &b;
BEGIN
null;
END;
Output:
Enter value for a: 24
old 2: a number := &a;
new 2: a number := 24;
Enter value for b: 'GeeksForGeeks'
old 3: b varchar2(30) := &b;
new 3: b varchar2(30) := 'GeeksForGeeks';
5. (***) Let us see an example on PL/SQL to demonstrate all above concepts in one
single block of code.
--PL/SQL code to print sum of two numbers taken from the user.
SQL> DECLARE
a integer := &a ;
b integer := &b ;
c integer ;
BEGIN
c := a + b ;
END;
Sum of 2 and 3 is = 5
Control Structures
PL/SQL Control Structures are used to control flow of execution. PL/SQL provides different kinds of statements to provide such type of
procedural capabilities.These statements are almost same as that of provided by other languages.
The flow of control statements can be classified into the following categories:
Conditional Control
50
Iterative Control
Sequential Control
Conditional Control :
PL/SQL allows the use of an IF statement to control the execution of a block of code.
In PL/SQL, the IF -THEN - ELSIF - ELSE - END IF construct in code blocks allow specifying certain conditions under which a specific block of code
should be executed.
Syntax:
Example:
create file named "condi.sql"
DECLARE
a Number := 30; b Number;
BEGIN
IF a > 40 THEN
b := a - 40;
DBMS_OUTPUT.PUT_LINE('b=' || b);
ELSE
b := 0;
DBMS_OUTPUT.PUT_LINE('b=' || b);
END IF;
END;
/
Output:
Run SQL Command Line
SQL>set serveroutput on
SQL>start d://condi.sql
b=70
Iterative Control :
Iterative control indicates the ability to repeat or skip sections of a code block.
A loop marks a sequence of statements that has to be repeated. The keyword loop has to be placed before the first statement in the sequence
of statements to be repeated, while the keyword end loop is placed immediately after the last statement in the sequence.
51
Once a loop begins to execute, it will go on forever. Hence a conditional statement that controls the number of times a loop is executed always
accompanies loops.
PL/SQL supports the following structures for iterative control:
Simple loop :
In simple loop, the key word loop should be placed before the first statement in the sequence and the keyword end loop should be written at
the end of the sequence to end the loop.
Syntax:
Loop
< Sequence of statements >
End loop;
Example:
create file named it.sql
DECLARE
i number := 0;
BEGIN
LOOP
dbms_output.put_line ('i = '||i);
i:=i+1;
EXIT WHEN i>=11;
END LOOP;
END;
/
Output:
Run SQL Command Line
SQL>set serveroutput on
SQL>start d://it.sql
i = 0
i = 1
i = 2
i = 3
i = 4
i = 5
i = 6
i = 7
i = 8
i = 9
52
i = 10
PL/SQL successfully completed.
WHILE loop
The while loop executes commands in its body as long as the condtion remains true
Syntax :
Example :
find reverse of given number using while loop
DECLARE
num Number(3) :=123;
ans Number(3) :=0;
i Number(3) :=0;
BEGIN
WHILE num != 0
LOOP
i:=mod(num,10);
ans:=(ans * 10 ) + i;
num:=floor(num/10);
END LOOP;
dbms_output.put_line('reverse of given number is: ' || ans);
END;
/
Output :
Run SQL Command Line
SQL>set serveroutput on
SQL>start d://rev.sql
The FOR loop can be used when the number of iterations to be executed are known.
Syntax :
The variable in the For Loop need not be declared. Also the increment value cannot be specified. The For Loop variable is always incremented
by 1.
Example :
DECLARE
i number ;
BEGIN
FOR i IN 1 .. 10
LOOP
dbms_output.put_line ('i = '||i);
END LOOP;
END;
/
Output :
Run SQL Command Line
SQL>set serveroutput on
SQL>start d://it.sql
i = 1
i = 2
i = 3
i = 4
i = 5
i = 6
i = 7
i = 8
i = 9
i = 10
PL/SQL successfully completed.
Sequential Control :
The GOTO Statement
The GOTO statement changes the flow of control within a PL/SQL block. This statement allows execution of a section of code, which is not in
the normal flow of control. The entry point into such a block of code is marked using the tags «userdefined name». The GOTO statement can
then make use of this user-defined name to jump into that block of code for execution.
54
Syntax :
GOTO jump;
....
<<jump>>
Example :
DECLARE
BEGIN
dbms_output.put_line ('code starts');
dbms_output.put_line ('before GOTO statement');
GOTO down;
dbms_output.put_line ('statement will not get executed..');
<<down>>
dbms_output.put_line ('flow of execution jumped here.');
END;
/
Output :
Run SQL Command Line
SQL>set serveroutput on
SQL>start d://a.sql
code starts
before gotostatements
flow of execution jumped here.
Exceptions
An Exception is an error situation, which arises during program execution. When an error occurs exception is raised, normal execution is
stopped and control transfers to exceptionhandling part.
Exception handlers are routines written to handle the exception. The exceptions can be internally defined (system-defined or pre-defined) or
User-defined exception.
Syntax:
EXCEPTION
WHEN <ExceptionName> THEN
<User Defined Action To Be Carried Out>
55
Predefined exception :
Predefined exception is raised automatically whenever there is a violation of Oracle coding rules. Predefined exceptions are those like
ZERO_DIVIDE, which is raised automatically when we try to divide a number by zero. Other built-in exceptions are given below. You can handle
unexpected Oracle errors using OTHERS handler. It can handle all raised exceptions that are not handled by any other handler. It must always
be written as the last handler in exception block.
DUP_VAL_ON_INDEX When you try to insert a duplicate value into a unique column.
TOO_MANY_ROWS When a select query returns more than one row and the destination variable can take only
single value.
Predefined exception handlers are declared globally in package STANDARD. Hence we need not have to define them rather just use them.
The biggest advantage of exception handling is it improves readability and reliability of the code. Errors from many statements of code can be
handles with a single handler. Instead of checking for an error at every point we can just add an exception handler and if any exception is raised
it is handled by that.
For checking errors at a specific spot it is always better to have those statements in a separate begin – end block.
Example:
DECLARE
N number;
BEGIN
N:=10/0;
EXCEPTION WHEN ZERO_DIVIDE THEN
DBMS_OUTPUT.PUT_LINE('divide by zero error occures..');
END;
/
Output:
56
User-defined Exceptions :
The technique that is used is to bind a numbered exception handler to a name using Pragma
Exception_init (). This binding of a numbered exception handler, to a name (i.e. a String), is done in the
Declare section of a PL/SQL block.
The Pragma action word is a call to a pre-compiler, which immediately binds the numbered exception
handler to a name when encountered.
The function Exception_init() takes two parameters the first is the user defined exception name the
second is the Oracle engine's exception number. These lines will be included in the Declare section of
the PL/SQL block.
The user defined exception name must be the statement that immediately precedes the Pragma
Exception_init() statement.
Syntax:
DECLARE
< ExceptionName > EXCEPTION ;
PRAGMA EXCEPTION_INIT (< ExceptionName >, <ErrorCodeNo>);
BEGIN
Using this technique it is possible to bind appropriate numbered exception handlers to names
and use these names in the Exception section of a PL/SQL block. When this is done the default
exception handling code of the exception handler is overridden and the user-defined exception
handling code is executed .
Syntax:
DECLARE
< ExceptionName > EXCEPTION ;
PRAGMA EXCEPTION_INIT (< ExceptionName >, <ErrorCodeNo>);
BEGIN
. . . .
EXCEPTION
WHEN < ExceptionName > THEN
< Action >
END;
Example:
Create table named emp have column like id with notnull constraint,name and etc.
DECLARE
57
e_MissingNull EXCEPTION;
PRAGMA EXCEPTION_INIT(e_MissingNull, -1400);
BEGIN
INSERT INTO emp(id) VALUES (NULL);
EXCEPTION
WHEN e_MissingNull then
DBMS_OUTPUT.put_line('ORA-1400 occurred');
END;
/
Output:
Run SQL Command Line
SQL>set serveroutput on
SQL>start D://e.sql
ORA-1400 occurred
PL/SQL procedure successfully completed.
Syntax:
DECLARE
< ExceptionName > EXCEPTION ;
BEGIN
<SQL Sentence >;
IF < Condition > THEN
RAISE <ExceptionName>;
END IF;
EXCEPTION
WHEN <ExceptionName>THEN {User Defined Action To Be Taken};
END;
Example:
DECLARE
ex EXCEPTION;
BEGIN
IF TO_CHAR(SYSDATE,'DY')=='SUN' THEN
RAISE ex;
END IF;
EXCEPTION
58
WHEN ex then
DBMS_OUTPUT.put_line('No Transcations Today');
END;
/
Output:
Run SQL Command Line
SQL>set serveroutput on
SQL>start D://ex.sql
No Transactions Today
PL/SQL procedure successfully completed.
Cursors
A cursor is a temporary work area created in the system memory when a SQL statement is
executed. A cursor contains information on a select statement and the rows of data accessed
by it. This temporary work area is used to store the data retrieved from the database, and
manipulate this data. A cursor can hold more than one row, but can process only one row at a
time. The set of rows the cursor holds is called the active set.
There are two types of cursors in PL/SQL :
1. Implicit cursors.
2. Explicit cursors.
Both implicit and explicit cursors have the same functionality, but they differ in the way they
are accessed.
Cursor Attributes
Name Description
%NOTFOUND Returns TRUE if record was not fetched successfully, FALSE otherwise.
%ROWCOUNT Returns number of records fetched from cursor at that point in time.
Implicit cursors :
These are created by default when DML statements like, INSERT, UPDATE, and DELETE
statements are executed. They are also created when a SELECT statement that returns just one
row is executed.
When you execute DML statements like DELETE, INSERT, UPDATE and SELECT statements,
implicit statements are created to process these statements.
Oracle provides few attributes called as implicit cursor attributes to check the status of DML
operations. The cursor attributes available are %FOUND, %NOTFOUND, %ROWCOUNT, and
%ISOPEN.
For example, When you execute INSERT, UPDATE, or DELETE statements the cursor attributes
tell us whether any rows are affected and how many have been affected. When a SELECT...
INTO statement is executed in a PL/SQL Block, implicit cursor attributes can be used to find out
whether any row has been returned by the SELECT statement. PL/SQL returns an error when no
data is selected.
Consider the PL/SQL Stock that uses implicit cursor attributes as shown below:
Example:
DECLARE
Eid number(3);
BEGIN
UPDATE emp set eid=&eid where salary=&salary; eid:=sql%rowcount;
IF SQL%found then
dbms_output.put_line('success');
ELSE
dbms_output.put_line ( ' not' ) ;
END IF;
dbms_output.put_line( 'rowcount'||eid);
END;
/
Output:
Run SQL Command Line
SQL>START D://c.sql
success
PL/SQL Procedure successfully completed.
Explicit Cursors :
They must be created when you are executing a SELECT statement that returns more than one
row. Even though the cursor stores multiple records, only one record can be processed at a
time, which is called as current row. When you fetch a row the current row position moves to
next row.
An explicit cursor is defined in the declaration section of the PL/SQL Block. It is created on a
60
SELECT Statement which returns more than one row. We can provide a suitable name for the
cursor.
Syntax:
Syntax:
Syntax:
OPEN cursor_name;
Syntax:
Syntax:
CLOSE cursor__name;
61
When a cursor is opened, the first row becomes the current row. When the data is fetched it is
copied to the record or variables and the logical pointer moves to the next row and it becomes
the current row. On every fetch statement, the pointer moves to the next row. If you want to
fetch after the last row, the program will throw an error. When there is more than one row in a
cursor we can use loops along with explicit cursor attributes to fetch all the records.
1. We can fetch the rows in a cursor to a PL/SQL Record or a list of variables created in the
PL/SQL Block.
2. If you are fetching a cursor to a PL/SQL Record, the record should have the same
structure as the cursor.
3. If you are fetching a cursor to a list of variables, the variables should be listed in the
same order in the fetch statement as the columns are present in the cursor.
Syntax:
DECLARE
variables;
records;
create a cursor;
BEGIN
OPEN cursor;
FETCH cursor;
process the records;
CLOSE cursor;
END;
Example:
DECLARE
CURSOR er IS select eid,name from emp order by name ;
id emp.eid%type;
ename emp.name%type;
BEGIN
OPEN er;
Loop
FETCH er into id,ename;
Exit when er%notfound;
dbms_output.put_line (id || ename);
62
end loop;
close er;
END;
/
Output:
Run SQL Command Line
SQL>start D://ec.sql
1||parimal
2||preet
PL/SQL Procedure successfully completed.
Syntax:
Parameterized Cursors :
Oracle allows to pass parameters to cursors that can be used to provide condition with WHERE
clause.If parameters are passed to curso, that cursor is called a parameterized cursors.
Syntax:
Syntax:
between a procedure and a function is, a function must always return a value, but a procedure
may or may not return a value.
Procedures:
A procudure is a named PL/SQL block which performs one or more specific task. This is similar
to a procedure in other programming languages. A procedure has a header and a body.
The header consists of the name of the procedure and the parameters or variables passed to
the procedure.
The body consists or declaration section, execution section and exception section similar to a
general PL/SQL Block. A procedure is similar to an anonymous PL/SQL Block but it is named for
repeated usage.
Parameters Description
IN type These types of parameters are used to send values to stored procedures.
OUT type These types of parameters are used to get values from stored procedures. This is
similar to a return type in functions.
IN OUT These types of parameters are used to send values and get values from stored
type procedures.
Syntax:
Exception section
END
IS - marks the beginning of the body of the procedure and is similar to DECLARE in anonymous
PL/SQL Blocks. The code between IS and BEGIN forms the Declaration section.
The syntax within the brackets [ ] indicate they are optional. By using CREATE OR REPLACE
together the procedure is created if no other procedure with the same name exists or the
existing procedure is replaced with the current code.
How to execute a Procedure?
There are two ways to execute a procedure :
Example:
create table named emp have two column id and salary with number datatype.
Output:
Run SQL Command Line
SQL>set serveroutput on
SQL>start D://pr.sql
Procedure created.
SQL>exec p1(5,4);
VALUE INSERTED.
PL/SQL procudere successfully completed.
Functions:
65
A function is a named PL/SQL Block which is similar to a procedure. The major difference
between a procedure and a function is, a function must always return a value, but a procedure
may or may not return a value.
Syntax:
RETURN TYPE: The header section defines the return type of the function. The return datatype
can be any of the oracle datatype like varchar, number etc.
The execution and exception section both should return a value which is of the datatype
defined in the header section.
How to execute a Function?
A function can be executed in the following ways.
Example:
Output:
66
SQL>start D://fun.sql
Function created.
In the example we are retrieving the ‘salary’ of employee with id 2 to variable ‘sal’.
The return type of the function is number.
Destroying procedure and function :
Syntax:
Procedures VS Functions:
= n*(n-1)*(n-2)*(n-3)... 1
num number;
factorial number;
RETURN number
IS
f number;
BEGIN
IF x=0 THEN
f := 1;
ELSE
f := x * fact(x-1);
END IF;
RETURN f;
END;
BEGIN
num:= 6;
factorial := fact(num);
END;
When the above code is executed at the SQL prompt, it produces the
following result −
Factorial 6 is 720
Packages
"A package is a container for other database objects."
A package can hold other database objects such as variables ,
consatants,cursors,exceptions,procedures,functions and sub-programs.
68
Package specification:
The package specification contains:
This means that procedures, functions, variables, constants, cursors and exceptions and other
objects, declared in a package are accessible from anywhere in the package.
Therefore, all the information a package needs, to execute a stored subprogram, is contained in
the package specifications itself.
Syntax:
Example:
create package operation that contains procedure 'add' and function 'sub'.
Output:
Run SQL Command Line
SQL>start D://pac.sql
Package created.
69
Package Body :
The body of a package contains the definition of public objects that are declared in the
specification.
The body can also contain other object declarations that are private to the package.
The objects declared privately in the package body are not accessible to other objects outside
the package.
Unlike package specification, the package body can contain subprogram bodies.
After the package is written, debugged, compiled and stored in the database applications can
reference the package's types, call its subprograms, use its cursors, or raise its exceptions.
Syntax:
Example:
Output:
70
SQL>start D://pacbody.sql
Package body created.
Advantages of package:
Triggers
A trigger is a pl/sql block structure which is fired when a DML statements like Insert, Delete,
Update is executed on a database table. A trigger is triggered automatically when an associated
DML statement is executed.
Syntax:
Statement Description
CREATE [OR This clause creates a trigger with the given name or overwrites an existing
REPLACE ] TRIGGER trigger with the same name.
trigger_name
{BEFORE | AFTER | This clause indicates at what time the trigger should get fired. i.e for
INSTEAD OF } example: before or after updating a table. INSTEAD OF is used to create a
trigger on a view. before and after cannot be used to create a trigger on a
view.
{INSERT [OR] | This clause determines the triggering event. More than one triggering
UPDATE [OR] | events can be used together separated by OR keyword. The trigger gets
DELETE} fired at all the specified triggering event.
[OF col_name] This clause is used with update triggers. This clause is used when you
want to trigger an event only when a specific column is updated.
CREATE [OR This clause creates a trigger with the given name or overwrites an existing
REPLACE ] TRIGGER trigger with the same name.
trigger_name
[ON table_name] This clause identifies the name of the table or view to which the trigger is
associated.
[REFERENCING OLD This clause is used to reference the old and new values of the data being
AS o NEW AS n] changed. By default, you reference the values as :old.column_name or
:new.column_name. The reference names can also be changed from old
(or new) to any other user-defined name. You cannot reference old
values when inserting a record, or new values when deleting a record,
because they do not exist.
[FOR EACH ROW] This clause is used to determine whether a trigger must fire when each
row gets affected ( i.e. a Row Level Trigger) or just once when the entire
sql statement is executed(i.e.statement level Trigger).
72
WHEN (condition) This clause is valid only for row level triggers. The trigger is fired only for
rows that satisfy the condition specified.
Example:
Output:
Run SQL Command Line
SQL>start D://t.sql
Trigger created.
Types of Triggers
A trigger's type is defined by the type of triggering transaction and by the level at which the
trigger is executed. Oracle has the following types of triggers depending on the different
applications.
For example, if an UPDATE statement updates multiple rows of a table, a row trigger is fired
once for each row affected by the UPDATE statement.
If the triggering statement affects no rows, the trigger is not executed at all.
Row level triggers are created using the FOR EACH ROW clause in the CREATE TRIGGER
command.
Application:
Consider a case where our requirement is to prevent updation of
empno 100 record cannot be updated, then whenever UPDATE statement update records,
there must be PL/SQL block that will be fired automatically by UPDATE statement to check
that it must not be 100, so we have to use Row level Triggers for that type of applications.
Application:
Consider a case where our requirement is to prevent the DELETE operation during
Sunday. For this whenever DELETE statement deletes records, there must be PL/SQL block that
will be fired only once by DELETE statement to check that day must not be Sunday by
referencing system date, so we have to use Statement level Trigger for which fires only once for
above application.
Before Trigger :
Since triggers are executed by events, they may be set to occur immediately before or after
those events.
When a trigger is defined, you can specify whether the trigger must occur before or after the
triggering event i.e. INSERT, UPDATE, or DELETE commands.
BEFORE trigger execute the trigger action before the triggering statement.
These types of triggers are commonly used in the following situation:
1. BEFORE triggers are used when the trigger action should determine whether or not the
triggering statement should be allowed to complete.
2. By using a BEFORE trigger, you can eliminate unnecessary processing of the triggering
statement.
74
3. For example: To prevent deletion on Sunday, for this we have to use Statement level
before trigger on DELETE statement.
4. BEFORE triggers are used to derive specific column values before completing a triggering
INSERT or UPDATE statement.
After Trigger :
AFTER trigger executes the trigger action after the triggering statement is executed.
AFTER triggers are used when you want the triggering statement to complete before executing
the trigger action.
For example: To perform cascade delete operation, it means that user delete the record fro one
table, but the corresponding records in other tables are delete automatically by a trigger which
fired after the execution of delete statement issued by the user.
When combining the different types of triggering actions, there are mainly 4 possible Valid
trigger types available to us.
Dropping Triggers :
Triggers may be dropped via the drop trigger command. In order to drop a trigger, you must
either own the trigger or have the DROP ANY TRIGGER system privilege.
Syntax:
Example:
Run SQL Command Line
Trigger dropped.