Module 3
Module 3
• UNION
• It combines the similar columns from two tables into one resultant table. All columns that are
participating in the UNION operation should be Union Compatible.
• This operator combines the records from both the tables into one. If there are duplicate values as a
result, then it eliminates the duplicate. The resulting records will be from both table and distinct.
• Suppose we have to see the employees in EMP_TEST and EMP_DESIGN tables. If we are using
UNION, then it will combine both the results from tables in to one set.
SELECT EMP_ID, EMP_NAME, EMP_ADDRESS, EMP_SSN FROM EMP_TEST
UNION
SELECT EMP_ID, EMP_NAME, EMP_ADDRESS, EMP_SSN FROM EMP_DESIGN;
• We can notice that Result will have same column names as first query. Duplicate record – 104 from
EMP_TEST and EMP_DESIGN are showed only once in the result set. Records are sorted in the result.
• UNION ALL
• This operation is also similar to UNION, but it does not eliminate the duplicate records. It shows all the
records from both the tables.
• All other features are same as UNION. We can have conditions in the SELECT query. It need not be a
simple SELECT query.
Look at the same example below with UNION ALL operation.
SELECT EMP_ID, EMP_NAME, EMP_ADDRESS, EMP_SSN FROM EMP_TEST
UNION ALL
SELECT EMP_ID, EMP_NAME, EMP_ADDRESS, EMP_SSN FROM EMP_DESIGN;
• INTERSECT
• This operator is used to pick the records from both the tables which are common to them. In other
words it picks only the duplicate records from the tables.
• Even though it selects duplicate records from the table, each duplicate record will be displayed only
once in the result set. It should have UNION Compatible columns to run the query with this operator.
Same example above when used with INTERSECT operator, gives below result.
SELECT EMP_ID, EMP_NAME, EMP_ADDRESS, EMP_SSN FROM EMP_TEST
INTERSECT
SELECT EMP_ID, EMP_NAME, EMP_ADDRESS, EMP_SSN FROM EMP_DESIGN;
• We have INTERSECT ALL operator too. But it is same as INTERSET. There is no difference between
them like we have between UNION and UNION ALL.
Now, let us join these two tables in our SELECT statement as shown below.
This would produce the following result.
+----+---------+--------+-----------------+
| ID | NAME | AMOUNT | DATE |
+----+---------+--------+-----------------+
| 1 |Ramesh | NULL | NULL |
| 5 |Hardik | NULL | NULL |
| 6 |Komal | NULL | NULL |
| 7 |Muffy | NULL | NULL |
+----+---------+--------+---------------------+
Sub Queries
● Sub query is inner query or nested query where the inner query is executed first and its result is used in
the outer query. Sub queries will be executed only once. It has some of the following features:
● Sub queries can be used with SELECT, INSERT, UPDATE and DELETE statements.
● We can use sub queries to compare the results using =, <, >, >=, <=, IN, BETWEEN etc operators in
the WHERE clause.
● Inner queries are enclosed inside a parenthesis.
● It should return only one row of data. If there is more than one row are returned by sub query then IN
operator has to be used.
● In most of the cases only one column is used in inner SELECT statement.
4. sub queries in the SELECT statement :
To display the details of all employees whose salary is equal to minimum salary.
FROM employees
● ORDER BY clause cannot be used inside sub query. Ideally it does not signify anything if used too
because it should return only one row. Even if we have to sort the columns, then we can use GROUP BY
clause.
● In SQL, one can have up to 255 sub queries in the WHERE clause.
The following shows the syntax of a subquery with the ANY operator:
For example, the following condition evaluates to true if x is greater than any value returned by the
subquery. So the condition x > SOME (1,2,3) evaluates to true if x is greater than 1.
Note that the SOME operator is a synonym for the ANY operator so you can use them interchangeably.
The following query finds all employees whose salaries are greater than or equal to the highest salary of
every department.
SELECT
employee_id, first_name, last_name, salary
FROM
employees
WHERE
salary >= SOME (SELECT
MAX(salary)
FROM
employees
GROUP BY department_id);
Code language: SQL (Structured Query Language) (sql)
In this example, the subquery finds the highest salary of employees in each department. The outer query
looks at these values and determines which employee’s salaries are greater than or equal to any highest
salary by department.
All operator:● Sub queries can be used to compare the values using ALL clauses. ALL is used when we
have to compare the list of values using AND clause. If all of the list values are matching, then result will
be displayed.
SELECT * FROM STUDENT
WHERE (AGE) > ALL
(SELECT AGE FROM STUDENT
WHERE STD_ID BETWEEN 100 AND 105);
● Here if there is any student whose age is above students from 100 to 105, then result will be displayed.
SQL subquery with the ALL operator
The syntax of the subquery when it is used with the ALL operator is as follows:
The following condition evaluates to true if x is greater than every value returned by the subquery.
For example, suppose the subquery returns three value one, two, and three. The following condition
evaluates to true if x is greater than 3.
The following query uses the GROUP BY clause and MIN() function to find the lowest salary by
department:
SELECT
MIN(salary)
FROM
employees
GROUP BY department_id
ORDER BY MIN(salary) DESC;
Code language: SQL (Structured Query Language) (sql)
The following example finds all employees whose salaries are greater than the lowest salary of every
department:
SELECT
employee_id, first_name, last_name, salary
FROM
employees
WHERE
salary >= ALL (SELECT
MIN(salary)
FROM
employees
GROUP BY department_id)
ORDER BY first_name , last_name;
Code language: SQL (Structured Query Language) (sql)
You can use a subquery in the FROM clause of the SELECT statement as follows:
SELECT
ROUND(AVG(average_salary), 0)
FROM
(SELECT
AVG(salary) average_salary
FROM
employees
GROUP BY department_id) department_salar
To find the salaries of all employees, their average salary, and the difference between the salary
of each employee and the average salary.
SELECT
employee_id, first_name, last_name, salary,
(SELECT ROUND(AVG(salary), 0) FROM employees) average_salary,
salary - (SELECT ROUND(AVG(salary), 0) FROM employees) difference
FROM
employees;
1. Find all the employees who earn more than the average salary in their department.
SELECT last_name, salary, department_id
FROM employees outer
WHERE salary >
(SELECT AVG(salary)
FROM employees
WHERE department_id =
outer.department_id);
2. Use a correlated subquery to delete rows in one table based on the rows from another table.
delete from emp e where deptno = (select deptno from dept where
deptno = e.deptno);
update emp a
set comm = (select avg(sal) from emp b
where a.deptno = b.deptno);
1.In case of correlated subquery inner query depends on outer query while in case of noncorrelated
query inner query or subquery doesn't depends on outer query and run by its own.
2.In case of correlated subquery, outer query executed before inner query or subquery while in case of
NonCorrelated subquery inner query executes before outer query.
3.Correlated Sub-queries are slower than non correlated subquery and should be avoided in favor of sql
joins.
4.Common example of correlated subquery is using exits and not exists keyword while non correlated
query mostly use IN or NOT IN keywords.
EXISTS Operator :
The EXISTS operator tests for existence of rows in the results set of the subquery. If a subquery row
value is found the condition is flagged TRUE and the search does not continue in the inner query, and
if it is not found then the condition is flagged FALSE and the search continues in the inner query.
EXIST operator :
To find employees who have at least one person reporting to them.
SELECT empno, ename, job, deptno
FROM emp outer
WHERE EXISTS (SELECT *
FROM emp
WHERE mgrid = outer.empno);
Joins
SQL Join is used to fetch data from two or more tables, which is joined to appear as single set of data.
● SQL Join is used for combining column from two or more tables by using values common to both
tables.
● Join Keyword is used in SQL queries for joining two or more tables. Minimum required condition for
joining table, is (n-1) where n, is number of tables.
● A table can also join to itself known as, Self Join.
Types of Join
The following are the types of JOIN that we can use in SQL.
Inner Join
Equi Join
Natural Join
Non-equi join
self join
Outer Join
Left outer join
Right outer join
Full outer join
Cross JOIN or Cartesian Product
Consider the following tables
Emp, dept, salgrade tables:
EQUI Join
This is a simple JOIN in which the result is based on matched data as per the equality condition specified
in the query. Syntax is,
SELECT column-name-list
from table-name1 JOIN table-name2
WHERE table-name1.column-name = table-name2.column-name;
Natural JOIN
Natural Join is a type of Inner join which is based on column having same name and same datatype
present in both the tables to be joined. Natural Join Syntax is,
SELECT * from
table-name1
NATURAL JOIN
table-name2;
Example:
Non-equi join:
This is a simple JOIN in which the result is based on matched data as per the condition that includes the
operator other than equality operator specified in the query. Syntax is,
To display the employee details, their salaries, and their salary grades
Self join:
A table can also join to itself known as, Self Join.
To display the employee details and their manager details from emp table
Outer joins:
Outer Join is based on both matched and unmatched data
Consider the emp and dept tables as given below
Left Outer join:
The left outer join returns a result table with the matched data of two tables then remaining rows of the
left table and null for the right table's column. Left Outer Join syntax is,
SELECT column-name-list
from table-name1
LEFT OUTER JOIN
table-name2
on table-name1.column-name = table-name2.column-name;
OR
select column-name-list
from table-name1
LEFT OUTER JOIN
table-name2
using column-name;
Example:
select column-name-list
from table-name1
RIGHT OUTER JOIN
table-name2
on table-name1.column-name = table-name2.column-name;
or
select column-name-list
from table-name1
RIGHT OUTER JOIN
table-name2
using column-name;
Example:
Full Join
The full outer join returns a result table with the matched data of two table then remaining rows of
both left table and then the right table. Full Outer Join Syntax is,
select column-name-list
from table-name1
FULL OUTER JOIN
table-name2
on table-name1.column-name = table-name2.column-name;
or
select column-name-list
from table-name1
FULL OUTER JOIN
table-name2
using column-name;
Example:
SQL Aggregate Functions
An aggregate function in SQL returns one value after calculating multiple values of a column. We often
use aggregate functions with the GROUP BY and HAVING clauses of the SELECT statement.
Useful aggregate functions:
AVG() - Returns the average value
COUNT() - Returns the number of rows
FIRST() - Returns the first value
LAST() - Returns the last value
MAX() - Returns the largest value
MIN() - Returns the smallest value
SUM() - Returns the sum
Consider the table given below
AVG() Function
The AVG function is used to calculate the average value of the numeric type. AVG function returns the
average of all non-Null values.
Syntax
AVG()
or
AVG( [ALL|DISTINCT] expression )
Example:
Computing average marks of students.
SELECT AVG(MARKS) AS AvgMarks FROM Students;
SUM() Function
Sum function is used to calculate the sum of all selected columns. It works on numeric fields only.
Syntax
SUM()
or
SUM( [ALL|DISTINCT] expression )
Example: SUM()
SELECT SUM(MARKS) AS TotalMarks FROM Students;
COUNT() function
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.
COUNT function uses the COUNT(*) that returns the count of all the rows in a specified table. COUNT(*)
considers duplicate and Null.
Syntax
COUNT(*)
or
COUNT( [ALL|DISTINCT] expression )
Example:
Computing total number of students.
SELECT COUNT(*) AS NumStudents FROM Students;
MAX Function
MAX function is used to find the maximum value of a certain column. This function determines the
largest value of all selected values of a column.
Syntax
MAX()
or
MAX( [ALL|DISTINCT] expression )
Example:
Fetching maximum marks among students from the Students table. SELECT MAX(MARKS) AS MaxMarks
FROM Students;
MIN Function
MIN function is used to find the minimum value of a certain column. This function determines the
smallest value of all selected values of a column.
Syntax
MIN()
or
MIN( [ALL|DISTINCT] expression )
Example
Fetching minimum marks among students from the Students table. SELECT MIN(MARKS) AS MinMarks
FROM Students;
LAST() Function
The LAST() function returns the last value of the selected column.
syntax
SELECT LAST(column_name) FROM table_name
Example:Fetching marks of last student from the Students table.
SELECT LAST(MARKS) AS MarksLast FROM Students;
FIRST() Function
The FIRST() function returns the first value of the selected column.
Syntax
SELECT FIRST(column_name) FROM table_name
Example
Fetching marks of first student from the Students table.
SELECT FIRST(MARKS) AS MarksFirst FROM Students;
SUM() function
SUM() function returns the total sum of a numeric column
The GROUP BY Statement
The GROUP BY statement is used in conjunction with the aggregate functions to group the result-set by
one or more columns.
SQL GROUP BY Syntax
SELECT column_name, aggregate_function(column_name) FROM table_name WHERE column_name
operator value GROUP BY column_name
If a field in a table is optional, it is possible to insert a new record or update a record without adding a
value to this field. Then, the field will be saved with a NULL value.
The following SQL lists all customers with a NULL value in the "Address" field:
Example
The IS NOT NULL operator is used to test for non-empty values (NOT NULL values).
The following SQL lists all customers with a value in the "Address" field:
Example
SELECT CustomerName, ContactName, Address
FROM Customers
WHERE Address IS NOT NULL;
Relational Algebra
Relational algebra is one of the two formal query languages associated with the relational model.
Queries in algebra are composed using a collection of operators. A fundamental property is that
every operator in the algebra accepts one or more relational instances as arguments and returns a
relation instance as the result. The relational algebra is procedural.
28 Yuppy 9 35.0
31 Lubber 8 55.5
44 Guppy 5 35.0
58 Rusty 10 35.0
Fig: Instance S1 Sailors
22 101 10/10/96
58 103 11/12/96
Relational algebra includes operators to select rows from a relation (σ) and to project columns
(π). These operations allow us to manipulate data in a single relation.
In general, the selection operator σ specifies the tuples to get through a selection condition. Here the
selection condition is a Boolean combination of terms that have the form attribute op constant or
attribute1 op attribute2, where op is one of the relational operators <, <=, =, ≠, >=, or >.
Consider the instance S2 of the Sailors relation shown in figure, we can find the Sailors with
rating above 8 by the following expression:
28 Yuppy 9 35.0
58 Rusty 10 35.0
The projection operator π allows us to extract columns from a relation. For example, we can find
out all sailors names and ratings by the following expression:
sname rating
Yuppy 9
Lubber 8
Guppy 5
Rusty 10
Similarly, we can find the names and ratings of sailors with rating above 8 by the following
expression:
sname rating
Yuppy 9
Rusty 10
2) Set Operations
The following standard operations on sets are available in relational algebra: union (U),
intersection (∩),
set-difference (─), and cross-product (Х).
Union:
R U S returns a relation instance containing all tuples that occur in either relation instance R or
relation instance S (or both).
R and S must be union-compatible, and the schema of the result is identical to the
conditions hold:
Corresponding fields, taken in order from left to right, have the same domains
22 Dustin 7 45.0
31 Lubber 8 55.5
58 Rusty 10 35.0
28 Yuppy 9 35.0
44 Guppy 5 35.0
Intersection:
R ∩ S returns a relation instance containing all tuples that occur in both R and S. The relations R
and S must be union-compatible, and the scheme of the result is same as the schema of R.
31 Lubber 8 55.5
58 Rusty 10 35.0
Set-difference:
R ─ S returns a relation instance containing all tuples that occur in R but not in S. The relations
R and S must be union-compatible, and the schema of the result is identical to the schema of R.
22 Dustin 7 45.0
Cross-product:
R Х S returns a relation instance whose schema contains all the fields of R followed by all the
fields of S. The cross product operation is sometimes called as Cartesian product.
The result of the relational algebra expression includes the field names in such a way that
naming conflicts can arise in some cases. For example, in S1 Х R1. Hence we have to rename the
fields or rename the relation. Relation algebra provides renaming operator ρ for this purpose.
The expression ρ (R (F), E) takes a relational algebra expression E and returns an instance of a
relation R. R contains the same tuples as the result of E and has the same schema as E, but some
fields are renamed. F is the list of fields renamed and is in the form oldname ─> newname or
position ─> newname.
For example, the expression ρ (C (1 ─> sid1, 5 ─> sid2), S1 Х R1) returns a relation with the
following schema:
C (sid1: integer, sname: string, rating: integer, age: real, sid2: integer, bid: integer, day: date)
4) Joins
The join operation is used to combine the information from two or more relations. Join can be
defined as a cross-product followed by selection and projection. There are several variants of
join operation:
Conditional Join:
The most general version of the join operation accepts a join condition c and a pair of relational
instances as arguments and returns a relation instance. The operation is defined as follows:
R C S = σc (R Х S)
shown below:
Equijoin:
A common special case of the join operation R S is when the join condition consists
solely of equalities of the form R.name1 = S.name2, that is, equalities between two fields in R
and S. The join operation with such equality condition is called equijoin.
For example, the result of S1 R.sid = S. sid R1 is shown below:
Note that the fields in the equijoin condition appears only once in the resultant instance.
Natural Join:
A further special case of the join operation R S is an equijoin in which equalities are specified on
all common fields of R and S. In this case, we can simply omit the join condition. By default, the
equality condition is employed on all common fields.
We call this as natural join and can simply be denoted as S1 R1. The result of this expression
is same as above, since the only common field is sid.
5) Division
We discuss division through an example. Consider two relation instances A and B in which A
has two fields x and y and B has just one filed y, with the same domain as in A. We define the
division operation A/B as the set of all x values such that for every y value in B, there is a tuple
<x,y> in A.
Division is illustrated in figure below. Consider the relation A listing the parts(pid) supplied by
suppliers(sid) and the relation B listing the parts(pid). A/B i computes suppliers who supply all
parts listed in relation instance Bi.
Sno pno A A/B1 Sno
Pno S1
S1 P1
P2 S2
S1 P2 B1
S3
S1 P3
Sno S4
B2 S1 P4
P2
S2 P1
P4 Sno
S2 P2 A/B2
B3 S3 P2 S1
Pno
S4 P2 S4
P1
S4 P4
P2 A/B3
Sno
P4
S1
Relational Calculus
1) Tuple Relational Calculus (TRC): Variables in TRC take tuples as the values.
2) Domain Relational Calculus (DRC): Variables in DRC range over field values.
R Є Rel
R.a op S.b
R.a op constant, or constant op R.a
Where p and q are themselves are formulas and p(R) denotes a formula with the
variable R.
Example Relations:
2. Find the loan number for each loan of an amount greater than $1200
3. Find the names of all customers having a loan, an account, or both at the bank
4. Find the names of all customers who have a loan and an account at the bank
5. Find the names of all customers having a loan at the Perryridge branch
{t | s borrower(t[customer-name] = s[customer-name]
u loan(u[branch-name] = “Perryridge”
u[loan-number] = s[loan-number]))}
6. Find the names of all customers who have a loan at the Perryridge branch, but no account at any
branch of the bank
Example Queries:
1. Find the loan-number, branch-name, and amount for loans of over $1200
{ l, b, a | l, b, a loan a > 1200}
2. Find the names of all customers who have a loan of over $1200
{ c | l, b, a ( c, l borrower l, b, a loan a > 1200)}
3. Find the names of all customers who have a loan from the Perryridge branch and the loan
amount:
{ c, a | l ( c, l borrower b( l, b, a loan b = “Perryridge”))}
or
{ c, a | l ( c, l borrower l, “Perryridge”, a loan)}
4. Find the names of all customers having a loan, an account, or both at the Perryridge branch:
{ c | l ({ c, l borrower b,a( l, b, a loan b = “Perryridge”))
a( c, a depositor b,n( a, b, n account b = “Perryridge”))}
5. Find the names of all customers who have an account at all branches located in Brooklyn:
{ c | s, n ( c, s, n customer) x,y,z( x, y, z branch y = “Brooklyn”)
a,b( x, y, z account c,a depositor)}
PL/SQL
PL/SQL (procedural language extension to Structured Query Language)
PL/SQL is a procedural language extension to Structured Query Language (SQL).
The purpose of PL/SQL is to combine database language and procedural programming language.
The basic unit in PL/SQL is called a block and is made up of three parts: a declarative part, an
executable part and an exception-building part.
PL/SQL enables users to mix SQL statements with procedural constructs, it is possible to use
PL/SQL blocks and subprograms to group SQL statements before sending them to Oracle for
execution. Without PL/SQL, Oracle must process SQL statements one at a time. In a network
environment, this can affect traffic flow and slow down response time.
PL/SQL blocks can be compiled once and stored in executable form to improve response time. A
PL/SQL program that is stored in a database in compiled form and can be called by name is
referred to as a stored procedure. A PL/SQL stored procedure that is implicitly started when an
INSERT, UPDATE or DELETE statement is issued against an associated table is called a
trigger.
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:
● PL/SQL is basically a procedural language, which provides the functionality of decision
making, iteration and many more features of procedural programming languages.
● PL/SQL can execute a number of queries in one block using single command.
● 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.
● PL/SQL provides a feature to handle the exception which occurs in PL/SQL block known as
exception handling block.
● Applications written in PL/SQL are portable to computer hardware or operating system where
Oracle is operational.
● PL/SQL Offers extensive error checking.
⮚ Differences between SQL and PL/SQL:
● 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.
● 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 data type [NOT NULL := value];
● Example program to declare variables in PL/SQL :
● SET SERVEROUTPUT ON is used to display the buffer used by the dbms_output. var1
INTEGER 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 etc.
● It also supports variables used in SQL as well like NUMBER (prec, scale), varchar, varchar2
etc.
● PL/SQL procedure successfully completed is displayed when the code is compiled and
executed successfully. Slash (/) after END;
● The slash (/) tells the SQL*Plus to execute the block.
⮚ INITIALISING VARIABLES
● The variables can also be initialised just like in other programming languages. Let us see an
example for the same:
Let us see an example on PL/SQL to demonstrate all above concepts in one single block of code.
Let us see an example on PL/SQL to demonstrate all above concepts in one single block of code.
Syntax (IF-THEN-ELSIF)
The syntax for IF-THEN-ELSIF in Oracle/PLSQL is:
IF condition1 THEN
{...statements to execute when condition1 is TRUE...}
END IF;
You use the IF-THEN-ELSIF syntax, when you want to execute one set
of statements when condition1 is TRUE or a different set of statements when condition2 is
TRUE.
Syntax (IF-THEN-ELSIF-ELSE)
The syntax for IF-THEN-ELSIF-ELSE in Oracle/PLSQL is:
IF condition1 THEN
{...statements to execute when condition1 is TRUE...}
ELSE
{...statements to execute when both condition1 and condition2 are FALSE...}
END IF;
You use the IF-THEN-ELSIF-ELSE syntax, when you want to execute one set
of statements when condition1 is TRUE, a different set of statements when condition2 is TRUE,
or a different set of statements when all previous conditions (ie: condition1 and condition2) are
FALSE
Iterative Statements in PL/SQL
Iterative control Statements are used when we want to repeat the execution of one or more
statements for specified number of times.
There are three types of loops in PL/SQL:
• Simple Loop
• While Loop
• For Loop
1) Simple Loop
A Simple Loop is used when a set of statements is to be executed at least
once before the loop terminates. An EXIT condition must be specified in
the loop, otherwise the loop will get into an infinite number of iterations.
When the EXIT condition is satisfied the process exits from the loop.
General Syntax to write a Simple Loop is:
LOOP
statements;
EXIT;
{or EXIT WHEN condition;}
END LOOP;
These are the important steps to be followed while using Simple Loop.
1) Initialise a variable before the loop body.
2) Increment the variable in the loop.
3) Use a EXIT WHEN statement to exit from the Loop. If you use a EXIT statement without
WHEN condition, the statements in the loop is executed only once.
2) While Loop
A WHILE LOOP is used when a set of statements has to be executed as long as a condition is
true. The condition is evaluated at the beginning of each iteration. The iteration continues until
the condition becomes false.
A FOR LOOP is used to execute a set of statements for a predetermined number of times.
Iteration occurs between the start and end integer values given. The counter is always
incremented by 1. The loop exits when the counter reaches the value of the end integer.
CASE Statement
A CASE statement is similar to IF-THEN-ELSIF statement that selects one alternative based
on the condition from the available options.
Unlike IF-THEN-ELSIF, the CASE statement can also be used in SQL statements.
ELSE block in CASE statement holds the sequence that needs to be executed when none of
the alternatives got selected.
Syntax:
CASE (expression)
WHEN <valuel> THEN action_blockl;
WHEN <value2> THEN action_block2;
WHEN <value3> THEN action_block3;
ELSE action_block_default;
END CASE;
Example:
DECLARE
a NUMBER :=55;
b NUMBER :=5;
arth_operation VARCHAR2(20) :='MULTIPLY';
BEGIN
dbms_output.put_line('Program started.' );
CASE (arth_operation)
WHEN 'ADD' THEN dbms_output.put_line('Addition of the numbers are: '|| a+b );
WHEN 'SUBTRACT' THEN dbms_output.put_line('Subtraction of the numbers are: '||a-b );
WHEN 'MULTIPLY' THEN dbms_output.put_line('Multiplication of the numbers are: '|| a*b );
WHEN 'DIVIDE' THEN dbms_output.put_line('Division of the numbers are:'|| a/b);
ELSE dbms_output.put_line('No operation action defined. Invalid operation');
END case;
dbms_output.put_line('Program completed.' );
END;
/
begin
len:=length(str1);
declare
n number;
m number;
rev number:=0;
r number;
begin
n:=12321;
m:=n;
while n>0
loop
r:=mod(n,10);
rev:=(rev*10)+r;
n:=trunc(n/10);
end loop;
if m=rev
then
dbms_output.put_line('number is palindrome');
else
dbms_output.put_line('number is not palindrome');
end if;
end;
/
PL/SQL Program to Find Factorial of a Number
declare
n number;
fac number:=1;
i number;
begin
n:=&n;
for i in 1..n
loop
fac:=fac*i;
end loop;
dbms_output.put_line('factorial='||fac);
end;
/
PL/SQL Records
Records are another type of datatypes which oracle allows to be defined as a placeholder.
Records are composite datatypes, which means it is a combination of different scalar datatypes
like char, varchar, number etc. Each scalar data types in the record holds a value. A record
can be visualized as a row of data. It can contain all the contents of a row.
Declaring a record:
To declare a record, you must first define a composite datatype; then declare a record for that
type.
The following table consolidates the different ways in which you can define and declare a pl/sql
record.
Usage
Syntax
Example:
1.
DECLARE
TYPE employee_type IS RECORD
(employee_id number(5),
employee_first_name varchar2(25),
employee_last_name employee.last_name%type,
employee_dept employee.dept%type);
employee_salary employee.salary%type;
employee_rec employee_type;
2.
DECLARE
employee_rec employee%ROWTYPE;
Example:
Consider the table emp as below.
Procedures:
Procedures and functions allow code to be named and stored in the database, making code reuse
simpler and more efficient. Procedures and functions still retain the block format, but the
DECLARE keyword is replaced by PROCEDURE or FUNCTION definitions,
Stored procedures can also have parameters. These parameters have to be valid SQL types, and
have one of three different modes: IN, OUT, or IN OUT. IN parameters are arguments to' the
stored procedure. OUT parameters are returned from the stored procedure; it assigns values to all
OUT parameters that the user can process. INOUT parameters combine the properties of IN and
OUT parameters: They contain values to be passed to the stored procedures, and the stored
procedure can set their values as return values.
Example:
output:
Functions
Functions are similar to procedures but return a single value.
output:
Example: Using %ROWTYPE with a PL/SQL Record
Proc2.sql
Proc1.sql
create or replace procedure proc1 as
empid emp.empno%TYPE; -- employee_id datatype is NUMBER(6)
emplname emp.ename%TYPE; -- last_name datatype is VARCHAR2(25)
BEGIN
empid:= 7900; -- this is OK because it fits in NUMBER(6)
-- empid := 3018907; -- this is too large and will cause an overflow
emplname:= 'Patel'; -- this is OK because it fits in VARCHAR2(25)
DBMS_OUTPUT.PUT_LINE('Employee ID: ' || empid); -- display data
DBMS_OUTPUT.PUT_LINE('Employee name: ' || emplname); -- display dataet
update emp set ename=emplname where empno=empid;
END;
/
CURSORS
A cursor is a pointer to a private SQL area that stores information about the processing of a
SELECT or data manipulation language (DML) statement (INSERT, UPDATE, DELETE, or
MERGE). Cursor management of DML statements is handled by Oracle Database, but PL/SQL
offers several ways to define and manipulate cursors to execute SELECT statements.
Implicit cursors are automatically created and used every time a Select statement is issued in
PL/SQL, when there is no explicitly defined cursor. Explicit cursors, as the name suggests,
are defined explicitly by the developer. In PL/SQL an explicit cursor is actually a named
query defined using the key word cursor.
Implicit cursors are automatically created and used by Oracle each time a select statement is
issued. If an implicit cursor is used, the Database Management System (DBMS) will perform
the open, fetch and close operations automatically. An implicit cursor is automatically
associated with each Data Manipulation Language (DML) statements, namely INSERT,
UPDATE and DELETE statements. Also, an implicit cursor is used to process SELECT
INTO statements. When fetching data using implicit cursors NO_DATA_FOUND exception
can be raised when the SQL statement returns no data. Furthermore, implicit cursors can
raise TOO_MANY_ROWS exceptions when the SQL statement returns more than one row.
explicit cursors are queries defined using a name. An explicit cursor can be thought of as a
pointer to a set of records and the pointer can be moved forward within the set of records.
Explicit cursors provide the user the complete control over opening, closing and fetching
data. Also, multiple rows can be fetched using an explicit cursor. Explicit cursors can also
take parameters just like any function or procedure so that the variables in the cursor can be
changed each time it is executed. In addition, explicit cursors allow you to fetch a whole row
in to a PL/SQL record variable. When using an explicit cursor, first it needs to be declared
using a name. Cursor attributes can be accessed using the name given to cursor. After
declaring, cursor needs to be opened first. Then fetching can be started. If multiple rows need
to be fetched, the fetching operation needs to be done inside a loop. Finally, the cursor needs
to be closed.
PL/SQL creates implicit cursor and manages automatically means implcit open & close takes
place. It used when sql statement return only one row.It has 4 attributes SQL
%ROWCOUNT, SQL%FOUND, SQL%NOTFOUND, SQL%ISOPEN.
.EXPLICIT: It is created & managed by the programmer. It needs every time explicit
open,fetch & close. It is used when sql statement returns more than one row. It has also 4
attributes CUR_NAME%ROWCOUNT, CUR_NAME%FOUND, CUR_NAME
%NOTFOUND, CUR_NAME%ISOPEN. It process several rows by using loop. The
programmer can pass the parameter too to explicit cursor
%NOTFOUND
%ISOPEN
3 Always returns FALSE for implicit cursors, because Oracle closes the SQL cursor
automatically after executing its associated SQL statement.
%ROWCOUNT
4 Returns the number of rows affected by an INSERT, UPDATE, or DELETE
statement, or returned by a SELECT INTO statement.
Implicit Cursor:
Implicit cursors are automatically created by Oracle whenever an SQL statement is executed,
when there is no explicit cursor for the statement. Programmers cannot control the implicit
cursors and the information in it.
Whenever a DML statement (INSERT, UPDATE and DELETE) is issued, an implicit cursor is
associated with this statement. For INSERT operations, the cursor holds the data that needs to be
inserted. For UPDATE and DELETE operations, the cursor identifies the rows that would be
affected.
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
+----+----------+-----+-----------+----------+
DECLARE
total_rows number(2);
BEGIN
UPDATE customers
IF sql%notfound THEN
total_rows := sql%rowcount;
END IF;
END;
When the above code is executed at the SQL prompt, it produces the following result −
6 customers selected
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2500.00 |
| 2 | Khilan | 25 | Delhi | 2000.00 |
| 3 | kaushik | 23 | Kota | 2500.00 |
| 4 | Chaitali | 25 | Mumbai | 7000.00 |
| 5 | Hardik | 27 | Bhopal | 9000.00 |
| 6 | Komal | 22 | MP | 5000.00 |
+----+----------+-----+-----------+----------+
In the following PL/SQL code block, the select statement makes use of an implicit cursor:
Begin
Update emp Where 1=2;
Dbms_output.put_line (sql%rowcount ||’ ‘|| ‘ rows are affected by the update statement’);
End;
The following single-row query calculates and returns the total salary for a department. PL/SQL
creates an implicit cursor for this statement:
DECLARE
rows_deleted NUMBER;
BEGIN
DELETE * FROM emp;
rows_deleted := SQL%ROWCOUNT;
END;
Example:
Explicit Cursors
Explicit cursors are programmer-defined cursors for gaining more control over the context
area. An explicit cursor should be defined in the declaration section of the PL/SQL Block. It is
created on a SELECT Statement which returns more than one row.
CURSOR c_customers IS
OPEN c_customers;
CLOSE c_customers;
Example
1. Write a cursor program to retrieve the details of all the employees using
cursors.
SQL> ed cursor1.sql;
declare
cursor cemp is select empno, ename, job, sal from emp;
vemp cemp%rowtype;
begin
open cemp;
dbms_output.put_line(' Details of the employees :- ');
loop
fetch cemp into vemp ;
exit when (cemp% notfound);
dbms_output.put_line(vempno.empno || ' ' || vempno.ename || ' ' ||
vemp.job || ‘ ‘ || vempno.sal);
end loop;
close cemp;
end;
3. Write a PL/SQL block to update the salary of each employee in department
20 by raising the salary by 20% and insert a record in empraise table.
SQL> create table empraise(empno number(5), raisedate date, raiseamt
number(5));
Table created.
SQL> ed cursor3.sql;
declare
cursor cempr is select empno, sal from emp where deptno=20;
vemp cempr%rowtype;
begin
open cempr;
loop
fetch cempr into vemp;
exit when cempr% notfound;
update emp set sal = vemp.sal+(vemp.sal*.20) where
empno=vemp.empno;
insert into empraise values(vemp.empno, sysdate, vemp.sal*0.20);
end loop;
commit;
close cempr;
end;
Triggers
What are triggers?
Triggers are named PL/SQL blocks which are stored in the database or we can also say that they
are specialized stored programs which execute implicitly when a triggering event occurs which
means we cannot call and execute them directly instead they only get triggered by events in the
database.
1. A DML Statement. For example Update, Insert or Delete, executing on any table of your
database. You can program your trigger to execute either BEFORE or AFTER executing
your DML statement. For example you can create a trigger which will get fired Before
the Update statement. Or you can create a trigger which will get triggered after the
execution of your INSERT DML statement.
2. Next type of triggering statement can be a DDL Statement such as CREATE or ALTER.
These triggers can also be executed either BEFORE or AFTER the execution of your
DDL statement. These triggers are generally used by DBAs for auditing purposes and
they really come in handy when you want to keep an eye on the various changes on your
schema such as who created the object or which user. Just like some cool spy tricks.
3. A system event. Yes, you can create a trigger on a system event and by system event I
mean shut down or startup of your database.
4. Another type of triggering event can be User Events such as log off or log on onto your
database. You can create a trigger which will either execute before or after the event and
record the information such as time of event occur, the username who created it.
A procedure is executed explicitly from another block via a procedure call with passing
arguments, while a trigger is executed (or fired) implicitly whenever the triggering event (DML:
INSERT, UPDATE, or DELETE) happens, and a trigger doesn't accept arguments.
Triggers exist in a separate namespace from procedure, package, tables (that share the same
namespace), which means that a trigger can have the same name as a table or procedure.
A triggering event or statement is the SQL statement that causes a trigger to be fired. A
triggering event can be an INSERT, UPDATE, or DELETE statement on a table, a DML event
or a DDL event or system event or a user event
A trigger restriction specifies a Boolean (logical) expression that must be TRUE for the trigger to
fire. The trigger action is not executed if the trigger restriction evaluates to FALSE or
UNKNOWN.
A trigger restriction is an option available for triggers that are fired for each row. Its function is
to control the execution of a trigger conditionally. You specify a trigger restriction using a
WHEN clause.
Trigger Action
A trigger action is the procedure (PL/SQL block) that contains the SQL statements and PL/SQL
code to be executed when a triggering statement is issued and the trigger restriction evaluates to
TRUE.
Similar to stored procedures, a trigger action can contain SQL and PL/SQL statements, define
PL/SQL language constructs (variables, constants, cursors, exceptions, and so on), and call
stored procedures. Additionally, for row trigger, the statements in a trigger action have access to
column values (new and old) of the current row being processed by the trigger. Two correlation
names provide access to the old and new values for each column.
Types of triggers
There are two types of triggers in Oracle including row-level triggers and statement-level
triggers
• Statement-level triggers execute once for each transaction. For example, if a single
transaction inserted 500 rows into the Customer table, then a statement-level trigger on that
table would only be executed once.
• Statement-level triggers therefore are not often used for data-related activities; they are
normally used to enforce additional security measures on the types of transactions that may be
performed on a table.
• Statement-level triggers are the default type of triggers created and are identified
by omitting the FOR EACH ROW clause in the CREATE TRIGGER command.
• Since triggers occur because of events, they may be set to occur immediately before or after
those events. The events that execute triggers are database transactions, triggers can be
executed immediately BEFORE or AFTER the statements INSERTs, UPDATEs, DELETEs.
• AFTER row-level triggers are frequently used in auditing applications, since they do not fire
until the row has been modified.
Clearly, there is a great deal of flexibility in the design of a trigger.
• Triggers for multiple INSERT, UPDATE, DELETE commands on a table can be combined
into a single trigger (using OR), provided they are all at the same level (row-level or statement-
level), e.g., INSERT OR UPDATE OR DELETE.
• However, you can not combine BEFORE or AFTER, e.g., BEFORE OR AFTER is illegal.
In a row level trigger, the trigger fires for each related row. And sometimes it is required to know
the value before and after the DML statement.
Oracle has provided two clauses in the RECORD-level trigger to hold these values. We can use
these clauses to refer to the old and new values inside the trigger body.
:NEW – It holds a new value for the columns of the base table/view during the trigger execution
:OLD – It holds old value of the columns of the base table/view during the trigger execution
This clause should be used based on the DML event. Below table will specify which clause is
valid for which DML statement (INSERT/UPDATE/DELETE).
Examples
TRIGGERS’s PROGRAMS :
1. Trigger on Insertion.
SQL> create table log(access_date date,operation varchar2(40), table
varchar(10));
Table created.
SQL> create or replace trigger trigger2 after insert on class
2 begin
3 insert into log values(sysdate,' 1 row successfully inserted ','
CLASS ');
4 dbms_output.put_line('CONGRATULATIONS!!!');
5 end;
6/
Trigger created.
SQL> insert into class values(1260,’Vikram’);
Output :-
CONGRATULATIONS!!!
83
1 row created.
SQL> select * from log;
ACCESS_DATE OPERATION TABLE
02 – APR – 2005 1 row successfully inserted CLASS
2. Trigger on updation.
SQL> create or replace trigger trigger3 after update on class
2 begin
3 insert into log values(sysdate,' 1 row successfully updated ',' CLASS ');
4 dbms_output.put_line('Success!!!');
5 end;
6/
Trigger created.
SQL> update class set name=’Uday’ where roll=1260;
Output :-
Success!!!
1 row updated.
SQL> select * from log;
ACCESS_DATE OPERATION TABLE
02 – APR – 2005 1 row successfully updated CLASS
02 – APR – 2005 1 row successfully inserted CLASS
84
3. Trigger on updation (Statement Level Trigger).
SQL> create or replace trigger trigger3 after update on class
2 begin
3 dbms_output.put_line ('Success!!!');
4 insert into log values(sysdate, 'One row successfully updated ',' CLASS ');
5 end;
6/
Trigger created.
SQL> update class set grade='A' where marks>90;
Output :-
Success!!!
3 rows updated.
SQL> select * from log;
ACCES DATE OPERATION TABLENAME
85
02 – APR – 2005 One row successfully updated CLASS
02 – APR – 2005 1 row successfully updated CLASS
02 – APR – 2005 1 row successfully inserted CLASS
4. Trigger on updation (Row Level Trigger).
SQL> create or replace trigger trigger4 after update on class for each row
2 begin
3 dbms_output.put_line ('Success!!!');
4 insert into log values(sysdate, '1 row Updated ',' CLASS ');
5 end;
6/
Trigger created.
SQL> update class set grade='A' where marks>90;
Output :-
Success!!!
Success!!!
Success!!!
3 rows updated.
SQL> select * from log;
ACCES DATE OPERATION TABLENAME
86
02 – APR – 2005 1 row updated CLASS
02 – APR – 2005 1 row updated CLASS
02 – APR – 2005 1 row updated CLASS
02 – APR – 2005 One row successfully updated CLASS
02 – APR – 2005 1 row successfully updated CLASS
02 – APR – 2005 1 row successfully inserted CLASS
5. Trigger on Deletion.
SQL> create or replace trigger trigger4 after update on class
2 begin
3 dbms_output.put_line ('A row deleted!!!');
4 insert into log values(sysdate, '1 row successfully deleted ',' CLASS ');
5 end;
6/
Trigger created.
SQL> delete from class where roll=1201;
Output :-
A row deleted!!!
1 row deleted.
SQL> select * from log;
ACCES DATE OPERATION TABLENAME
87
02 – APR – 2005 1 row successfully deleted CLASS
02 – APR – 2005 1 row updated CLASS
02 – APR – 2005 1 row updated CLASS
02 – APR – 2005 1 row updated CLASS
02 – APR – 2005 One row successfully updated CLASS
02 – APR – 2005 1 row successfully updated CLASS
02 – APR – 2005 1 row successfully inserted CLASS
Example2: Create an update trigger that displays salary changes for every salary updation
in customer table
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
+----+----------+-----+-----------+----------+
sal_diff number;
BEGIN
END;
/
Triggering a Trigger
Let us perform some DML operations on the CUSTOMERS table. Here is one INSERT
statement, which will create a new record in the table −
Old salary:
New salary: 7500
Salary difference:
Because this is a new record, old salary is not available and the above result comes as null. Let
us now perform one more DML operation on the CUSTOMERS table. The UPDATE statement
will update an existing record in the table −
UPDATE customers
WHERE id = 2;
Assertions
An assertion is a predicate expressing a condition we wish the database to always satisfy.
Domain constraints, functional dependency and referential integrity are special forms of
assertion.
Where a constraint cannot be expressed in these forms, we use an assertion, e.g.
o Ensuring the sum of loan amounts for each branch is less than the sum of all account
balances at the branch.
o Ensuring every loan customer keeps a minimum of $1000 in an account.
An assertion takes the form,
create assertion assertion-name check predicate
Example1: to create an assertion called “salary_assertion” that checks that no employee in the
“employees” table has a salary greater than $100,000, you could use the following statement:
Example 2: to create an assertion named nomanager which checks that all the tuples in manager
relation with department_id being NULL as not a manager.
Example3: to check the sum of all loan amounts for each branch must be less than the sum of all
account balances at the branch. This can be satisfied by creating assertion as below:
Assertions are useful for enforcing data integrity and ensuring that the data in the database meets
certain conditions. They can be used to enforce business rules or to ensure the consistency of the
data. However, they can also be time-consuming to create and maintain, so they are not always
used in practice.