NLP Module-3
NLP Module-3
One of the characteristics of RDBMS is that it should support all the transaction on the records in the
table by means relational operations.
● That means it should have strong query language which supports relational algebra.
● There are three main relational algebras on sets – UNION, SET DIFFERENCE and SET
INTERSECT. The same is implemented in database query language using set operators.
● Relational set operators are used to combine or subtract the records from two tables.
● These operators are used in the SELECT query to combine the records or remove the records.
● In order to set operators to work in database, it should have same number of columns participating
in the query and the datatypes of respective columns should be same. This is called Union
Compatibility.
● The resulting records will also have same number of columns and same datatypes for the respective
column.
• 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.
SQL - EXCEPT Clause
The SQL EXCEPT clause/operator is used to combine two SELECT statements and returns rows
from the first SELECT statement that are not returned by the second SELECT statement. This means
EXCEPT returns only rows, which are not available in the second SELECT statement.
Just as with the UNION operator, the same rules apply when using the EXCEPT operator. MySQL
does not support the EXCEPT operator.
Syntax
The basic syntax of EXCEPT is as follows.
SELECT column1 [, column]
FROM table1 [, table2]
[WHERE condition]
EXCEPT
SELECT column1 [, column2]
FROM table1 [, table2]
[WHERE condition]
Here, the given condition could be any given expression based on your requirement.
Example
Consider the following two tables.
Table 1 − CUSTOMERS Table is as follows.
● 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.
FROM employees
SELECT *
FROM employees
WHERE salary =
(SELECT max(salary) FROM employees);
● For example, if we need to find the students who are of Alex’s age and are from
his place, then the inner / sub query can be written as below:
SELECT * FROM STUDENT
WHERE (AGE, ADDRESS) =
(SELECT AGE, ADDRESS
FROM STUDENT
WHERE STD_NAME = ‘Alex’);
● 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.
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 t0 105, then result will be
displayed.
You can use a subquery in the FROM clause of the SELECT statement as follows:
• 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;
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
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,
Self join:
A table can also join to itself known as, Self Join.
Outer joins:
Outer Join is based on both matched and unmatched data
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
● 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:
● Assignment operator (:=) : It is used to assign a value to a variable.
DISPLAYING OUTPUT
● The outputs are displayed by using DBMS_OUTPUT which is a built-in package that enables the
user to display output, debugging information, and send messages from PL/SQL blocks,
subprograms, packages, and triggers.
● Let us see an example to see how to display a message using PL/SQL:
Let us see an example on PL/SQL to demonstrate all above concepts in one single block of code.
Syntax (IF-THEN-ELSIF)
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)
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
• 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.
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.
3) FOR Loop
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 reachs 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;
/
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;
/
begin
n:=&n;
for i in 1..n
loop
fac:=fac*i;
end loop;
dbms_output.put_line('factorial='||fac);
end;
/
PL/SQL Records
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
TYPE record_type_name IS RECORD Define a composite datatype,
(column_name1 datatype, column_name2 where each field is scalar.
datatype, ...);
col_name table_name.column_name%type; Dynamically define the datatype
of a column based on a database
column.
record_name record_type_name; Declare a record based on a user-
defined type.
record_name table_name%ROWTYPE; Dynamically declare a record
based on an entire row of a table.
Each column in the table
corresponds to a field in the
record.
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:
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.
1
%FOUND
Returns TRUE if an INSERT, UPDATE, or DELETE statement affected one or more rows or a
SELECT INTO statement returned one or more rows. Otherwise, it returns FALSE.
%NOTFOUND
%ISOPEN
3 Always returns FALSE for implicit cursors, because Oracle closes the SQL cursor automatically
after executing its associated SQL statement.
%ROWCOUNT
+----+----------+-----+-----------+----------+
| 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
PL/SQL procedure successfully completed.
If you check the records in customers table, you will find that the rows have been updated –
Select * from customers;
+----+----------+-----+-----------+----------+
| 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.
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
Select * from customers;
+----+----------+-----+-----------+----------+
| 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
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 −
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
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:
Example 4:
Ensuring every loan customer keeps a minimum of $1000 in an account.
create assertion balance-constraint check
(not exists (select * from loan L
where not exists (select * from borrower B, depositor D, account A
where L.loan# = B.loan# and B.cname = D.cname
and D.account# = A.account# and A.balance >= 1000 )))
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.
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.
Consider the following instances to illustrate the relational algebra operators:
The various operators that form the relational algebraic query are:
1) Selection and Projection
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:
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(S2)
This evaluates to the relation shown below:
Similarly, we can find the names and ratings of sailors with rating above 8 by the following expression:
Πsname,rating(σrating>8 (S2))
This evaluates to the relation shown below:
2) Set Operations
The following standard operations on sets are available in relational algebra: union(U), intersection(∩),
set-difference(─), and cross-product (Х).
Union:
RUS 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 schema of R. Two relation
instances are said to be union-compatible if the following conditions hold:
Corresponding fields, taken in order from left to right, have the same domains
Ex : The union of S1and S2(S1 U S2) is shown below:
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.
Ex: The intersection of S1and S2(S1 ∩S2) is shown below:
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.
Ex: The Set-difference of S1and S2 (S1─S2) is shown below:
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.
Ex: The Cross-product of S1and R1(S1ХR1) is shown below:
3) Renaming
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)
Thus is defined to be a cross-product followed by a selection. For example, the result of
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
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
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/Bi computes suppliers who supply all parts listed in relation
instance Bi.
Relational Calculus
• Comes in two flavors: Tuple relational calculus (TRC) and Domain relational calculus
(DRC).
• Calculus has variables, constants, comparison ops, logical connectives and quantifiers.
• Expressions in the calculus are called formulas. An answer tuple is essentially an assignment of
constants to variables that make the formula evaluate to true.
A tuple variable is a variable that takes on tuples of a particular relation schema as values. A TRC
query has the form { T / p(T) }, where T is a tuple variable and p(T) denotes a formula that describes
T.
Syntax of TRC Queries:
A nonprocedural query language, where each query is of the form
{t | P (t) }
It is the set of all tuples t such that predicate P is true for t
t is a tuple variable, t[A] denotes the value of tuple t on attribute A
t r denotes that tuple t is in relation r
P is a formula similar to that of the predicate calculus
Where p and q are themselves are formulas and p(R) denotes a formula with the variable R. Predicate
Calculus Formula
x Þ y º ¬x v y
5. Set of quantifiers:
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)}