Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
52 views43 pages

Module 3

Download as pdf or txt
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 43

Module 3: SQL AND PL/SQL (10 Periods)

SQL: Form of basic SQL query, Nested queries, Aggregate operators, Null
values, Complex integrity constrains in SQL, Triggers and active databases.

PL/SQL: Generic PL/SQL block, PL/SQL data types, Control structure, Procedures
and functions, Cursors, Database triggers

INTRODUCTION OF SQL
SQL or Structured Query Language is simply a computer language that is used to establish a
communication between the user and the database i.e. all the database related operations are performed using
this Structured Query Language.

As the name suggests, SQL is used to manage the structured databases like RDBMS. Non-Structured databases
can't be managed by SQL. Some of the Relational Database Management Systems like Oracle, MS Access, MySQL,
etc uses SQL for all the operations on the database.

Some of the operations that can be performed with the help of SQL are:

• Users can create a database.


• Users can create some tables in some database.
• Users can delete or alter the properties of the table.
• Users can provide particular grant access to some particular users using the SQL.
• Users can put constraints on the data stored in the database.
These are some of the operations that can be performed on database with the help of SQL.

In SQL, we give some commands to the system to perform some operation. That command or the instruction is
known as a Query. The system will take this query as an input and will give the desired output. So, there are some
steps that are included in this whole process. So, let's look at the process involved in executing a SQL query.

Query Processing
In SQL, we write queries to perform certain operations. But those queries are in some high-level language and
this high-level language must be converted to some low-level language because the system can understand the
low-level languages only. So, following is the block diagram of Query processing in SQL:
Following is the description of the same:

• SQL Query: It is the query that you are want to execute to get some data from the database. It can be
some create table query or delete table query or something else that you want to perform on the
database.
• Parser and Translator: The SQL query is in high-level language and we need to convert this high-level
language in low-level language. So, a translator translates the SQL queries into some relational algebraic
expressions. At the same time, the Parser checks for some syntax error(if any) and the relations that are
used in the RDBMS.
• Query Optimizer: There can be a number of ways for writing the same query. But your query should be
such that it should be the most efficient query. So, the Query Optimizer optimizes the query in such a way
that it is the efficient query that can be executed.
• Query Evaluation: Finally the optimized query will be evaluated and the result will be shown to the users.

FORM OF BASIC SQL QUERY


It is used to extract the data from the relations. e.g.; SELECT
So first we will consider the Data Query Language. A generic query to retrieve from a relational database is:
1. SELECT [DISTINCT] Attribute_List FROM R1,R2….RM
2. [WHERE condition]
3. [GROUP BY (Attributes)[HAVING condition]]
4. [ORDER BY(Attributes)[DESC]];
Part of the query represented by statement 1 is compulsory if you want to retrieve from a relational
database. The statements written inside [] are optional

The SQL SELECT statement is used to select (retrieve) data from a database table.
For example,

SELECT first_name, last_name FROM Customers;

Here, the SQL command selects the first_name and last_name of all Customers.
Example: SQL SELECT
SQL SELECT ALL
To select all columns from a database table, we use the * character. For example,
SELECT * FROM Customers;

Here, the SQL command selects all columns of the Customers table.
Example: SQL SELECT All

SQL SELECT WHERE Clause


A SELECT statement can have an optional WHERE clause. The WHERE clause allows us to fetch records from a
database table that matches specified condition(s).

For example,
SELECT * FROM Customers WHERE last_name = 'Doe';
Here, the SQL command selects all customers from the Customers table with last_name Doe.
Example: SQL SELECT with WHERE

SQL Operators
The WHERE clause uses operators to construct conditions. Some of the commonly used operators are:
1. Equal to Operator (=)
SELECT * FROM Customers WHERE first_name = 'John';

Run Code

This SQL command selects all customers from the Customers table having first_name John.

2. Greater than (>)


SELECT * FROM Customers WHERE age > 25;

Run Code

This SQL command selects all customers from the Customers table having age greater than 25.

3. AND Operator (AND)


SELECT * FROM Customers WHERE last_name = 'Doe' AND country = 'USA';

Run Code

This SQL command selects all customers from the Customers table having last_name Doe and country USA

NESTED QUERIES
A Subquery is a query within another SQL query and embedded within the WHERE clause.
Subquery is also known as Nested Query.
Important Rule:
o A subquery can be placed in a number of SQL clauses like WHERE clause, FROM clause, HAVING clause.
o You can use Subquery with SELECT, UPDATE, INSERT, DELETE statements along with the operators like =, <, >,
>=, <=, IN, BETWEEN, etc.
o A subquery is a query within another query. The outer query is known as the main query, and the inner query
is known as a subquery.
o Subqueries are on the right side of the comparison operator.
o A subquery is enclosed in parentheses.
o In the Subquery, ORDER BY command cannot be used. But GROUP BY command can be used to perform the
same function as ORDER BY command.

Note: SQL subqueries are most frequently used with the Select statement.

Syntax: SELECT column_name


FROM table_name
WHERE column_name expression operator
( SELECT column_name from table_name WHERE ... );

Example
Consider the EMPLOYEE table have the following records:
ID NAME AGE ADDRESS SALARY
1 John 20 US 2000.00
2 Stephan 26 Dubai 1500.00
3 David 27 Bangkok 2000.00
4 Alina 29 UK 6500.00
5 Kathrin 34 Bangalore 8500.00
6 Harry 42 China 4500.00
7 Jackson 25 Mizoram 10000.00
The subquery with a SELECT statement will be:
SELECT * FROM EMPLOYEE WHERE ID IN (SELECT ID FROM EMPLOYEE WHERE SALARY > 4500);
This would produce the following result:
ID NAME AGE ADDRESS SALARY
4 Alina 29 UK 6500.00
5 Kathrin 34 Bangalore 8500.00
7 Jackson 25 Mizoram 10000.00

There are mainly two types of nested queries:

1. Independent Nested Queries: In independent nested queries, query execution starts from innermost query to
outermost queries. The execution of inner query is independent of outer query, but the result of inner query is
used in execution of outer query. Various operators like IN, NOT IN, ANY, ALL etc are used in writing independent
nested queries.

STUDENT
S_ID S_NAME S_ADDRESS S_PHONE S_AGE
S1 RAM DELHI 9455123451 18
S2 RAMESH GURGAON 9652431543 18
S3 SUJIT ROHTAK 9156253131 20
S4 SURESH DELHI 9156768971 18

COURSE
C_ID C_NAME
C1 DSA
C2 Programming
C3 DBMS

IN: If we want to find out S_ID who are enrolled in C_NAME ‘DSA’ or ‘DBMS’, we can write it with the help of
independent nested query and IN operator. From COURSE table, we can find out C_ID for C_NAME ‘DSA’ or DBMS’
and we can use these C_IDs for finding S_IDs from STUDENT_COURSE TABLE.

STEP 1: Finding C_ID for C_NAME =’DSA’ or ‘DBMS’


Select C_ID from COURSE where C_NAME = ‘DSA’ or C_NAME = ‘DBMS’

STEP 2: Using C_ID of step 1 for finding S_ID


Select S_ID from STUDENT_COURSE where C_ID IN (SELECT C_ID from COURSE where C_NAME =
‘DSA’ or C_NAME=’DBMS’);

The inner query will return a set with members C1 and C3 and outer query will return those S_IDs for which C_ID is
equal to any member of set (C1 and C3 in this case). So, it will return S1, S2 and S4.

Note: If we want to find out names of STUDENTs who have either enrolled in ‘DSA’ or ‘DBMS’, it can be done as:
Select S_NAME from STUDENT where S_ID IN
(Select S_ID from STUDENT_COURSE where C_ID IN
(SELECT C_ID from COURSE where C_NAME=’DSA’ or C_NAME=’DBMS’));

NOT IN: If we want to find out S_IDs of STUDENTs who have neither enrolled in ‘DSA’ nor in ‘DBMS’, it can be done
as:
Select S_ID from STUDENT where S_ID NOT IN (Select S_ID from STUDENT_COURSE where C_ID IN
(SELECT C_ID from COURSE where C_NAME=’DSA’ or C_NAME=’DBMS’));

The innermost query will return a set with members C1 and C3. Second inner query will return those S_IDs for
which C_ID is equal to any member of set (C1 and C3 in this case) which are S1, S2 and S4. The outermost query
will return those S_IDs where S_ID is not a member of set (S1, S2 and S4). So it will return S3.

2. Co-related Nested Queries: In co-related nested queries, the output of inner query depends on the row which
is being currently executed in outer query. e.g.; If we want to find out S_NAME of STUDENTs who are enrolled
in C_ID ‘C1’, it can be done with the help of co-related nested query as:
Select S_NAME from STUDENT S where EXISTS
( select * from STUDENT_COURSE SC where S.S_ID=SC.S_ID and SC.C_ID=’C1’);

For each row of STUDENT S, it will find the rows from STUDENT_COURSE where S.S_ID = SC.S_ID and
SC.C_ID=’C1’. If for a S_ID from STUDENT S, atleast a row exists in STUDENT_COURSE SC with C_ID=’C1’, then inner
query will return true and corresponding S_ID will be returned as output.

AGGREGATE OPERATORS
In database management systems, an aggregate function is a function that performs calculations on a group
of values and returns a single value.
It is used to summarize the data. It performs calculations on multiple rows of a single column of a t able to form
a single value of more significant meaning.
These Aggregate functions are inbuilt SQL functions. They are often used with the GROUP BY clause to
calculate an aggregate value for each group.

Some of MySQL Aggregate functions are:


• AVG
• COUNT
• MAX
• MIN
• SUM
The AGGREGATE Functions ignore all NULL Values.

AVG : The SQL AVG function calculates the average value of a column of numeric type. It returns the average of
all non-NULL values.

Syntax AVG ( [ALL | DISTINCT] expression )


[ALL | DISTINCT] is optional. ALL is used to select all the records for input while DISTINCT is used to select only
uniques values of the record.
Expression: it specifies the input source. It may be a field of the table or a subquery.

For example:
SELECT AVG(Salary) FROM Employees;
This query returns the average salary of all the employees.

SELECT Dept_Id,AVG(Salary) FROM Employees GROUP BY Dept_Id;


This query will return the Dept_Id and Average Salary of Employees of corresponding Department.

SELECT Emp_Id, Emp_Name FROM Employees WHERE Salary > AVG(Salary);


This query will return the Emp_Id and Emp_Name of Employees whose Salary is greater the Average Salary of all the
Employees.

COUNT : The COUNT function is used to count the number of rows in a database table. It can work on both
numeric and non-numeric data types.
The SQL COUNT function returns the number of rows in a table satisfying the criteria specified in the WHERE
clause. It sets on the number of rows or non-NULL column values.
COUNT function uses the COUNT(*) that returns the count of all the rows in a specified table.
COUNT(*) considers duplicate and Null while Count(column_name) removes Null values records from counting.

Syntax
COUNT(*)
or
COUNT( [ALL | DISTINCT] expression )
[ALL | DISTINCT] is optional. By default it is ALL. DISTINCT keyword removes duplicate and Null values from
operation.

For example:
SELECT COUNT(*) FROM Employees;
This query will return the total number of records in the Employees table.
SELECT COUNT(DISTINCT Dept_Id) FROM Employees;
This query will return the count total number of Dept_Id. It does not consider duplicate Dept_Id and Null.

SELECT Dept_Id, COUNT(*) FROM Employees GROUP BY Dept_Id;


This query will return the count of Employees in each department.

MAX : The aggregate function MAX() is used to find the maximum value or highest value of a certain column or
expression or a set of values.
It is applicable to all the data types.
It excludes NULL values and return distinct value as a result.

Syntax MAX(expression)

For example:
SELECT MAX(Salary) FROM Employees;
This query will return maximum salary from the Employees table.

SELECT Dept_Id, MAX(Salary) FROM Employees GROUP BY Dept_Id;


This query will return the Dept_Id along with the maximum salary of each department.

SELECT * FROM Employees WHERE Salary = MAX(Salary);


This query will return all the details of the Employee who has the maximum salary.

SELECT * FROM Employees WHERE Hire_Date = MAX(Hire_Date);


This query will return the details of the Employee who has been in the Company for the least amount of time.

MIN : The aggregate function MIN() is used to find the minimum value or lowest value of a certain column or
expression or a set of values.
It is applicable to all the data types.
It excludes NULL values and return distinct value as a result.

Syntax : MIN(expression)

For example
SELECT MIN(Salary) FROM Employees;
This query will return minimum salary from the Employees table.

SELECT Dept_Id, MIN(Salary) FROM Employees GROUP BY Dept_Id;


This query will return the Dept_Id along with the minimum salary of each department.

SELECT * FROM Employees WHERE Salary = MIN(Salary);


This query will return all the details of the Employee who has the minimum salary.

SELECT * FROM Employees WHERE Hire_Date = MIN(Hire_Date);


This query will return the details of the Employee who has been at the Company for the longest time.

SUM : The aggregate function SUM() is used to calculate the sum of all the values of the select column. It
returns the sum of values in a set.
SUM function ignores the NULL values. If no matching records are found, it returns NULL.
It is applicable to numeric values.

Syntax
SUM([ALL | DISTINCT]) expression)
DISTINCT is used to select unique values.

For example:
SELECT SUM(Salary) FROM Employees;
This query will return total salary of all the Employees.

SELECT Dept_Id, SUM(Salary) FROM Employees GROUP BY Dept_Id;


This query will return the Dept_Id along with the total salary of all the employees in each department.

SELECT Dept_Id FROM Employees WHERE SUM(Salary) > 200000;


This query will return the Dept_Id in which the total salary of all the employees in the department is greater than
200000.

GROUP BY – We can combine specific categories of columns together and show the results. For example, there are
multiple employees working in different department. Using group by option we can display how many employees
are working in each department.

SELECT d.DEPATMENT_NAME, COUNT (e.DEPATMENT_ID) total_emp_count


FROM EMPLOYEE e, DEPARTMENT d
WHERE e.DEPARTMENT_ID = d.DEPARTMENT_ID – this condition pulls the matching employees
GROUP BY e.DEPARTMENT_ID;

Having Clause – Using this clause we can add conditions to the grouped categories and filter the records. For
examples, if we want to display the details of the department which has more than 100 employees.

SELECT d.DEPATMENT_NAME, COUNT (e.DEPATMENT_ID) total_emp_count


FROM EMPLOYEE e, DEPARTMENT d
WHERE e.DEPARTMENT_ID = d.DEPARTMENT_ID – this condition pulls the matching employees
GROUP BY e.DEPARTMENT_ID
HAVING COUNT(e.DEPATMENT_ID)>100; -- filters more than 100 employees present in specific department. We
cannot give this condition in the where clause as this is the result of Group by clause.

NULL VALUES
In SQL there may be some records in a table that do not have values or data for every field. This could
be possible because at a time of data entry information is not available. So SQL supports a special value known as
NULL which is used to represent the values of attributes that may be unknown or not apply to a tuple. SQL places
a NULL value in the field in the absence of a user-defined value. For example, the Apartment_number attribute of
an address applies only to address that are in apartment buildings and not to other types of residences.
Importance of NULL value:
• It is important to understand that a NULL value is different from a zero value.
• A NULL value is used to represent a missing value, but that it usually has one of three different
interpretations:
• The value unknown (value exists but is not known)
• Value not available (exists but is purposely withheld)
• Attribute not applicable (undefined for this tuple)
• It is often not possible to determine which of the meanings is intended. Hence, SQL does not distinguish
between the different meanings of NULL.
Principles of NULL values:
• Setting a NULL value is appropriate when the actual value is unknown, or when a value would not be
meaningful.
• A NULL value is not equivalent to a value of ZERO if the data type is a number and is not equivalent to
spaces if the data type is character.
• A NULL value can be inserted into columns of any data type.
• A NULL value will evaluate NULL in any expression.
• Suppose if any column has a NULL value, then UNIQUE, FOREIGN key, CHECK constraints will ignore by
SQL.
Consider the sample table ‘emp’

EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO


7839 KING PRESIDENT – 17-NOV-81 5000 – 10
7698 BLAKE MANAGER 7839 01-MAY-81 2850 500 30
7782 CLARK MANAGER 7839 09-JUN-81 2450 500 10
7566 JONES MANAGER 7839 02-APR-81 2975 – 20
7788 SCOTT ANALYST 7566 19-APR-87 3000 – 20
7902 FORD ANALYST 7566 03-DEC-81 3000 – 20
7369 SMITH CLERK 7902 17-DEC-80 800 500 20

IS NULL operator
All operations upon null values present in the table must be done using this ‘is null’ operator .we cannot compare
null value using the assignment operator

Example : select * from emp where comm is null


O/P : 4 rows selected.

EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO


7839 KING PRESIDENT – 17-NOV-81 5000 – 10
7566 JONES MANAGER 7839 02-APR-81 2975 – 20
7788 SCOTT ANALYST 7566 19-APR-87 3000 – 20
7902 FORD ANALYST 7566 03-DEC-81 3000 – 20

The details of those employees whose commission value is Null are displayed.

IS NOT NULL
Ex: select * from emp where comm is not null;

O/P : 3 rows selected.

EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO


7698 BLAKE MANAGER 7839 01-MAY-81 2850 500 30
7782 CLARK MANAGER 7839 09-JUN-81 2450 500 10
7369 SMITH CLERK 7902 17-DEC-80 800 500 20

Details of all those employees whose Commission value is not null value are displayed.
Ex: SELECT COUNT(*) AS Count FROM Employee WHERE mgr IS NOT NULL;

NOT NULL Constraint


• Not all constraints prevents a column to contain null values
• Once not null is applied to a particular column, you cannot enter null values to that column and restricted
to maintain only some proper value other than null
• A not-null constraint cannot be applied at table level

Example

CREATE TABLE STUDENT


(
ID INT NOT NULL,
NAME VARCHAR (20) NOT NULL,
AGE INT NOT NULL,
ADDRESS CHAR (25) ,
SALARY DECIMAL (18, 2),
PRIMARY KEY (ID)
);
• In the above example, we have applied not null on three columns ID, name and age which means whenever
a record is entered using insert statement all three columns should contain a value other than null
• We have two other columns address and salary, where not null is not applied which means that you can
leave the row as empty or use null value while inserting the record into the table.
NVL() NULL Function

• Using NVL function you can substitute a value in the place of NULL values.
• The substituted value then temporarily replaces the NULL values in your calculations or expression.
Remember that the substituted value only replaces the NULL value temporarily for the session and does not
affect the value stored in the table.
• Here is the syntax of NVL function NVL (exp, replacement-exp)
• As you can see NVL function takes two parameters exp and replacement exp. First parameter exp can be a
column name of a table or an arithmetic expression and the second parameter replacement expression will
be the value which you want to substitute when a NULL value is encountered.
• Always remember the data type of both the parameters must match otherwise the compiler will raise an
error.

Example : SELECT NVL (comm, 500) FROM employees WHERE salary>1000;

• On execution all the null values in the result set will get replaced by 500.
• Similarly we can use NVL null function while performing arithmetic expression.
• Again let’s take the same arithmetic expression which we used in the previous query where we added 100 to
the values of commission column.

Ex: SELECT NVL(comm,100), NVL(comm,100)+100 FROM employees WHERE salary>1000;

COMPLEX INTEGRITY CONSTRAINS IN SQL


A Key Constraint is a statement that a certain minimal subset of the fields of a relation is a unique identifier for a
tuple. The types of key constraints-

1. Primary key constraints


2. Unique key constraints
3. Foreign Key constraints
4. NOT NULL constraints
5. Check constraints

1. Primary key constraints


Primary key is the term used to identify one or more columns in a table that make a row of data unique.
Although the primary key typically consists of one column in a table, more than one column can comprise the primary
key.

Syntax to define a Primary key at column level:


column name datatype [CONSTRAINT constraint_name] PRIMARY KEY

Syntax to define a Primary key at table level:


[CONSTRAINT constraint_name] PRIMARY KEY (column_name1,column_name2,..)

For example, either the employee's Social Security number or an assigned employee identification number
is the logical primary key for an employee table. The objective is for every record to have a unique primary key or
value for the employee's identification number. Because there is probably no need to have more than one record for
each employee in an employee table, the employee identification number makes a logical primary key. The primary
key is assigned at table creation.
The following example identifies the EMP_ID column as the PRIMARY KEY for the EMPLOYEES table:
CREATE TABLE EMPLOYEE_TBL
(EMP_ID CHAR(9) NOT NULL PRIMARY KEY,
EMP_NAME VARCHAR (40) NOT NULL,
EMP_ST_ADDR VARCHAR (20) NOT NULL,
EMP_CITY VARCHAR (15) NOT NULL,
EMP_ST CHAR(2) NOT NULL,
EMP_ZIP INTEGER(5) NOT NULL,
EMP_PHONE INTEGER(10) NULL,
EMP_PAGER INTEGER(10) NULL);

2. Unique Constraints
A unique column constraint in a table is similar to a primary key in that the value in that column for every row
of data in the table must have a unique value. Although a primary key constraint is placed on one column, you can
place a unique constraint on another column even though it is not actually for use as the primary key.
Syntax to define a Unique key at column level:
[CONSTRAINT constraint_name] UNIQUE

Syntax to define a Unique key at table level:


[CONSTRAINT constraint_name] UNIQUE(column_name)

Ex:
CREATE TABLE EMPLOYEE_TBL
(EMP_ID CHAR(9) NOT NULL PRIMARY KEY,
EMP_NAME VARCHAR (40) NOT NULL,
EMP_ST_ADDR VARCHAR (20) NOT NULL,
EMP_CITY VARCHAR (15) NOT NULL,
EMP_ST CHAR(2) NOT NULL,
EMP_ZIP INTEGER(5) NOT NULL,
EMP_PHONE INTEGER(10) NULL UNIQUE,
EMP_PAGER INTEGER(10) NULL)

3. Foreign Key Constraints


A foreign key is a column in a child table that references a primary key in the parent table. A foreign key
constraint is the main mechanism used to enforce referential integrity between tables in a relational database. A
column defined as a foreign key is used to reference a column defined as a primary key in another table.

Syntax to define a Foreign key at column level:


[CONSTRAINT constraint_name] REFERENCES Referenced_Table_name(column_name)

Syntax to define a Foreign key at table level:


[CONSTRAINT constraint_name] FOREIGN KEY(column_name) REFERENCES referenced_table_name(column_name);

Ex:
CREATE TABLE EMPLOYEE_PAY_TBL
(EMP_ID CHAR(9) NOT NULL,
POSITION VARCHAR2(15) NOT NULL,
DATE_HIRE DATE NULL,
PAY_RATE NUMBER(4,2) NOT NULL,
DATE_LAST_RAISE DATE NULL,

4. NOT NULL Constraints


Previous examples use the keywords NULL and NOT NULL listed on the same line as each column and after the
data type. NOT NULL is a constraint that you can place on a table's column. This constraint disallows the entrance of
NULL values into a column; in other words, data is required in a NOT NULL column for each row of data in the table.
NULL is generally the default for a column if NOT NULL is not specified, allowing NULL values in a column.

Syntax to define a Not Null constraint:


[CONSTRAINT constraint name] NOT NULL

5. Check Constraints
Check (CHK) constraints can be utilized to check the validity of data entered into particular table columns. Check
constraints are used to provide back-end database edits, although edits are commonly found in the front-end
application as well. General edits restrict values that can be entered into columns or objects, whether within the
database itself or on a front-end application. The check constraint is a way of providing another protective layer for
the data.

Syntax to define a Check constraint:


[CONSTRAINT constraint_name] CHECK (condition)

Ex:
CREATE TABLE EMPLOYEE_TBL
(EMP_ID CHAR(9) NOT NULL,
EMP_NAME VARCHAR2(40) NOT NULL,
EMP_ST_ADDR VARCHAR2(20) NOT NULL,
EMP_CITY VARCHAR2(15) NOT NULL,
EMP_ST CHAR(2) NOT NULL,
EMP_ZIP NUMBER(5) NOT NULL,
EMP_PHONE NUMBER(10) NULL,
EMP_PAGER NUMBER(10) NULL),
PRIMARY KEY (EMP_ID),
CONSTRAINT CHK_EMP_ZIP CHECK ( EMP_ZIP = '46234');

TRIGGERS AND ACTIVE DATABASES

Active Databases :
Active Database is a database consisting of set of triggers. These databases are very difficult to be
maintained because of the complexity that arises in understanding the effect of these triggers. In such database,
DBMS initially verifies whether the particular trigger specified in the statement that modifies the database) is
activated or not, prior to executing the statement.
If the trigger is active then DBMS executes the condition part and then executes the action part only if the
specified condition is evaluated to true. It is possible to activate more than one trigger within a single statement.
In such situation, DBMS processes each of the trigger randomly. The execution of an action part of a
trigger may either activate other triggers or the same trigger that Initialized this action. Such types of trigger that
activates itself is called as ‘recursive trigger’. The DBMS executes such chains of trigger in some pre-defined
manner but it effects the concept of understanding.
Features of Active Database:
1. It possess all the concepts of a conventional database i.e. data modelling facilities, query language etc.
2. It supports all the functions of a traditional database like data definition, data manipulation, storage
management etc.
3. It supports definition and management of ECA rules.
4. It detects event occurrence.
5. It must be able to evaluate conditions and to execute actions.
6. It means that it has to implement rule execution.
Advantages :
1. Enhances traditional database functionalities with powerful rule processing capabilities.
2. Enable a uniform and centralized description of the business rules relevant to the information system.
3. Avoids redundancy of checking and repair operations.
4. Suitable platform for building large and efficient knowledge base and expert systems.

Triggers
Triggers are the SQL statements that are automatically executed when there is any change in the database. The
triggers are executed in response to certain events(INSERT, UPDATE or DELETE) in a particular table. These
triggers help in maintaining the integrity of the data by changing the data of the database in a systematic fashion.

Syntax
create trigger Trigger_name
(before | after)
[insert | update | delete]
on [table_name]
[for each row]
[trigger_body]

1. CREATE TRIGGER: These two keywords specify that a triggered block is going to be declared.
2. TRIGGER_NAME: It creates or replaces an existing trigger with the Trigger_name. The trigger name should
be unique.
3. BEFORE | AFTER: It specifies when the trigger will be initiated i.e. before the ongoing event or after the
ongoing event.
4. INSERT | UPDATE | DELETE: These are the DML operations and we can use either of them in a given
trigger.
5. ON[TABLE_NAME]: It specifies the name of the table on which the trigger is going to be applied.
6. FOR EACH ROW: Row-level trigger gets executed when any row value of any column changes.
7. TRIGGER BODY: It consists of queries that need to be executed when the trigger is called.

Example of Trigger in SQL


To understand the concept of trigger in SQL, first, we have to create the table on which trigger is to be executed.
The following query creates the Student_Trigger table in the SQL database:
1. CREATE TABLE Student_Trigger
2. (
3. Student_RollNo INT NOT NULL PRIMARY KEY,
4. Student_FirstName Varchar (100),
5. Student_EnglishMarks INT,
6. Student_PhysicsMarks INT,
7. Student_ChemistryMarks INT,
8. Student_MathsMarks INT,
9. Student_TotalMarks INT,
10. Student_Percentage );

The following query shows the structure of theStudent_Trigger table:

1. DESC Student_Trigger;
Field Type NULL Key Default Extra
Student_RollNo INT NO PRIMARY NULL
Student_FirstName Varchar(100) YES NULL
Student_EnglishMarks INT YES NULL
Student_PhysicsMarks INT YES NULL
Student_ChemistryMarks INT YES NULL
Student_MathsMarks INT YES NULL
Student_TotalMarks INT YES NULL
Student_Percentage INT YES NULL

The following query fires a trigger before the insertion of the student record in the table:

1. CREATE TRIGGER Student_Table_Marks


2. BEFORE INSERT
3. ON
4. Student_Trigger
5. FOR EACH ROW
6. SET new.Student_TotalMarks = new.Student_EnglishMarks + new.Student_PhysicsMarks + new.Student_Ch
emistryMarks + new.Student_MathsMarks,
7. new.Student_Percentage = ( new.Student_TotalMarks / 400) * 100;

The following query inserts the record into Student_Trigger table:


1. INSERT INTO Student_Trigger (Student_RollNo, Student_FirstName, Student_EnglishMarks, Student_Physics
Marks, Student_ChemistryMarks, Student_MathsMarks, Student_TotalMarks, Student_Percentage) VALUES
( 201, Sorya, 88, 75, 69, 92, 0, 0);

To check the output of the above INSERT statement, you have to type the following SELECT statement:

1. SELECT * FROM Student_Trigger;

Output:

Student_ Student_F Student_E Student_ Student_c Student_M Student_T Student_P


RollNo irstName nglishMar Physics hemistry athsMarks otalMarks ercentage
ks Marks Marks
201 Sorya 88 75 69 92 324 81

Advantages : Following are the three main advantages of triggers in Structured Query Language:
1. SQL provides an alternate way for maintaining the data and referential integrity in the tables.
2. Triggers helps in executing the scheduled tasks because they are called automatically.
3. They catch the errors in the database layer of various businesses.
4. They allow the database users to validate values before inserting and updating.

Disadvantages: Following are the main disadvantages of triggers in Structured Query Language:
1. They are not compiled.
2. It is not possible to find and debug the errors in triggers.
3. If we use the complex code in the trigger, it makes the application run slower.
4. Trigger increases the high load on the database system.

PL/SQL: Generic PL/SQL block, PL/SQL data types, Control structure, Procedures and
functions, Cursors, Database triggers.

GENERIC PL/SQL BLOCK


In PL/SQL, the code is not executed in single line format, but it is always executed by grouping the code into
a single element called Blocks. Blocks contain both PL/SQL as well as SQL instruction. All these instruction will be
executed as a whole rather than executing a single instruction at a time.
PL/SQL blocks can include variables, SQL statements, loops, constants, conditional statements and
exception handling. Blocks can also build a function or a procedure or a package.

Block Structure
PL/SQL blocks have a pre-defined structure in which the code is to be grouped. Below are different sections of
PL/SQL blocks.

1. Declaration section
2. Execution section
3. Exception-Handling section

Declaration Section
This is the first section of the PL/SQL blocks. This section is an optional part. This is the section in which the
declaration of variables, cursors, exceptions, subprograms, pragma instructions and collections that are needed in
the block will be declared. Below are few more characteristics of this part.

• This particular section is optional and can be skipped if no declarations are needed.
• This should be the first section in a PL/SQL block, if present.
• This section starts with the keyword ‘DECLARE’ for triggers and anonymous block. For other subprograms,
this keyword will not be present. Instead, the part after the subprogram name definition marks the
declaration section.
• This section should always be followed by execution section.

Execution Section
Execution part is the main and mandatory part which actually executes the code that is written inside it. Since the
PL/SQL expects the executable statements from this block this cannot be an empty block, i.e., it should have at least
one valid executable code line in it. Below are few more characteristics of this part.

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


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

Exception-Handling Section
The exception is unavoidable in the program which occurs at run-time and to handle this Oracle has provided an
Exception-handling section in blocks. This section can also contain PL/SQL statements. This is an optional section of
the PL/SQL blocks.

• This is the section where the exception raised in the execution block is handled.
• This section is the last part of the PL/SQL block.
• Control from this section can never return to the execution block.
• This section starts with the keyword ‘EXCEPTION’.
• This section should always be followed by the keyword ‘END’.

The Keyword ‘END’ marks the end of PL/SQL block.

PL/SQL Block Syntax


Below is the syntax of the PL/SQL block structure.
Note: A block should always be followed by ‘/’ which sends the information to the compiler about the end of the
block
Ex: DECLARE
message varchar2(20):= 'Hello, World!';
BEGIN
dbms_output.put_line(message);
END;
/

Types of PL/SQL block


PL/SQL blocks are of mainly two types.
1. Anonymous blocks
2. Named Blocks
Anonymous blocks: Anonymous blocks are PL/SQL blocks which do not have any names assigned to them.
They need to be created and used in the same session because they will not be stored in the server as database
objects.
Since they need not store in the database, they need no compilation steps. They are written and executed directly,
and compilation and execution happen in a single process.

Below are few more characteristics of Anonymous blocks.

• These blocks don’t have any reference name specified for them.
• These blocks start with the keyword ‘DECLARE’ or ‘BEGIN’.
• Since these blocks do not have any reference name, these cannot be stored for later purpose. They shall be
created and executed in the same session.
• They can call the other named blocks, but call to anonymous block is not possible as it is not having any
reference.
• It can have nested block in it which can be named or anonymous. It can also be nested in any blocks.
• These blocks can have all three sections of the block, in which execution section is mandatory, the other two
sections are optional.
Ex:
DECLARE
-- declare variable a, b and c
-- and these three variables datatype are integer
a number;
b number;
c number;
BEGIN
a:= 10;
b:= 100;
--find largest number
--take it in c variable
IF a > b THEN
c:= a;
ELSE
c:= b;
END IF;
dbms_output.put_line(' Maximum number in 10 and 100: ' || c);
END;
/

Named blocks: Named blocks have a specific and unique name for them. They are stored as the database
objects in the server. Since they are available as database objects, they can be referred to or used as long as it is
present on the server. The compilation process for named blocks happens separately while creating them as a
database objects.
Below are few more characteristics of Named blocks.

• These blocks can be called from other blocks.


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

1. Procedure
2. Function

Ex:
DECLARE

-- declare variable a, b and c


-- and these three variables datatype are integer
DECLARE
a number;
b number;
c number;
--Function return largest number of
-- two given number
FUNCTION findMax(x IN number, y IN number)
RETURN number
IS
z number;
BEGIN
IF x > y THEN
z:= x;
ELSE
Z:= y;
END IF;
RETURN z;
END;
BEGIN
a:= 10;
b:= 100;
c := findMax(a, b);
dbms_output.put_line(' Maximum number in 10 and 100 is: ' || c);
END;
/

PL/SQL DATA TYPES


Data Types in PL/SQL are used to define how the data will be stored, handled, and treated by Oracle during
the data storage and processing. Data types are associated with the specific storage format and range constraints.
In Oracle, each value or constant is assigned with a data type.
The main difference between PL/SQL and SQL data types is, SQL data type are limited to table column while the
PL/SQL data types are used in the PL/SQL blocks.

Following datatypes can be used in PL/SQL depending upon the type of data required:

So,we have 4 broader categories of datatypes and they are:


1. Scalar Types: These are basic datatypes which generally holds a single value like a number or a string of
characters. Scalar types have 4 different categories which are listed in the diagram above, namely Number
Types, Character and String, Boolean Types and Date and Time etc.

2. LOB Types: This datatype deals with large objects and is used to specify location of these large objects like
text files, images etc which are generally not stored outside the database.

3. Reference Types: This datatype is used to hold pointer values which generally stores address of other
program items.

4. Composite Types: Last but not the least, as the name suggests this type of data is a composition of individual
data which can be manipulated/processed separate as well.

PL/SQL Numeric Data Types and Subtypes


Following table lists out the PL/SQL pre-defined numeric data types and their sub-types −
S.No Data Type & Description
1 PLS_INTEGER
Signed integer in range -2,147,483,648 through 2,147,483,647, represented in 32 bits
2 BINARY_INTEGER
Signed integer in range -2,147,483,648 through 2,147,483,647, represented in 32 bits
3 BINARY_FLOAT
Single-precision IEEE 754-format floating-point number
4 BINARY_DOUBLE
Double-precision IEEE 754-format floating-point number
5 NUMBER(prec, scale)
Fixed-point or floating-point number with absolute value in range 1E-130 to (but not including) 1.0E126.
A NUMBER variable can also represent 0
6 DEC(prec, scale)
ANSI specific fixed-point type with maximum precision of 38 decimal digits
7 DECIMAL(prec, scale)
IBM specific fixed-point type with maximum precision of 38 decimal digits
8 NUMERIC(pre, secale)
Floating type with maximum precision of 38 decimal digits
9 DOUBLE PRECISION
ANSI specific floating-point type with maximum precision of 126 binary digits (approximately 38 decimal
digits)
10 FLOAT
ANSI and IBM specific floating-point type with maximum precision of 126 binary digits (approximately
38 decimal digits)
11 INT
ANSI specific integer type with maximum precision of 38 decimal digits
12 INTEGER
ANSI and IBM specific integer type with maximum precision of 38 decimal digits
13 SMALLINT
ANSI and IBM specific integer type with maximum precision of 38 decimal digits
14 REAL
Floating-point type with maximum precision of 63 binary digits (approximately 18 decimal digits)

PL/SQL Character Data Types and Subtypes


Following is the detail of PL/SQL pre-defined character data types and their sub-types –
S.No Data Type & Description
1 CHAR
Fixed-length character string with maximum size of 32,767 bytes
2 VARCHAR2
Variable-length character string with maximum size of 32,767 bytes
3 RAW
Variable-length binary or byte string with maximum size of 32,767 bytes, not interpreted by PL/SQL
4 NCHAR
Fixed-length national character string with maximum size of 32,767 bytes
5 NVARCHAR2
Variable-length national character string with maximum size of 32,767 bytes
6 LONG
Variable-length character string with maximum size of 32,760 bytes
7 LONG RAW
Variable-length binary or byte string with maximum size of 32,760 bytes, not interpreted by PL/SQL
8 ROWID
Physical row identifier, the address of a row in an ordinary table
9 UROWID
Universal row identifier (physical, logical, or foreign row identifier)
PL/SQL Large Object (LOB) Data Types
Data Type Description Size
BFILE Used to store large binary objects in operating System-dependent. Cannot
system files outside the database. exceed 4 gigabytes (GB).
BLOB Used to store large binary objects in the database. 8 to 128 terabytes (TB)
CLOB Used to store large blocks of character data in the 8 to 128 TB
database.
NCLOB Used to store large blocks of NCHAR data in the 8 to 128 TB
database.

CONTROL STRUCTURE

1. Decision Making Statements:


Decision-making structures require that the programmer specify one or more conditions to be
evaluated or tested by the program, along with a statement or statements to be executed if the condition is
determined to be true, and optionally, other statements to be executed if the condition is determined to be
false.
Following is the general form of a typical conditional (i.e., decision making) structure found in most of the
programming languages −
PL/SQL programming language provides following types of decision-making statements.
S.No Statement & Description
1 IF - THEN statement
The IF statement associates a condition with a sequence of statements enclosed by the
keywords THEN and END IF. If the condition is true, the statements get executed and if the
condition is false or NULL then the IF statement does nothing.
2 IF-THEN-ELSE statement
IF statement adds the keyword ELSE followed by an alternative sequence of statement. If the
condition is false or NULL, then only the alternative sequence of statements get executed. It
ensures that either of the sequence of statements is executed.
3 IF-THEN-ELSIF statement
It allows you to choose between several alternatives.
4 Case statement
Like the IF statement, the CASE statement selects one sequence of statements to execute.
However, to select the sequence, the CASE statement uses a selector rather than multiple
Boolean expressions. A selector is an expression whose value is used to select one of several
alternatives.
5 Searched CASE statement
The searched CASE statement has no selector, and it's WHEN clauses contain search conditions
that yield Boolean values.
6 nested IF-THEN-ELSE
You can use one IF-THEN or IF-THEN-ELSIF statement inside another IF-THEN or IF-THEN-
ELSIF statement(s).

IF - THEN statement
It is the simplest form of the IF control statement, frequently used in decision-making and changing the
control flow of the program execution.
The IF statement associates a condition with a sequence of statements enclosed by the
keywords THEN and END IF. If the condition is TRUE, the statements get executed, and if the condition
is FALSE or NULL, then the IF statement does nothing.
Syntax for IF-THEN statement is −
IF condition THEN
S;
END IF;
Where condition is a Boolean or relational condition and S is a simple or compound statement. Following is
an example of the IF-THEN statement −
IF (a <= 20) THEN
c:= c+1;
END IF;
If the Boolean expression condition evaluates to true, then the block of code inside the if statement will be
executed. If the Boolean expression evaluates to false, then the first set of code after the end of the if
statement (after the closing end if) will be executed.
Flow Diagram

Example 1
Let us try an example that will help you understand the concept −
DECLARE
a number(2) := 10;
BEGIN
a:= 10;
-- check the boolean condition using if statement
IF( a < 20 ) THEN
-- if condition is true then print the following
dbms_output.put_line('a is less than 20 ' );
END IF;
dbms_output.put_line('value of a is : ' || a);
END;
/
When the above code is executed at the SQL prompt, it produces the following result −
a is less than 20
value of a is : 10

PL/SQL procedure successfully completed.


IF-THEN-ELSE Statement
A sequence of IF-THEN statements can be followed by an optional sequence of ELSE statements, which
execute when the condition is FALSE.
Syntax for the IF-THEN-ELSE statement is −
IF condition THEN
S1;
ELSE
S2;
END IF;
Where, S1 and S2 are different sequence of statements. In the IF-THEN-ELSE statements, when the test
condition is TRUE, the statement S1 is executed and S2 is skipped; when the test condition is FALSE,
then S1 is bypassed and statement S2 is executed. For example −
IF color = red THEN
dbms_output.put_line('You have chosen a red car')
ELSE
dbms_output.put_line('Please choose a color for your car');
END IF;
If the Boolean expression condition evaluates to true, then the if-then block of code will be executed
otherwise the else block of code will be executed.
Flow Diagram

Example
Let us try an example that will help you understand the concept −

DECLARE
a number(3) := 100;
BEGIN
-- check the boolean condition using if statement
IF( a < 20 ) THEN
-- if condition is true then print the following
dbms_output.put_line('a is less than 20 ' );
ELSE
dbms_output.put_line('a is not less than 20 ' );
END IF;
dbms_output.put_line('value of a is : ' || a);
END;
/
When the above code is executed at the SQL prompt, it produces the following result −
a is not less than 20
value of a is : 100

PL/SQL procedure successfully completed.

IF-THEN-ELSIF Statement
The IF-THEN-ELSIF statement allows you to choose between several alternatives. An IF-THEN statement can
be followed by an optional ELSIF...ELSE statement. The ELSIF clause lets you add additional conditions.
When using IF-THEN-ELSIF statements there are a few points to keep in mind.
• It's ELSIF, not ELSEIF.
• An IF-THEN statement can have zero or one ELSE's and it must come after any ELSIF's.
• An IF-THEN statement can have zero to many ELSIF's and they must come before the ELSE.
• Once an ELSIF succeeds, none of the remaining ELSIF's or ELSE's will be tested.

The syntax of an IF-THEN-ELSIF Statement in PL/SQL programming language is −


IF(boolean_expression 1)THEN
S1; -- Executes when the boolean expression 1 is true
ELSIF( boolean_expression 2) THEN
S2; -- Executes when the boolean expression 2 is true
ELSIF( boolean_expression 3) THEN
S3; -- Executes when the boolean expression 3 is true
ELSE
S4; -- executes when the none of the above condition is true
END IF;
Example
DECLARE
a number(3) := 100;
BEGIN
IF ( a = 10 ) THEN
dbms_output.put_line('Value of a is 10' );
ELSIF ( a = 20 ) THEN
dbms_output.put_line('Value of a is 20' );
ELSIF ( a = 30 ) THEN
dbms_output.put_line('Value of a is 30' );
ELSE
dbms_output.put_line('None of the values is matching');
END IF;
dbms_output.put_line('Exact value of a is: '|| a );
END;
/
When the above code is executed at the SQL prompt, it produces the following result −
None of the values is matching
Exact value of a is: 100

PL/SQL procedure successfully completed.

CASE Statement
Like the IF statement, the CASE statement selects one sequence of statements to execute. However, to
select the sequence, the CASE statement uses a selector rather than multiple Boolean expressions. A
selector is an expression, the value of which is used to select one of several alternatives.
The syntax for the case statement in PL/SQL is −
CASE selector
WHEN 'value1' THEN S1;
WHEN 'value2' THEN S2;
WHEN 'value3' THEN S3;
...
ELSE Sn; -- default case
END CASE;
Flow Diagram

Example
DECLARE
grade char(1) := 'A';
BEGIN
CASE grade
when 'A' then dbms_output.put_line('Excellent');
when 'B' then dbms_output.put_line('Very good');
when 'C' then dbms_output.put_line('Well done');
when 'D' then dbms_output.put_line('You passed');
when 'F' then dbms_output.put_line('Better try again');
else dbms_output.put_line('No such grade');
END CASE;
END;
/
When the above code is executed at the SQL prompt, it produces the following result −
Excellent

PL/SQL procedure successfully completed.

Searched CASE Statement


The searched CASE statement has no selector and the WHEN clauses of the statement contain search
conditions that give Boolean values.
The syntax for the searched case statement in PL/SQL is −
CASE
WHEN selector = 'value1' THEN S1;
WHEN selector = 'value2' THEN S2;
WHEN selector = 'value3' THEN S3;
...
ELSE Sn; -- default case
END CASE;
Flow Diagram

Example
DECLARE
grade char(1) := 'B';
BEGIN
case
when grade = 'A' then dbms_output.put_line('Excellent');
when grade = 'B' then dbms_output.put_line('Very good');
when grade = 'C' then dbms_output.put_line('Well done');
when grade = 'D' then dbms_output.put_line('You passed');
when grade = 'F' then dbms_output.put_line('Better try again');
else dbms_output.put_line('No such grade');
end case;
END;
/
When the above code is executed at the SQL prompt, it produces the following result −
Very good

PL/SQL procedure successfully completed.

Nested IF-THEN-ELSE Statements


It is always legal in PL/SQL programming to nest the IF-ELSE statements, which means you can use
one IF or ELSE IF statement inside another IF or ELSE IF statement(s).
Syntax
IF( boolean_expression 1)THEN
-- executes when the boolean expression 1 is true
IF(boolean_expression 2) THEN
-- executes when the boolean expression 2 is true
sequence-of-statements;
END IF;
ELSE
-- executes when the boolean expression 1 is not true
else-statements;
END IF;
Example
DECLARE
a number(3) := 100;
b number(3) := 200;
BEGIN
-- check the boolean condition
IF( a = 100 ) THEN
-- if condition is true then check the following
IF( b = 200 ) THEN
-- if condition is true then print the following
dbms_output.put_line('Value of a is 100 and b is 200' );
END IF;
END IF;
dbms_output.put_line('Exact value of a is : ' || a );
dbms_output.put_line('Exact value of b is : ' || b );
END;
/
When the above code is executed at the SQL prompt, it produces the following result −
Value of a is 100 and b is 200
Exact value of a is : 100
Exact value of b is : 200

PL/SQL procedure successfully completed.

Looping Statements:
There may be a situation when you need to execute a block of code several number of times. In general,
statements are executed sequentially: The first statement in a function is executed first, followed by the second, and
so on.
Programming languages provide various control structures that allow for more complicated execution paths.
A loop statement allows us to execute a statement or group of statements multiple times and following is the general
form of a loop statement in most of the programming languages −
PL/SQL provides the following types of loop to handle the looping requirements. Click the following links to check
their detail.
S.No Loop Type & Description
1 PL/SQL Basic LOOP
In this loop structure, sequence of statements is enclosed between the LOOP and the END LOOP
statements. At each iteration, the sequence of statements is executed and then control resumes at the
top of the loop.
2 PL/SQL WHILE LOOP
Repeats a statement or group of statements while a given condition is true. It tests the condition before
executing the loop body.
3 PL/SQL FOR LOOP
Execute a sequence of statements multiple times and abbreviates the code that manages the loop
variable.
4 Nested loops in PL/SQL
You can use one or more loop inside any another basic loop, while, or for loop.

Basic Loop Statement


Basic loop structure encloses sequence of statements in between the LOOP and END
LOOP statements. With each iteration, the sequence of statements is executed and then control resumes at
the top of the loop.
The syntax of a basic loop in PL/SQL programming language is −
LOOP
Sequence of statements;
END LOOP;
Here, the sequence of statement(s) may be a single statement or a block of statements. An EXIT
statement or an EXIT WHEN statement is required to break the loop.
Example
DECLARE
x number := 10;
BEGIN
LOOP
dbms_output.put_line(x);
x := x + 10;
IF x > 50 THEN
exit;
END IF;
END LOOP;
-- after exit, control resumes here
dbms_output.put_line('After Exit x is: ' || x);
END;
/
When the above code is executed at the SQL prompt, it produces the following result −
10
20
30
40
50
After Exit x is: 60

PL/SQL procedure successfully completed.

WHILE LOOP Statement


It is an entry controlled loop which means that before entering in a while loop first the condition is
tested, if the condition is TRUE the statement or a group of statements get executed and if the condition
is FALSE the control will move out of the while loop.
Syntax
WHILE condition LOOP
sequence_of_statements
END LOOP;
Example
DECLARE
a number(2) := 10;
BEGIN
WHILE a < 20 LOOP
dbms_output.put_line('value of a: ' || a);
a := a + 1;
END LOOP;
END;
/
When the above code is executed at the SQL prompt, it produces the following result −
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15
value of a: 16
value of a: 17
value of a: 18
value of a: 19

PL/SQL procedure successfully completed.

FOR LOOP Statement


A FOR LOOP is a repetition control structure that allows you to efficiently write a loop that needs to execute
a specific number of times.
Syntax
FOR counter IN initial_value .. final_value LOOP
sequence_of_statements;
END LOOP;
Following is the flow of control in a For Loop −
• The initial step is executed first, and only once. This step allows you to declare and initialize any
loop control variables.
• Next, the condition, i.e., initial_value .. final_value is evaluated. If it is TRUE, the body of the
loop is executed. If it is FALSE, the body of the loop does not execute and the flow of control
jumps to the next statement just after the for loop.
• After the body of the for loop executes, the value of the counter variable is increased or
decreased.
• The condition is now evaluated again. If it is TRUE, the loop executes and the process repeats
itself (body of loop, then increment step, and then again condition). After the condition
becomes FALSE, the FOR-LOOP terminates.
Following are some special characteristics of PL/SQL for loop −
• The initial_value and final_value of the loop variable or counter can be literals, variables, or
expressions but must evaluate to numbers. Otherwise, PL/SQL raises the predefined exception
VALUE_ERROR.
• The initial_value need not be 1; however, the loop counter increment (or decrement) must be
1.
• PL/SQL allows the determination of the loop range dynamically at run time.
Example
DECLARE
a number(2);
BEGIN
FOR a in 10 .. 20 LOOP
dbms_output.put_line('value of a: ' || a);
END LOOP;
END;
/
When the above code is executed at the SQL prompt, it produces the following result −
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15
value of a: 16
value of a: 17
value of a: 18
value of a: 19
value of a: 20

PL/SQL procedure successfully completed.

Nested Loops
PL/SQL allows using one loop inside another loop. Following section shows a few examples to illustrate the
concept.
The syntax for a nested basic LOOP statement in PL/SQL is as follows −
LOOP
Sequence of statements1
LOOP
Sequence of statements2
END LOOP;
END LOOP;
The syntax for a nested FOR LOOP statement in PL/SQL is as follows −
FOR counter1 IN initial_value1 .. final_value1 LOOP
sequence_of_statements1
FOR counter2 IN initial_value2 .. final_value2 LOOP
sequence_of_statements2
END LOOP;
END LOOP;
The syntax for a nested WHILE LOOP statement in Pascal is as follows −
WHILE condition1 LOOP
sequence_of_statements1
WHILE condition2 LOOP
sequence_of_statements2
END LOOP;
END LOOP;
Example
The following program uses a nested basic loop to find the prime numbers from 2 to 100 −
DECLARE
i number(3);
j number(3);
BEGIN
i := 2;
LOOP
j:= 2;
LOOP
exit WHEN ((mod(i, j) = 0) or (j = i));
j := j +1;
END LOOP;
IF (j = i ) THEN
dbms_output.put_line(i || ' is prime');
END IF;
i := i + 1;
exit WHEN i = 50;
END LOOP;
END;
/
When the above code is executed at the SQL prompt, it produces the following result −
2 is prime
3 is prime
5 is prime
7 is prime
11 is prime
13 is prime
17 is prime
19 is prime
23 is prime
29 is prime
31 is prime
37 is prime
41 is prime
43 is prime
47 is prime

PL/SQL procedure successfully completed.

PROCEDURES AND FUNCTIONS

Procedure:
A Procedure in PL/SQL is a subprogram unit that consists of a group of PL/SQL statements that can be
called by name. Each procedure in PL/SQL has its own unique name by which it can be referred to and called. This
subprogram unit in the Oracle database is stored as a database object.

Note: Subprogram is nothing but a procedure, and it needs to be created manually as per the requirement. Once
created they will be stored as database objects.

Below are the characteristics of Procedure subprogram unit in PL/SQL:


• Procedures are standalone blocks of a program that can be stored in the database.
• Call to these PLSQL procedures can be made by referring to their name, to execute the PL/SQL statements.
• It is mainly used to execute a process in PL/SQL.
• It can have nested blocks, or it can be defined and nested inside the other blocks or packages.
• It contains declaration part (optional), execution part, exception handling part (optional).
• The values can be passed into Oracle procedure or fetched from the procedure through parameters.
• These parameters should be included in the calling statement.
• A Procedure in SQL can have a RETURN statement to return the control to the calling block, but it cannot
return any values through the RETURN statement.
• Procedures cannot be called directly from SELECT statements. They can be called from another block or
through EXEC keyword.

Syntax:
CREATE OR REPLACE PROCEDURE
<procedure_name>
(
<parameterl IN/OUT <datatype>
..
.
)
[ IS | AS ]
<declaration_part>
BEGIN
<execution part>
EXCEPTION
<exception handling part>
END;

• CREATE PROCEDURE instructs the compiler to create new procedure in Oracle. Keyword ‘OR REPLACE’
instructs the compile to replace the existing procedure (if any) with the current one.
• Procedure name should be unique.
• Keyword ‘IS’ will be used, when the stored procedure in Oracle is nested into some other blocks. If the
procedure is standalone then ‘AS’ will be used. Other than this coding standard, both have the same
meaning.

Example1: Creating Procedure and calling it using EXEC

In this example, we are going to create an Oracle procedure that takes the name as input and prints the welcome
message as output. We are going to use EXEC command to call procedure.

CREATE OR REPLACE PROCEDURE welcome_msg (p_name IN VARCHAR2)


IS
BEGIN
dbms_output.put_line (‘Welcome '|| p_name);
END;
/
EXEC welcome_msg (‘MBU’);

Code Explanation:
• Code line 1: Creating the procedure with name ‘welcome_msg’ and with one parameter ‘p_name’ of ‘IN’
type.
• Code line 4: Printing the welcome message by concatenating the input name.
• Procedure is compiled successfully.
• Code line 7: Calling the procedure using EXEC command with the parameter ‘MBU’. Procedure is executed,
and the message is printed out as “Welcome MBU”.

Functions
Functions is a standalone PL/SQL subprogram. Like PL/SQL procedure, functions have a unique name by which it can
be referred. These are stored as PL/SQL database objects. Below are some of the characteristics of functions.

• Functions are a standalone block that is mainly used for calculation purpose.
• Function use RETURN keyword to return the value, and the datatype of this is defined at the time of
creation.
• A Function should either return a value or raise the exception, i.e. return is mandatory in functions.
• Function with no DML statements can be directly called in SELECT query whereas the function with DML
operation can only be called from other PL/SQL blocks.
• It can have nested blocks, or it can be defined and nested inside the other blocks or packages.
• It contains declaration part (optional), execution part, exception handling part (optional).
• The values can be passed into the function or fetched from the procedure through the parameters.
• These parameters should be included in the calling statement.
• A PLSQL function can also return the value through OUT parameters other than using RETURN.
• Since it will always return the value, in calling statement it always accompanies with assignment operator to
populate the variables.

Syntax
CREATE OR REPLACE FUNCTION
<procedure_name>
(
<parameterl IN/OUT <datatype>
)
RETURN <datatype>
[ IS | AS ]
<declaration_part>
BEGIN
<execution part>
EXCEPTION
<exception handling part>
END;

• CREATE FUNCTION instructs the compiler to create a new function. Keyword ‘OR REPLACE’ instructs the
compiler to replace the existing function (if any) with the current one.
• The Function name should be unique.
• RETURN datatype should be mentioned.
• Keyword ‘IS’ will be used, when the procedure is nested into some other blocks. If the procedure is
standalone then ‘AS’ will be used. Other than this coding standard, both have the same meaning.

Example1: Creating Function and calling it using Anonymous Block

In this program, we are going to create a function that takes the name as input and returns the welcome message
as output. We are going to use anonymous block and select statement to call the function.
CREATE OR REPLACE FUNCTION welcome_msgJune ( p_name IN VARCHAR2) RETURN VAR.CHAR2
IS
BEGIN
RETURN (‘Welcome ‘|| p_name);
END;
/
DECLARE
lv_msg VARCHAR2(250);
BEGIN
lv_msg := welcome_msg_func (‘Guru99’);
dbms_output.put_line(lv_msg);
END;
SELECT welcome_msg_func(‘Guru99:) FROM DUAL;

Code Explanation:

• Code line 1: Creating the Oracle function with name ‘welcome_msg_func’ and with one parameter ‘p_name’
of ‘IN’ type.
• Code line 2: declaring the return type as VARCHAR2
• Code line 5: Returning the concatenated value ‘Welcome’ and the parameter value.
• Code line 8: Anonymous block to call the above function.
• Code line 9: Declaring the variable with datatype same as the return datatype of the function.
• Code line 11: Calling the function and populating the return value to the variable ‘lv_msg’.
• Code line 12: Printing the variable value. The output you will get here is “Welcome Guru99”
• Code line 14: Calling the same function through SELECT statement. The return value is directed to the
standard output directly.

DATABASE TRIGGERS
A trigger is a set of SQL statements that reside in system memory with unique names. It is a specialized category
of stored procedure that is called automatically when a database server event occurs. Each trigger is always associated
with a table.
A trigger is called a special procedure because it cannot be called directly like a stored procedure. The key
distinction between the trigger and procedure is that a trigger is called automatically when a data modification event
occurs against a table. A stored procedure, on the other hand, must be invoked directly.

The following are the main characteristics that distinguish triggers from stored procedures:
o We cannot manually execute/invoked triggers.
o Triggers have no chance of receiving parameters.
o A transaction cannot be committed or rolled back inside a trigger.

Syntax of Trigger
We can create a trigger in SQL Server by using the CREATE TRIGGER statement as follows:
1. CREATE TRIGGER schema.trigger_name
2. ON table_name
3. AFTER {INSERT, UPDATE, DELETE}
4. [NOT FOR REPLICATION]
5. AS
6. {SQL_Statements}

The parameter descriptions of this syntax illustrate below:


schema: It is an optional parameter that defines which schema the new trigger belongs to.
trigger_name: It is a required parameter that defines the name for the new trigger.
table_name: It is a required parameter that defines the table name to which the trigger applies. Next to the table
name, we need to write the AFTER clause where any events like INSERT, UPDATE, or DELETE could be listed.
NOT FOR REPLICATION: This option tells that SQL Server does not execute the trigger when data is modified as part
of a replication process.
SQL_Statements: It contains one or more SQL statements that are used to perform actions in response to an event
that occurs
Example of Trigger in SQL Server
Let us understand how we can work with triggers in the SQL Server. We can do this by first creating a table named
'Employee' using the below statements:
1. CREATE TABLE Employee
2. (
3. Id INT PRIMARY KEY,
4. Name VARCHAR(45),
5. Salary INT,
6. Gender VARCHAR(12),
7. DepartmentId INT
8. )

Next, we will insert some record into this table as follows:


1. INSERT INTO Employee VALUES (1,'Steffan', 82000, 'Male', 3),
2. (2,'Amelie', 52000, 'Female', 2),
3. (3,'Antonio', 25000, 'male', 1),
4. (4,'Marco', 47000, 'Male', 2),
5. (5,'Eliana', 46000, 'Female', 3)

We can verify the insert operation by using the SELECT statement. We will get the below output:
1. SELECT * FROM Employee;

We will also create another table named 'Employee_Audit_Test' to automatically store transaction records of each
operation, such as INSERT, UPDATE, or DELETE on the Employee table:
1. CREATE TABLE Employee_Audit_Test
2. (
3. Id int IDENTITY,
4. Audit_Action text
5. )
Now, we will create a trigger that stores transaction records of each insert operation on the Employee table into the
Employee_Audit_Test table. Here we are going to create the insert trigger using the below statement:

1. CREATE TRIGGER trInsertEmployee


2. ON Employee
3. FOR INSERT
4. AS
5. BEGIN
6. Declare @Id int
7. SELECT @Id = Id from inserted
8. INSERT INTO Employee_Audit_Test
9. VALUES ('New employee with Id = ' + CAST(@Id AS VARCHAR(10)) + ' is added at ' + CAST(Getdate() AS VAR
CHAR(22)))
10. END

After creating a trigger, we will try to add the following record into the table:
1. INSERT INTO Employee VALUES (6,'Peter', 62000, 'Male', 3)
If no error is found, execute the SELECT statement to check the audit records.

You might also like