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

dbms unit5

Uploaded by

sirisha
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
26 views

dbms unit5

Uploaded by

sirisha
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 74

1

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

create to create new table or database

alter for alteration

truncate delete data from table

drop to drop a table

rename to rename a table

DML: Data Manipulation Language


DML commands are used for manipulating the data stored in the table and not the table itself.
DML commands are not auto-committed. It means changes are not permanent to database, they
can be rolled back.
2

Comman Description
d

insert to insert a new row

update to update existing row

delete to delete a row

merge merging two rows or two tables

TCL: Transaction Control Language


These commands are to keep a check on other commands and their affect on the database. These
commands can annul changes made by other commands by rolling the data back to its original
state. It can also make any temporary change permanent.

Comman Description
d

commit to permanently save

rollback to undo change

savepoint to save temporarily

DCL: Data Control Language


Data control language are the commands to grant and take back authority from any database
user.

Comman Description
d
3

grant grant permission of right

revoke take back permission.

DQL: Data Query Language


Data query language is used to fetch data from tables based on conditions that we can easily
apply.

Command Description

select retrieve records from one or more table

SQL: create command


create is a DDL SQL command used to create a table or a database in relational database
management system.

Creating a Database
To create a database in RDBMS, create command is used. Following is the syntax,
CREATE DATABASE <DB_NAME>;

Example for creating Database


CREATE DATABASE Test;

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.

Following is the syntax,


4

CREATE TABLE <TABLE_NAME>


(
column_name1 datatype1,
column_name2 datatype2,
column_name3 datatype3,
column_name4 datatype4
);

create table command will tell the database system to create a new table with the given
table name and column information.

Example for creating Table


CREATE TABLE Student(
student_id INT,
name VARCHAR(100),
age INT);

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

Most commonly used datatypes for Table columns


Here we have listed some of the most commonly used datatypes used for columns in
tables.

Datatype Use

INT used for columns which will store integer values.


5

FLOAT used for columns which will store float values.

DOUBLE used for columns which will store float values.

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

DATE used for columns which will store date values.

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.

SQL: ALTER command


alter command is used for altering the table structure, such as,

 to add a column to existing table


 to rename any existing column
 to change datatype of any column or to modify its size.
 to drop a column from the table.

ALTER Command: Add a new Column


Using ALTER command we can add a column to any existing table. Following is the syntax,
ALTER TABLE table_name ADD(
column_name datatype);
Here is an Example for this,
ALTER TABLE student ADD(
address VARCHAR(200)
6

);
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: Add multiple new


Columns
Using ALTER command we can even add multiple new columns to any existing table. Following
is the syntax,
ALTER TABLE table_name ADD(
column_name1 datatype1,
column-name2 datatype2,
column-name3 datatype3);
Here is an Example for this,
ALTER TABLE student ADD(
father_name VARCHAR(60),
mother_name VARCHAR(60),
dob DATE);
The above command will add three new columns to the student table

ALTER Command: Add Column with


default value
ALTER command can add a new column to an existing table with a default value too. The default
value is used when no value is inserted in the column. Following is the syntax,
ALTER TABLE table_name ADD(
column-name1 datatype1 DEFAULT some_value
);
Here is an Example for this,
ALTER TABLE student ADD(
dob DATE DEFAULT '01-Jan-99'
);
The above command will add a new column with a preset default value to the table student.

ALTER Command: Modify an existing


Column
7

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.

ALTER Command: Rename a Column


Using ALTER command you can rename an existing column. Following is the syntax,
ALTER TABLE table_name RENAME
old_column_name TO new_column_name;
Here is an example for this,
ALTER TABLE student RENAME
address TO location;
The above command will rename address column to location.

ALTER Command: Drop a Column


ALTER command can also be used to drop or remove columns. Following is the syntax,
ALTER TABLE table_name DROP(
column_name);
Here is an example for this,
ALTER TABLE student DROP(
address);
The above command will drop the address column from the table student.

Truncate, Drop or Rename a Table


In this tutorial we will learn about the various DDL commands which are used to re-define
the tables.

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.

Using INSERT SQL command


Data Manipulation Language (DML) statements are used for managing data in database.
DML commands are not auto-committed. It means changes made by DML command are
not permanent to database, it can be rolled back.
Talking about the Insert command, whenever we post a Tweet on Twitter, the text is stored
in some table, and as we post a new tweet, a new record gets inserted in that table.

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.

s_id name age

INSERT INTO student VALUES(101, 'Adam', 15);


The above command will insert a new record into student table.

s_id name age

101 Adam 15

Insert value into only specific columns


We can use the INSERT command to insert values for only some specific columns of a row.
We can specify the column names along with the values to be inserted like this,
INSERT INTO student(id, name) values(102, 'Alex');
The above SQL query will only insert id and name values in the newly inserted record.

Insert NULL value to a column


Both the statements below will insert NULL value into age column of the student table.
INSERT INTO student(id, name) values(102, 'Alex');
Or,
INSERT INTO Student VALUES(102,'Alex', null);
The above command will insert only two column values and the other column is set to null.

S_id S_Name age

101 Adam 15

102 Alex
10

Insert Default value to a column


INSERT INTO Student VALUES(103,'Chris', default)

S_id S_Name age

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

Using UPDATE SQL command


Let's take an example of a real-world problem. These days, Facebook provides an option
for Editing the status update this will work using the Update SQL command.
Let's learn about the syntax and usage of the UPDATE command.

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.

Lets take a sample table student,

student_id name age

101 Adam 15

102 Alex
11

103 chris 14

UPDATE student SET age=18 WHERE student_id=102;

S_id S_Name age

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.

Updating Multiple Columns


We can also update values of multiple columns using a single UPDATE statement.
UPDATE student SET name='Abhi', age=17 where s_id=103;
The above command will update two columns of the record which has s_id 103.

s_i nam age


d e

101 Ada 15
m

102 Alex 18

103 Abhi 17

UPDATE Command: Incrementing Integer Value


12

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.

Using DELETE SQL command


Let's study about the syntax and the usage of the Delete command.

DELETE command
DELETE command is used to delete data from a table.

Following is its general syntax,


DELETE FROM table_name;
Let's take a sample table student:

s_i nam age


d e

101 Ada 15
m

102 Alex 18

103 Abhi 17

Delete all Records from a Table


DELETE FROM student;
The above command will delete all the records from the table student.

Delete a particular Record from a Table


13

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.

S_i S_Nam age


d e

101 Adam 15

102 Alex 18

Isn't DELETE same as TRUNCATE


TRUNCATE command is different from DELETE command. The delete command will delete all the
rows from a table whereas truncate command not only deletes all the records stored in the table,
but it also re-initializes the table(like a newly created table).
For eg: If you have a table with 10 rows and an auto_increment primary key, and if you
use DELETEcommand to delete all the rows, it will delete all the rows, but will not re-initialize the
primary key, hence if you will insert any row after using the DELETE command, the
auto_increment primary key will start from 11. But in case of TRUNCATE command, primary key is
re-initialized, and it will again start from 1.

Commit, Rollback and Savepoint SQL commands


Transaction Control Language(TCL) commands are used to manage transactions in the
database. These are used to manage the changes made to the data in a table by DML
statements. It also allows statements to be grouped together into logical transactions.

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.

Using Savepoint and Rollback


Following is the table class,

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;

UPDATE class SET name = 'Abhijit' WHERE id = '5';


15

SAVEPOINT A;

INSERT INTO class VALUES(6, 'Chris');

SAVEPOINT B;

INSERT INTO class VALUES(7, 'Bravo');

SAVEPOINT C;

SELECT * FROM class;


NOTE: SELECT statement is used to show the data stored in the table.

The resultant table will look like,

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

SELECT * FROM class;


Now our class table will look like,

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;

SELECT * FROM class;


Now the table will look like,

id name

1 Abhi

2 Adam

4 Alex

5 Abhijit

So now you know how the commands COMMIT, ROLLBACK and SAVEPOINT works.
17

Using GRANT and REVOKE


Data Control Language(DCL) is used to control privileges in Database. To perform any
operation in the database, such as for creating tables, sequences or views, a user needs
privileges. Privileges are of two types,

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

In DCL we have two commands,

 GRANT: Used to provide any user access privileges or other priviliges for the database.

 REVOKE: Used to take back permissions from any user.

Allow a User to create session


When we create a user in SQL, it is not even allowed to login and create a session until and
unless proper permissions/priviliges are granted to the user.
Following command can be used to grant the session creating priviliges.
GRANT CREATE SESSION TO username;

Allow a User to create table


To allow a user to create tables in the database, we can use the below command,
GRANT CREATE TABLE TO username;

Provide user with space on tablespace to store table


Allowing a user to create table is not enough to start storing data in that table. We also must
provide the user with priviliges to use the available tablespace for their table and data.
ALTER USER username QUOTA UNLIMITED ON SYSTEM;
The above command will alter the user details and will provide it access to unlimited
tablespace on system.
NOTE: Generally unlimited quota is provided to Admin users.

Grant all privilege to a User


18

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

Grant permission to create any table


Sometimes user is restricted from creating come tables with names which are reserved for
system tables. But we can grant privileges to a user to create any table using the below
command,
GRANT CREATE ANY TABLE TO username

Grant permission to drop any table


As the title suggests, if you want to allow user to drop any table from the database, then
grant this privilege to the user,
GRANT DROP ANY TABLE TO username

To take back Permissions


And, if you want to take back the privileges from any user, use the REVOKE command.
REVOKE CREATE TABLE FROM username

Using the WHERE SQL clause


WHERE clause is used to specify/apply any condition while retrieving, updating or deleting
data from a table. This clause is used mostly with SELECT, UPDATE and DELETEquery.
When we specify a condition using the WHERE clause then the query executes only for those
records for which the condition specified by the WHERE clause is true.

Syntax for WHERE clause


Here is how you can use the WHERE clause with a DELETE statement, or any other statement,
DELETE FROM table_name WHERE [condition];
The WHERE clause is used at the end of any SQL query, to specify a condition for execution.

Time for an Example


Consider a table student,

s_id name age address

101 Adam 15 Chennai


19

102 Alex 18 Delhi

103 Abhi 17 Banglore

104 Ankit 22 Mumbai

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.

s_id name age address

101 Adam 15 Noida

Applying condition on Text Fields


In the above example we have applied a condition to an integer value field, but what if we
want to apply the condition on name field. In that case we must enclose the value in single
quote ' '. Some databases even accept double quotes, but single quotes is accepted by
all.
SELECT s_id,
name,
age,
address
FROM student WHERE name = 'Adam';
Following will be the result of the above query.

s_id name age address


20

101 Adam 15 Noida

Operators for WHERE clause condition


Following is a list of operators that can be used while specifying the WHERE clause condition.

Operator Description

= Equal to

!= Not Equal to

< Less than

> Greater than

<= Less than or Equal to

>= Greate than or Equal to

BETWEEN Between a specified range of values

LIKE This is used to search for a pattern in value.

IN In a given set of values

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;

Using default Order by


Consider the following Emp table,

eid name age salary

401 Anu 22 9000

402 Shane 29 8000

403 Rohan 34 6000

404 Scott 44 10000

405 Tiger 35 8000

SELECT * FROM Emp ORDER BY salary;


The above query will return the resultant data in ascending order of the salary.

eid name ag salary


e

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

Using Order by DESC


Consider the Emp table described above,
SELECT * FROM Emp ORDER BY salary DESC;
The above query will return the resultant data in descending order of the salary.

eid name ag salary


e

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

Example of Group by in a Statement


Consider the following Emp table.

eid name age salary

401 Anu 22 9000

402 Shane 29 8000

403 Rohan 34 6000

404 Scott 44 9000

405 Tiger 35 8000

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.

SQL query for the above requirement will be,


SELECT name, age
FROM Emp GROUP BY salary
Result will be,
24

name age

Rohan 34

Shane 29

Anu 22

Example of Group by in a Statement with WHERE clause


Consider the following Emp table

eid name age salary

401 Anu 22 9000

402 Shane 29 8000

403 Rohan 34 6000

404 Scott 44 9000

405 Tiger 35 8000

SQL query will be,


SELECT name, salary
FROM Emp
WHERE age > 25
GROUP BY salary
Result will be.

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

Example of SQL Statement using HAVING


Consider the following Sale table.

oid order_name previous_balance customer

11 ord1 2000 Alex

12 ord2 1000 Adam

13 ord3 2000 Abhi

14 ord4 1000 Adam


26

15 ord5 2000 Alex

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,

oid order_name previous_balance customer

11 ord1 2000 Alex

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.

Syntax for DISTINCT Keyword


SELECT DISTINCT column-name FROM table-name;

Example using DISTINCT Keyword


Consider the following Emp table. As you can see in the table below, there is employee name,
along with employee salary and age.
In the table below, multiple employees have the same salary, so we will be
using DISTINCT keyword to list down distinct salary amount, that is currently being paid to the
employees.

eid name ag salary


e

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

SELECT DISTINCT salary FROM Emp;


The above query will return only the unique salary from Emp table.

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.

DROP INDEX Statement


The DROP INDEX statement is used to delete an index in a table.

DROP INDEX index_name ON table_name;

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

CREATE VIEW view_name


AS
SELECT column_list
FROM table_name [WHERE condition];

 view_name is the name of the VIEW.


 The SELECT statement is used to define the columns and rows that you want to
display in the view.
For Example: to create a view on the product table the sql query would be like
CREATE VIEW view_product
AS
SELECT product_id, product_name
FROM product;

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:

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:

 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 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:
31

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


32

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;

Following is an example to drop the CUSTOMERS_VIEW from the


CUSTOMERS table.
DROP VIEW CUSTOMERS_VIEW;

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.

Materialized Views in DBMS


As we have seen above, views are executed when we fire query on it. So, it does not speed up the
execution of the query that is having views. But it simplifies the query. But when we write a
query it is always expected it to run quickly. So what we can do is, run the frequently used query
and store it under some name! This is similar to view but here we are executing the query and
storing the results of query under name. This type of view is called materialized view. Using
materialized view in complex query reduces the execution time for running repeated queries. It
involves the time for running ‘SELECT * FROM ...’. Unlike views, in this type of views, copies
of table records are created and stored. Materialized views are not virtual tables. Hence there will
be a storage space allocated to it.

CREATE MATERIALIZED VIEW mv_Design_Emp AS


SELECT e.EMP_ID, e.EMP_FIRST_NAME, e.EMP_LAST_NAME, d.DEPT_ID, d.DEPT_NAME
FROM EMPLOYEE e, DEPARTMENT d – two tables are used to create a view
WHERE e.DEPT_ID = d.DEPT_ID -- Join condition
AND d.DEPT_NAME = ‘DESIGN’; -- Filtering condition

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.

Comparison between Views and Materialized View :


34

What are the restrictions applicable while creating views?

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.

What are the restrictions that views have to follow?

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

What are the restrictions applicable while creating views?

Restrictions applicable while creating views:


35

- A view cannot be indexed.


- A view cannot be Altered or renamed. Its columns cannot be renamed.
- To alter a view, it must be dropped and re-created.
- ANSI_NULLS and QUOTED_IDENTIFIER options should be turned on to create a view.
- All tables referenced in a view must be part of the same database.
- Any user defined functions referenced in a view must be created with SCHEMABINDING option.
- Cannot use ROWSET, UNION, TOP, ORDER BY, DISTINCT, COUNT(*), COMPUTE, COMPUTE BY
Advantages of database view
The following are advantages of using database views.

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

Disadvantages of database view


Besides the advantages above, there are several disadvantages of using database views:

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

SQL ANY and ALL Operators


36

The SQL ANY and ALL Operators


The ANY and ALL operators are used with a WHERE or HAVING clause.

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.

2. SELECT fname, lname


3. FROM Customers
4. WHERE EXISTS (SELECT *
5. FROM Orders
WHERE Customers.customer_id = Orders.c_id);
Output:
38

6. Using NOT with EXISTS


Fetch last and first name of the customers who has not placed any order.
7. SELECT lname, fname
8. FROM Customer
9. WHERE NOT EXISTS (SELECT *
10. FROM Orders
WHERE Customers.customer_id = Orders.c_id);
Output:

11. Using EXISTS condition with DELETE statement


Delete the record of all the customer from Order Table whose last name is ‘Mehra’.
12. DELETE
13. FROM Orders
14. WHERE EXISTS (SELECT *
15. FROM customers
16. WHERE Customers.customer_id = Orders.cid
AND Customers.lname = 'Mehra');
SELECT * FROM Orders;

Output:

17. Using EXISTS condition with UPDATE statement


Update the lname as ‘Kumari’ of customer in Customer Table whose customer_id is 401.
18. UPDATE Customers
19. SET lname = 'Kumari'
20. WHERE EXISTS (SELECT *
21. FROM Customers
WHERE customer_id = 401);
SELECT * FROM Customers;
39

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.

Types of Integrity Constraint

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

2. Entity integrity constraints


o The entity integrity constraint states that primary key value can't be null.
o This is because the primary key value is used to identify individual rows in relation and if the primary key has a
null value, then we can't identify those rows.
o A table can contain a null value other than the primary key field.

Example:

3. Referential Integrity Constraints


o A referential integrity constraint is specified between two tables.
o In the Referential integrity constraints, if a foreign key in Table 1 refers to the Primary Key of Table 2, then every
value of the Foreign Key in Table 1 must be null or be available in Table 2.

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

Let's assume the value of X before starting of the transaction is 4000.

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.

To solve this problem, we have two important operations:

Commit: It is used to save the work done permanently.

Rollback: It is used to undo the work done.


43

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

Differences between SQL and PL/SQL:


SQL PL/SQL

SQL is a single query that is used to perform DML PL/SQL is a block of codes that used to write the

and DDL operations. entire program blocks/ procedure/ function, etc.

It is declarative, that defines what needs to be PL/SQL is procedural that defines how the things

done, rather than how things need to be done. needs to be done.

Execute as a single statement. Execute as a whole block.

Mainly used to manipulate data. Mainly used to create an application.

It is an extension of SQL, so it can contain SQL

Cannot contain PL/SQL code in it. inside it.

Structure of PL/SQL Block:

PL/SQL extends SQL by adding constructs found in procedural languages, resulting in a


structural language that is more powerful than SQL. The basic unit in PL/SQL is a block. All
PL/SQL programs are made up of blocks, which can be nested within each other.

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.

1.1) INITIALISING VARIABLES:


The variables can also be initialised just like in other programming languages. Let
us see an example for the same:
SQL> SET SERVEROUTPUT ON;

SQL> DECLARE

var1 INTEGER := 2 ;

var3 varchar2(20) := 'I Love DBMS' ;

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

var varchar2(40) := 'I love DBMS' ;

BEGIN

dbms_output.put_line(var);

END;
47

Output:
I love DBMS

PL/SQL procedure successfully completed.


Explanation:
 dbms_output.put_line : This command is used to direct the PL/SQL output to a
screen.

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

-- I am a comment, so i will be ignored.

var varchar2(40) := 'I love DBMS' ;

BEGIN

dbms_output.put_line(var);

END;

Output:
I love DBMS

PL/SQL procedure successfully completed.


48

4. Taking input from user:


Just like in other programming languages, in PL/SQL also, we can take input from
the user and store it in a variable. Let us see an example to show how to take input
from users in PL/SQL:
SQL> SET SERVEROUTPUT ON;

SQL> DECLARE

-- taking input for variable a

a number := &a;

-- taking input for variable b

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

PL/SQL procedure successfully completed.

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> SET SERVEROUTPUT ON;


49

SQL> DECLARE

-- taking input for variable a

a integer := &a ;

-- taking input for variable b

b integer := &b ;

c integer ;

BEGIN

c := a + b ;

dbms_output.put_line('Sum of '||a||' and '||b||' is = '||c);

END;

Enter value for a: 2


Enter value for b: 3

Sum of 2 and 3 is = 5

PL/SQL procedure successfully completed.


PL/SQL Execution Environment:
The PL/SQL engine resides in the Oracle engine.The Oracle engine can process not
only single SQL statement but also block of many statements.The call to Oracle engine
needs to be made only once to execute any number of SQL statements if these SQL
statements are bundled inside a PL/SQL block.

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:

IF < Condition > THEN


< Action >
ELSIF <Condition> THEN
< Action >
ELSE < Action >
END IF;

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

PL/SQL successfully completed.

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 :

WHILE < condition >


LOOP
< Action >
END LOOP

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

reverse of given number is: 321


PL/SQL successfully completed.

The FOR Loop


53

The FOR loop can be used when the number of iterations to be executed are known.

Syntax :

FOR variable IN [REVERSE] start..end


LOOP
< Action >
END LOOP;

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.

PL/SQL successfully completed.

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.

Exception Raised when....

DUP_VAL_ON_INDEX When you try to insert a duplicate value into a unique column.

INVALID_CURSOR It occurs when we try accessing an invalid cursor.

INVALID_NUMBER On usage of something other than number in place of number value.

LOGIN_DENIED At the time when user login is denied.

TOO_MANY_ROWS When a select query returns more than one row and the destination variable can take only
single value.

VALUE_ERROR When an arithmetic, value conversion, truncation, or constraint error occurs.

CURSOR_ALREADY_OPEN Raised when we try to open an already open cursor.

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

Run SQL Command Line


SQL>set serveroutput on
SQL>start D://d.sql
divide by zero error occures..
PL/SQL procedure successfully completed.

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.

User Defined Exception Handling :


To trap business rules being violated the technique of raising user-defined exceptions and then handling them, is used.
User-defined error conditions must be declared in the declarative part of any PL/SQL block. In the executable part, a check for the condition
that needs special attention is made. If that condition exists, the call to the user-defined exception is made using a RAISE statement. The
exception once raised is then handled in the Exception handling section of the PL/SQL code block.

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

%FOUND Returns TRUE if record was fetched successfully, FALSE otherwise.

%NOTFOUND Returns TRUE if record was not fetched successfully, FALSE otherwise.

%ROWCOUNT Returns number of records fetched from cursor at that point in time.

%ISOPEN Returns TRUE if cursor is open, FALSE otherwise.


59

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:

CURSOR cursor_name IS select_statement;

cursor _name -A suitable name for the cursor.


Select_statement - A select query which returns multiple rows.

How to use Explicit Cursor?


There are four steps in using an Explicit Cursor.

1. DECLARE the cursor in the declaration section


2. OPEN the cursor in the Execution Section.
3. FETCH the data from cursor into PL/SQL variables or records in the Execution Section.
4. CLOSE the cursor in the Execution Section before you end the PL/SQL Block.

Declaring a Cursor in the Declaration Section:

Syntax:

CURSOR CURSORNAME IS SELECT.......;

How to access an Explicit Cursor?


These are the three steps in accessing the cursor.
Open the cursor :

Syntax:

OPEN cursor_name;

Fetch the records in the cursor one at a time :

Syntax:

FETCH cursor_name INTO record_name;


OR
FETCH cursor_name INTO variable_list;

Close the cursor :

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.

Points to remember while fetching a row:

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.

General Form of using an explicit cursor is:

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.

Formated by Tuotiral Blocks

Cursor For Loop :


Oracle provides another loop-statements to control loops specifically for cursors.
This statements is a variation of the basic FOR loop , and it is known as cursor for loops.

Syntax:

FOR VARIABLE IN CURSORNAME


LOOP
<EXECUTE COMMANDS>
END LOOP

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:

CURSOR CURSORNAME (VARIABLENAME DATATYPES ) IS SELECT.........

And, parameters canbe passed to cursor while opening it using syntax-

Syntax:

OPEN CURSORNAME (VALUE / VARIABLE / EXPRESSION );

Procedures & Functions


"A procedures or function is a group or set of SQL and PL/SQL statements that perform a
specific task."
A function and procedure is a named PL/SQL Block which is similar . The major difference
63

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.

We can pass parameters to procedures in three ways :

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.

A procedure may or may not return any value.

Syntax:

CREATE [OR REPLACE] PROCEDURE procedure_name (<Argument> {IN, OUT, IN OUT}


<Datatype>,…)
IS
Declaration section<variable, constant> ;
BEGIN
Execution section
EXCEPTION
64

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 :

 From the SQL prompt : EXECUTE [or EXEC] procedure_name;


 Within another procedure – simply use the procedure name : procedure_name;

Example:
create table named emp have two column id and salary with number datatype.

CREATE OR REPLACE PROCEDURE p1(id IN NUMBER, sal IN NUMBER)


AS
BEGIN
INSERT INTO emp VALUES(id, sal);
DBMD_OUTPUT.PUT_LINE('VALUE INSERTED.');
END;
/

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.

SQL>select * from emp;


ID SALARY
----- --------
2 5000

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:

CREATE [OR REPLACE] FUNCTION function_name [parameters]


RETURN return_datatype; {IS, AS}
Declaration_section <variable,constant> ;
BEGIN
Execution_section
Return return_variable;
EXCEPTION
exception section
Return return_variable;
END;

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.

 As a part of a SELECT statement : SELECT emp_details_func FROM dual;


 In a PL/SQL Statements like, : dbms_output.put_line(emp_details_func);

This line displays the value returned by the function .

Example:

create or replace function getsal (no IN number) return number


is
sal number(5);
begin
select salary into sal from emp where id=no;
return sal;
end;
/

Output:
66

Run SQL Command Line


SQL>select * from emp;
ID SALARY
----- --------
2 5000

SQL>start D://fun.sql
Function created.

SQL>select getsal(2) from dual;


GETSAL(2)
---------
5000

Formated by Tuotiral Blocks

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:

DROP PROCEDURE/FUNCTION PROCEDURE/FUNCTION_NAME;

Procedures VS Functions:

 A function MUST return a value


 A procedure cannot return a value
 Procedures and functions can both return data in OUT and IN OUT parameters
 The return statement in a function returns control to the calling program and returns
the results of the function
 The return statement of a procedure returns control to the calling program and cannot
return a value
 Functions can be called from SQL, procedure cannot
 Functions are considered expressions, procedure are not

PL/SQL Recursive Functions


We have seen that a program or subprogram may call another subprogram.
When a subprogram calls itself, it is referred to as a recursive call and the
process is known as recursion.
To illustrate the concept, let us calculate the factorial of a number. Factorial
of a number n is defined as −
n! = n*(n-1)!
= n*(n-1)*(n-2)!
...
67

= n*(n-1)*(n-2)*(n-3)... 1

The following program calculates the factorial of a given number by calling


itself recursively −
DECLARE

num number;

factorial number;

FUNCTION fact(x 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);

dbms_output.put_line(' Factorial '|| num || ' is ' || factorial);

END;

When the above code is executed at the SQL prompt, it produces the
following result −
Factorial 6 is 720

PL/SQL procedure successfully completed.

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

A package has usually two components, a specification and a body.


A package's specification declares the types (variables of the record type), memory variables,
constants, exceptions, cursors, and subprograms that are available for use.
A package's body fully defines cursors, functions, and procedures and thus implements the
specification.

Package specification:
The package specification contains:

 Name of the package


 Names of the data types of any arguments
 This declaration is local to the database and global to the package

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:

Create [or replace] package package_name


{is | as}
Package_specification
End package_name;

Example:
create package operation that contains procedure 'add' and function 'sub'.

CREATE OR REPLACE PACKAGE OPERATION


IS
PROCEDURE ADDITION(A IN NUMBER,B IN NUMBER);
FUNCTION SUB(A IN NUMBER,B IN NUMBER)RETURN NUMBER;
END OPERATION;
/

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:

Create [or replace] package body package_name


{is | as}
Package_body
End package_name;

Example:

Create or replace package body OPERATION


is
PROCEDURE ADDITION(A IN NUMBER,B IN NUMBER)
is
begin
dbms_output.put_line('addtion of two number :'||ADD(A,B));
end;
FUNCTION SUB(A IN NUMBER,B IN NUMBER)RETURN NUMBER
is
ans number(3);
begin
ans:=A-B;
return ans;
end;
end OPERATION;
/

Output:
70

Run SQL Command Line

SQL>start D://pacbody.sql
Package body created.

Formated by Tuotiral Blocks

Advantages of package:

 Packages enable the organization of commercial applications into efficient modules.


Each package is easily understood and the interfaces between packages are simple,
clear and well defined.
 Packages allow granting of privileges efficiently .
 A package's public variables and cursors persist for the duration of the session.
Therefore all cursors and procedures that execute in this environment can share them .
 Packages enable the overloading of procedures and functions when required .
 Packages improve performance by loading multiple objects into memory at once.
Therefore, subsequent calls to related subprograms in the package require no i/o .
 Packages promote code reuse through the use of libraries that contain stored
procedures and functions, thereby reducing redundant coding .

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:

CREATE [OR REPLACE ] TRIGGER trigger_name


{BEFORE | AFTER | INSTEAD OF }
{INSERT [OR] | UPDATE [OR] | DELETE}
[OF col_name]
ON table_name
[REFERENCING OLD AS o NEW AS n]
[FOR EACH ROW]
WHEN (condition)
BEGIN
--- sql statements
END;
71

Each statements are described below :

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:

Create or replace Trigger np before insert on account for each row


Begin
IF :NEW.bal < 0 THEN
DBMS_OUTPUT.PUT_LINE('BALANCE IS NAGATIVE..');
END IF;
End;
/

Output:
Run SQL Command Line

SQL>start D://t.sql
Trigger created.

SQL>insert into account values(1,-100);


BALANCE IS NAGATIVE..
1 row 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.

 Row Level Triggers


 Statement Level Triggers
 Before Triggers
 After Triggers

Row Level Triggers :


Row level triggers execute once for each row in a transaction.
The commands of row level triggers are executed on all rows that are affected by the command
that enables the trigger.
73

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.

Statement Level Triggers :


Statement level triggers are triggered only once for each transaction.
For example when an UPDATE command update 15 rows, the commands contained in the
trigger are executed only once, and not with every processed row.
Statement level trigger are the default types of trigger created via the CREATE TRIGGER
command.

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.

The possible configurations are:

 BEFORE statement Trigger


 BEFORE row Trigger
 AFTER statement Trigger
 AFTER row Trigger

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:

DROP TRIGGER trigger_name;

Example:
Run SQL Command Line

SQL>DROP TRIGGER emp;

Trigger dropped.

You might also like