SQL and PLSQL
SQL and PLSQL
SQL and PLSQL
suppliers
supplier_id supplier_name contact_name
SQL: CREATE TABLE Statement
For example:
customers
customer_id customer_name address city
SQL: Drop TABLE Statement
The DROP TABLE statement allows you to remove a table
from the database.
For example:
2- Update statement
Used to Modify Existing data values in the Table.
3- Delete statement
Used to Delete Existing data Rows from The Table.
SQL :Insert into statement (1)
The INSERT statement allows you to insert a new data row into a table.
For Example
UPDATE table
SET column = expression
Here ,You apply the change to all the values stored in this column
SQL :Update statement (1)
For Example:
UPDATE supplier
SET name = 'HP'
UPDATE table
SET column = expression
Where condition
Here ,You apply the change to all the values stored in this column
The Where Clause
The WHERE clause allows you to filter the results from any SQL
statement - insert, update, or delete statement.
Where <Condition>
The Where Clause
Where <Condition>
Condition
Combination
And OR
Both conditions must be One condition is enough to be
evaluated to True evaluated to true
Supplier_Id= 100 Supplier_id =1 00
and Or
city = ‘riyadh’ City=‘riyadh’
SQL :Update statement (1)
For Example:
UPDATE supplier
SET supplier_name = 'HP‘
Where supplier_name = ‘IBM’
Here , only the supplier_name with the value IBM will be changed to HP
SQL :Delete statement (1)
The DELETE statement allows you to delete a single record or multiple
records from a table.
Here , You Delete all the data rows from the table
SQL :Delete statement (1)
For Example:
Here , You Delete all the data rows from the supplier table
SQL :Delete statement (2)
The DELETE statement allows you to delete a single record or multiple
records from a table.
Here , You Delete only the data rows which meet the where condition
SQL :Delete statement (2)
For Example:
Here , You Delete only the data rows that meet the where condition
Retrieving Data
1- The Select Statement
SELECT columns
FROM tables
For example
SELECT columns
FROM tables
WHERE predicates;
SELECT *
FROM suppliers
WHERE city = 'Newark';
Where <Condition>
The Where Clause
Where <Condition>
Condition
Combination
And OR
Both conditions must be One condition is enough to be
evaluated to True evaluated to true
Supplier_Id= 100 Supplier_id =1 00
and Or
city = ‘riyadh’ City=‘riyadh’
SQL: "AND" Condition
The syntax for the AND condition is:
SELECT columns
FROM tables
WHERE column1 = 'value1‘ and column2 = 'value2';
SELECT *
FROM suppliers
WHERE city = 'New York‘ and type = 'PCs’ ;
SQL: "OR" Condition
The syntax for the OR condition is:
SELECT columns
FROM tables
WHERE column1 = 'value1‘ or column2 = 'value2';
SELECT *
FROM suppliers
WHERE city = 'New York‘ or Type = ‘Software';
SQL: LIKE Condition
The LIKE condition allows you to use wildcards in the where clause of an
SQL statement.This allows you to perform pattern matching.
% allows you to match any string of any length (including zero length)
SELECT columns
FROM tables
WHERE column1 in (value1, value2, .... value_n);
SQL: "IN" Function
SELECT *
FROM suppliers
WHERE supplier_name in ( 'IBM', ‘HP', 'Microsoft');
SELECT *
FROM suppliers
WHERE supplier_name = 'IBM'
OR supplier_name = ‘HP'
OR supplier_name = 'Microsoft';
SQL: Not "IN" Function
SELECT *
FROM suppliers
WHERE supplier_name Not In ( 'IBM', ‘H P',
'Microsoft');
SQL: BETWEEN Condition
The BETWEEN condition allows you to retrieve values within a range.
SELECT columns
FROM tables
WHERE column1 between value1 and value2;
SELECT *
FROM suppliers
WHERE supplier_id between 5000 AND 5010;
SELECT *
FROM suppliers
WHERE supplier_id >= 5000
AND supplier_id <= 5010;
SQL: Not BETWEEN Condition
SELECT *
FROM suppliers
WHERE supplier_id not between 5000 and 5500;
Retrieve Data from More Than
one Table : Join Tables
- A join is used to combine rows from multiple tables.
The Basic Syntax for join tables is
Select Columns
From Table1 Join Table2
On Table1.JoinField = Table2.JoinField
Supplier
supplier_id supplier_name
100 IBM
200 HP
300 Microsoft
400 Apple
Product
product_Id Product_name sup_id Price
1 IPAD 2 400 2400
2 IPHONE 4s 400 2500
3 MS Office 2012 300 1600
4 Color Printer 100 1500
Retrieve Data from More Than one Table
: Join Tables
For Example:
Product
product_Id Product_name supplier_id
1 IPAD 2 400
2 IPHONE 4s 400
3 MS Office 2012 300
4 Color Printer 100
Join Tables
Select Customer_name , Product_name , Ord_date
From customer ,Order , product
Where customer_id = cust_id and product.product_id = order.product_id
Max( column x ) - Returns the Maximum value in the values stored in Column x
Min( column x ) - Returns the Minimum value in the values stored in Column x
Retrieving Data : Aggregate Functions
The Basic Syntax for using the Aggregate functions is
For each depart find the depart no and how many employees who get
salary over 1500
SELECT columns
FROM tables
WHERE predicates
ORDER BY column ASC/DESC;
For Example :
1 1
1 M
1
M
1
Q1 : Create all tables of this schema and apply any necessary
constraints.
Q2-2 : Alter the employee table to apply the following business rule
Q2-5: display a list of Employee SSN , Name and Salary for employees
working in depart no 2.
SQL Views
PL SQL Condition Statements
I. IF – Then – Else
II. Case Statement
Executes
Second
Main -Outer
Query
Inner - Sub Executes
Query First
Subqueries
A subquery Can be Categorized as :
1- Single Row Subquery : queries that return only a single
value.
Used with = , <> , >= , <= Operators.
Example: Display the ssn and last name for the employee who Work in the
same department that employee named ‘Waleed Ahmed’ works in.
Query 2 : who are the employees that belong to the department retrieved by
Query 1.
Query 2 : who are the employees that belong to the department retrieved by Q1.
Example: Display the ssn and last name for the employee who
got the maximum salary value.
-----
-----
-----
-----
Subqueries
Using the SubQuery in the WHERE clause
-----
-----
-----
-----
Subqueries
Using the SubQuery in the From clause
SQL Views
PL SQL Condition Statements
I. IF – Then – Else
II. Case Statement
You can Query, Insert, Update and delete from views, just
as any other table.
SQL:VIEWS
The syntax for creating a VIEW is:
Query :
Update Vw_Managers
Set ename = ‘Mohamed’
Where ename = ‘desouki’;
Update Vw_Managers
Set job= ‘Clerck’ ;
محمد إبراهيم الدسوقى
محاضر بكلية هندسة و علوم الحاسب – قسم نظم املعلومات
جامعة سل ــمان بن عبد العزيز -السعودية – محافظة الخرج
Email : mohamed_eldesouki@hotmail.com
Advanced Topics In SQL / PL SQL
SQL Sub Queries
SQL Views
Introduction to PL / SQL
PL SQL Condition Statements
I. IF – Then – Else
II. Case Statement
dbms_output.put_line ( message);
PL/SQL Syntax – Variables Declaration
Variables are declared in the declarative section of the block.
v_student_id CHAR(8);
v_lastname VARCHAR2(25);
v_capacity NUMBER(3) := 200;
IF condition THEN
{...statements to be executed...}
END IF;
Actions To be
Taken
End
IF
IF-THEN
Example:
declare
stdmarks number (2);
passmark number(2);
begin
passmark :=60;
stdmarks :=20;
if stdmarks > passmark then
dbms_output.put_line(Congatulations, go to the next level');
end if; ‘
end;
IF-THEN-ELSE Statement
Syntax #1: IF-THEN - ELSE
IF condition THEN
{...statements to be executed...}
ELSE
{...statements to be executed...}
END IF;
Actions To be Actions To be
Taken Taken
End
IF
IF-THEN-ELSE Statement
Example:
declare
stdmarks number (2);
passmark number(2);
begin
passmark :=60;
stdmarks :=20;
if stdmarks > passmark then
dbms_output.put_line(Congatulations, go to the next level');
Else
dbms_output.put_line(Sorry, you have to get extra ‘ ||
passmark – stdmarks || ‘ marks to pass’);
end if; ‘
end;
IF-THEN-ELSIF Statement
Syntax #1: IF-THEN - ELSIF
IF condition 1 THEN
{...statements to be executed...}
ELSIF condition 2 THEN
{...statements to be executed...}
ELSIF condition 3 THEN
{...statements to be executed...}
ELSE
{...statements to be executed...}
END IF;
Example: Print out the student grade according to the following rules
Otherwise F
And – Or Conditions
Print out the student grade according to the following
rules
Otherwise F
محمد إبراهيم الدسوقى
محاضر بكلية هندسة و علوم الحاسب – قسم نظم املعلومات
جامعة سل ــمان بن عبد العزيز -السعودية – محافظة الخرج
Email : mohamed_eldesouki@hotmail.com
Selected Topics In SQL / PL SQL
SQL Sub Queries
SQL Views
Introduction to PL / SQL
PL SQL Condition Statements
I. IF – Then – Else
II. Case Statement
Marks 95 >>> A
Marks 90 >>> B
Marks 85 >>> C
Otherwise F
declare
v_mark number;
begin
v_mark :=90;
case v_mark
when 95 then dbms_output.put_line('You Got A');
when 90 then dbms_output.put_line('You Got B');
when 85 then dbms_output.put_line('You Got C');
else
dbms_output.put_line ('Sorry ,You Got F');
end case;
end;
Case Statement : Searched Case
Print out the student grade according to the following rules
Otherwise F
declare
v_mark number;
begin
v_mark :=85;
case
when v_mark between 91 and 100 then dbms_output.put_line('You Got A');
when v_mark between 81 and 90 then dbms_output.put_line('You Got B');
when v_mark between 61 and 70 then dbms_output.put_line('You Got D');
else
dbms_output.put_line ('Sorry ,You Got F');
end case;
end;
Case Statement : Searched Case
declare
v_mark number :=85;
v_Level number:= 3;
v_Major char (15) := 'SW Engineering';
begin
case
when v_mark between 91 and 100 then dbms_output.put_line('You Got A');
when v_level = 4 then dbms_output.put_line('You Are in Second Year');
when v_Major ='Inform Systems' then dbms_output.put_line('You are an Analyst');
else
dbms_output.put_line ('Non of the conditions is true');
end case;
end;
Case Statement : Within Select Statement
Display a list of empno , ename and where he is working
according to the following facts
select supplier_id,
CASE
WHEN supplier_name = 'IBM' and supplier_type = 'Hardware' THEN 'North office'
WHEN supplier_name = 'IBM' and supplier_type = 'Software' THEN 'South office'
END
from suppliers;
محمد إبراهيم الدسوقى
محاضر بكلية هندسة و علوم الحاسب – قسم نظم املعلومات
جامعة سل ــمان بن عبد العزيز -السعودية – محافظة الخرج
Email : mohamed_eldesouki@hotmail.com
Selected Topics In SQL / PL SQL
SQL Sub Queries
SQL Views
Introduction to PL / SQL
PL SQL Condition Statements
I. IF – Then – Else
II. Case Statement
The LOOP statement is terminated when it encounters either an EXIT statement or when it
encounters an EXIT WHEN statement that evaluated to TRUE.
LOOP
{.statements.}
Exit When (Condition)
END LOOP;
Loops: 1- Loop Statement
-> Print out the word ‘Hello’ Five times.
declare
Counter number :=0;
begin
loop
dbms_output.put_line ('Hello');
counter:=counter +1;
end loop;
end;
/
Loops: 1- Loop Statement
-> Print out the word ‘Hello’ Five times.
declare
Counter number := 0 ;
begin
loop
dbms_output.put_line ('Hello');
counter:=counter +1;
If counter =5 then
Exit ;
End If;
end loop;
end;
/
Loops: 1- Loop Statement
-> Print out the numbers from 1 to 10.
declare
counter number :=1;
begin
loop
dbms_output.put_line (counter);
counter:=counter +1;
exit when (counter > 10);
end loop;
end;
/
محمد إبراهيم الدسوقى
محاضر بكلية هندسة و علوم الحاسب – قسم نظم املعلومات
جامعة سل ــمان بن عبد العزيز -السعودية – محافظة الخرج
Email : mohamed_eldesouki@hotmail.com
Selected Topics In SQL / PL SQL
SQL Sub Queries
SQL Views
Introduction to PL / SQL
PL SQL Condition Statements
I. IF – Then – Else
II. Case Statement
Since the WHILE condition is evaluated before entering the loop, it is possible that the loop
body may not execute even once.
declare
Counter number :=1;
begin
While (counter <=5 )
loop
dbms_output.put_line ('Hello');
counter:=counter +1;
end loop;
end;
/
Loops: 2- While Loop Statement
-> Print out the numbers from 1 to 10.
Example
declare
counter number :=1 ;
begin
END LOOP;
end;
محمد إبراهيم الدسوقى
محاضر بكلية هندسة و علوم الحاسب – قسم نظم املعلومات
جامعة سل ــمان بن عبد العزيز -السعودية – محافظة الخرج
Email : mohamed_eldesouki@hotmail.com
Selected Topics In SQL / PL SQL
SQL Sub Queries
SQL Views
Introduction to PL / SQL
PL SQL Condition Statements
I. IF – Then – Else
II. Case Statement
begin
For counter in 1..5
loop
dbms_output.put_line ('Hello');
end loop;
end;
/
Loops: 3- For Loop Statement
Example
-> Print out the numbers from 1 to 10.
begin
FOR counter IN 1..10
LOOP
END LOOP;
end;
/
Loops: 2- For Loop Statement with Reverse
FOR loop_counter IN Reverse lowest_number..highest_number
LOOP
{.statements.}
END LOOP;
Example
begin
FOR counter IN Reverse 1..10
LOOP
dbms_output.Put_Line ('counter value reaches ' || counter);
END LOOP;
end;
محمد إبراهيم الدسوقى
محاضر بكلية هندسة و علوم الحاسب – قسم نظم املعلومات
جامعة سل ــمان بن عبد العزيز -السعودية – محافظة الخرج
Email : mohamed_eldesouki@hotmail.com
Selected Topics In SQL / PL SQL
SQL Sub Queries
SQL Views
Introduction to PL / SQL
PL SQL Condition Statements
I. IF – Then – Else
II. Case Statement
A cursor is basically an Area allocated by Oracle for executing the SQL Statements.
I) Implicit Cursors
-It is associated with any DML statement (Insert , Update , Delete) and with
any single row query (query that that returns a single row).
if (sql%found) then
dbms_output.put_line
('the query affected ' || to_char(sql%rowcount));
end if;
end;
SQL/PL SQL : Explicit Cursors
-An Explicit cursor is a cursor which is declared by the programmer to handle SQL
queries (Select Statements) that return more than one row .
1- Declare a Cursor
2- Open Statement
3- FETCH Statement
4- CLOSE Statement
Explicit Cursors : Declare Statement
1- Declare Statement :
Assigns the user defined cursor to a select statement that returns more than one
row
The basic syntax for Declaring a cursor is:
CURSOR cursor_name
IS
SELECT_statement;
For example,
Declare
CURSOR Curs_Emp_Data
IS
SELECT Empno , Ename , Sal , Deptno
from Emp where Deptno = 20 ;
Explicit Cursor: Open Statement
Once you've declared your cursor, the next step is to open the cursor.
2- Open Statement :
Executes the select statement to create an active set of rows
OPEN cursor_name;
For example
Declare
CURSOR Curs_Emp_Data
IS
SELECT Empno , Ename , Sal , Deptno
from Emp where Deptno = 20 ;
Begin
OPEN Curs_Emp_Data;
Explicit Cursors: Fetch Statement
3- Fetch Statement :
Used to retrieve a record from the Select Statement Result Set. And populate
column values to memory variables. It retrieves one record each time.
The basic syntax for a FETCH statement is:
For example
Declare
VarEno number; varEnameVarchar2(20) ;
CURSOR Curs_Emp_Data
IS
SELECT Empno , Ename
from Emp where Deptno = 20 ;
Begin
OPEN Curs_Emp_Data;
FETCH Curs_Emp_Data into VarEno , varEname ;
Explicit Cursors: Close Statement
4- Close Statement :
Used to release the cursor.
Close cursor_name ;
For example
Declare
VarEno number; varEnameVarchar2(20) ;
CURSOR Curs_Emp_Data
IS
SELECT Empno , Ename
from Emp where Deptno = 20 ;
Begin
OPEN Curs_Emp_Data;
FETCH Curs_Emp_Data into VarEno , varEname ;
Close Curs_Emp_Data;
%Type and %RowType Attributes
The %TYPE attribute lets you use the datatype of a field instead of hard coding the
type names when declaring the variables.
Example
Declare Emp
VarEno number (3) ; Field Data Type
varEnameVarchar2(10) ;
Empno Number (5)
VarSalary number (5);
Ename Varchar2 (20)
CURSOR Curs_Emp_Data Sal Number (7,2)
IS
SELECT Empno , Ename , Sal
from Emp where Deptno = 20 ;
Begin
OPEN Curs_Emp_Data;
FETCH Curs_Emp_Data into VarEno , VarEname, VarSalary ;
Close Curs_Emp_Data;
%Type and %RowType Attributes
The syntax of %TYPE attribute
Varname TableName.ColumnName%Type.
Example
Declare Emp
VarEno Emp.Empno%Type ; Field Data Type
varEname Emp.Ename%Type ;
Empno Number (5)
VarSalary Emp.Sal%Type;
Ename Varchar2 (20)
CURSOR Curs_Emp_Data Sal Number (7,2)
IS
SELECT Empno , Ename , Sal
from Emp where Deptno = 20 ;
Begin
OPEN Curs_Emp_Data;
FETCH Curs_Emp_Data into VarEno , VarEname, VarSalary ;
Close Curs_Emp_Data;
%Type and %RowType Attributes
The ٌ% RowTYPE attribute provides a record type that represents a row in a database
table.The record can store an entire row of data selected from the table or fetched
from a cursor. Emp
Example Field Data Type
Begin
OPEN Curs_Emp_Data;
FETCH Curs_Emp_Data into VarEmpData ;
dbms_output.put_line (VarEmpData . Ename);
Close Curs_Emp_Data;
Explicit Cursors Attributes
Name Description
%ISOPEN Returns True if the Cursor is open , False Otherwise.
%FOUND Returns TRUE if the Fetch statement finds a row in the cursor.
%NOTFOUND Returns TRUE if the Fetch statement doesn’t find rows in the
cursor.
%ROWCOUNT Identify the row number of the currently fetched row.
Explicit Cursors: Working with Cursor Row Set
using Loops.
Declare
CURSOR Curs_Emp_Data
IS
SELECT Empno , Ename , Sal from Emp
where Deptno in ( 20 ,30) ;
VarEmpData Curs_Emp_Data%RowType;
Begin
OPEN Curs_Emp_Data;
Loop
FETCH Curs_Emp_Data into VarEmpData ;
Close Curs_Emp_Data;
Explicit Cursors: Working with Cursor Row Set
using Loops.
Declare
CURSOR Curs_Emp_Data
IS
SELECT Empno , Ename , Sal , Comm from Emp
where Deptno = 20 ;
VarEmpData Curs_Emp_Data%RowType;
Begin
OPEN Curs_Emp_Data;
Loop
FETCH Curs_Emp_Data into VarEmpData ;
Exit when (Curs_Emp_Data%notfound)
Update Emp
Set Comm = VarEmpData .Sal * 0.025 ;
End Loop;
Close Curs_Emp_Data;
Stored Program Units
Advantages of Using Stored Program Units:
1. It helps to break a program into manageable, well-defined modules.
2. The code is stored in a pre-compiled form which means that its syntax is valid and
does not need to be compiled at run-time, thereby saving resources.
3. promote re-usability and easy maintenance.
4. As the Stored Program Units are stored in the database there is no need to
transfer the code from the clients to the database server and this results in much
less network traffic and improves scalability;
5. Helps to apply security mechanisms on the Database and control Access.
1. Procedures
2. Functions
3. Packages
Stored Program Units
Problem
Write PL/SQL code to update the commission value for all the employees working
in a specific department according to the following formulas
2-if the Employee job is ‘SALESMAN’ , let the commission to be 5 % of the salary
value.
IN - The parameter is used to pass a value from the calling program to the
procedure. The value of the parameter can not be overwritten by the procedure.
OUT - The parameter is used to pass a value from the procedure to the calling
program.
IN OUT - The parameter can be used to pass a value to or from the procedure.
Stored Procedure With Parameters
create or replace procedure update_depart_comm ( depart_no in number )
is
cursor Curs_get_Emp is select empno , sal , job from emp where deptno= depart_no;
var_emp_data Curs_get_Emp%rowtype;
comission number;
begin
open Curs_get_Emp;
loop
fetch Curs_get_Emp into var_emp_data;
exit when (Curs_get_Emp%notfound);
if var_emp_data .job = 'Manager' then
comission := var_emp_data.sal * 0.10;
elsif var_emp_data .job = 'SALESMAN' then
comission := var_emp_data .sal * 0.05;
else
comission := var_emp_data .sal *0.02;
end if;
update emp
set comm = comission
where empno = var_emp_data .empno;
end loop;
close Curs_get_Emp;
end;
Stored Procedure With Parameters
SELECT text
FROM USER_SOURCE
WHERE name = ' update_depart_comm'
ORDER BY line;
Stored Program Units
Advantages of Using Stored Program Units:
1. It helps to break a program into manageable, well-defined modules.
2. The code is stored in a pre-compiled form which means that its syntax is valid and
does not need to be compiled at run-time, thereby saving resources.
3. promote re-usability and easy maintenance.
4. As the Stored Program Units are stored in the database there is no need to
transfer the code from the clients to the database server and this results in much
less network traffic and improves scalability;
5. Helps to apply security mechanisms on the Database and control Access.
1. Procedures
2. Functions
3. Packages
Functions
1. A stored function (also called a user function or user defined function) is a set
of PL/SQL statements you can call by name.
2. Stored functions are very similar to procedures, except that a function returns a
value to the environment in which it is called
IS | AS
[declaration_section]
BEGIN
executable_section
[EXCEPTION
exception_section]
END [function_name];
Functions With Parameters
Problem
Create Function that accepts the hire date the returns The Employee
Experience in Years.
begin
end;
/
Functions With Parameters
Problem
Create Function that returns the Annual salary for any given Employee Number
create or replace function Annual_Sal ( eno in number) return number
as
VarTotal number;
begin
return VarTotal ;
end;
/
Functions With Parameters
Problem
Create Function that accepts the hire date and returns The Employee Experience in
Years and in weeks.
create or replace function Service_Years ( hdate in date, weaks out number)
return number
As
years number;
Begin
years:= trunc ( months_between (sysdate, hdate)/12 ,0);
weaks := trunc ( months_between (sysdate, hdate)*4 ,0);
return years ;
end;
/
declare
noofweaks number; returnvalue number;
begin
returnvalue:= service_years (to_date('03/08/1981','dd/mm/yyyy')
,noofweaks) ;
dbms_output.put_line (returnvalue);
dbms_output.put_line (noofweaks );
end;
/
Restrictions with Stored Functions
1. when a function is called from within a query or DML statement,
the function cannot Have OUT or IN OUT parameters.
•A package is a schema object that groups logically related PL/SQL types, items
and subprograms.
2-body (Unnecessary): defines the queries for the cursors and the code
for the subprograms.
Packages
Reasons to use packages
You don’t need to fully define the package bodies until you are ready to
complete the application.
Packages
Reasons to use packages
End; [package_name]
End; [package_name]
Packages
Package Specifications
create or replace package hr
is
TYPE EmpRecTyp IS RECORD (emp_id NUMBER, sal NUMBER);
Function GetEmpCount (dno in number) return number;
Function GetEmpName (empno in number) return varchar2;
procedure UpdateComm (eno in number ,percent in number);
procedure UpdateComm (dno in number);
end;
/
create or replace package body hr
as
function GetEmpCount (dno in number) return number
as
empcount number;
Package Body
begin
select count(*) into empcount from emp where deptno=dno;
return empcount;
end;
package_name.type_name
package_name.item_name
package_name.subprogram_name
Declare
emprec hr.EmpRecTyp;
Empcount number;
Begin
select empno , sal into emprec
from emp where empno=7499;
dbms_output.put_line(emprec.emp_id);
dbms_output.put_line(emprec.sal);
Empcount := hr.GetEmpCount(10);
dbms_output.put_line(Empcount );
end;
/
محمد إبراهيم الدسوقى
محاضر بكلية هندسة و علوم الحاسب – قسم نظم املعلومات
جامعة سل ــمان بن عبد العزيز -السعودية – محافظة الخرج
Email : mohamed_eldesouki@hotmail.com
Selected Topics In SQL / PL SQL
SQL Sub Queries
SQL Views
Introduction to PL / SQL
PL SQL Condition Statements
I. IF – Then – Else
II. Case Statement
Triggers are similar to stored procedures. However, procedures and triggers differ in
the way that they are invoked.
Triggers are implicitly fired (executed) by Oracle when a triggering INSERT, UPDATE
, or DELETE statement is issued.
Deleteinto
Insert fromorders
orders
Inventory Values (135,’12/1’,1,5);
Where ordno=135;
Item # Qty
Act1 1 25
20
2 30
Act2
3 15
Act n
Database Triggers
Triggers and declarative integrity constraints can both be used to constrain data input.
A trigger does not apply to data loaded before the definition of the trigger.
Therefore, it does not guarantee all data in a table conforms to its rules.
A constraint applies to existing data in the table and any statement that
manipulates the table.
Parts of a Trigger
A trigger has three basic parts:
1- A Triggering Event Or Statement : The SQL statement that causes a
trigger to be fired. A triggering event can be an INSERT, UPDATE, or DELETE
statement on a table.
The trigger action is not executed if the trigger restriction evaluates to FALSE or
UNKNOWN
3- 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.
Types of Triggers
Row triggers are useful if the code in the trigger action depends on data provided by
the triggering statement or rows that are affected
Types of Triggers
2- Statement Triggers
A statement trigger is fired once on behalf of the triggering statement, regardless of
the number of the number of rows affected.(even if no rows are affected).
For example, if a trigger makes a complex security check on the current time or
user, or if a trigger generates a single audit record based on the type of triggering
statement, a statement trigger is used.
Trigger Timing
When defining a trigger, you can specify the trigger timing. That is,
you can specify whether the trigger action is to be executed before or after
the triggering statement.
BEFORE Triggers : Execute the trigger action before the triggering statement.
AFTER Triggers: Execute the trigger action after the triggering statement is
executed
Tips in Designing Triggers
1- Use triggers to guarantee that when a specific operation is performed, related actions are
performed.
2- Use database triggers only for centralized, global operations that should be fired for the
triggering statement, regardless of which user or database application issues the statement.
3- Do not define triggers that duplicate the functionality already built into Oracle. For example,
do not define triggers to enforce data integrity rules that can be easily enforced using declarative
integrity constraints.
4- Limit the size of triggers (60 lines or fewer is a good guideline). If the logic for your trigger
requires much more than 60 lines of PL/SQL code, it is better to include most of the code in a
stored procedure, and call the procedure from the trigger.
Creating Triggers
CREATE [OR REPLACE] TRIGGER trigger_name Insert ,
{BEFORE | AFTER } trigger_event Update ,
Delete
ON table_name
[FOR EACH ROW [WHEN trigger_condition]]
BEGIN
trigger_body
Row Level
END trigger_name; Trigger
•Notice :
The new column values are referenced using the :NEW qualifier before the
column name,
while the old column values are referenced using the :OLD qualifier before the
column name.
For Example :
create or replace Trigger emp_name_changes
BEFORE INSERT OR UPDATE ON emp
for each row
begin
:new.ename :=Upper(:new.ename);
end;
Accessing Column Values in Row Triggers
Orders
Ord # Date Item Qty
135 12/1 1 5
:NEW.Qty = 12
Update orders (2)
135 12/1 1 12
5 Set qty = 12 where
order _id =135;
:OLD.Qty = 5
We want to create trigger that automatically set the total cost , create_date
columns.
CREATE OR REPLACE TRIGGER orders_before_insert BEFORE INSERT ON orders FOR EACH ROW
BEGIN
END;
Trigger Examples (Row Level Trigger )
Suppose we have the following table :
We want to create trigger that automatically subtract the ordered quantity from
the available Quantity.
BEGIN
Update inventory
Set available_qty = available_qty - :new.quantity
where item_no = :new.item_no;
END;
Trigger Examples (Row Level Trigger )
BEGIN
Update inventory
Set available_qty = available_qty - :new.quantity where item_no = :new.item_no;
END;
Trigger Examples (Row Level Trigger )
Write a trigger that prevent the cancelation of orders that is older than
2 days .
And in case of cancelation increase the available quantity in the inventory
table with the canceled quantity
Syntax:
Here:
declare
v_user varchar2(20);
BEGIN
select user into v_user from dual;
IF INSERTING THEN
INSERT INTO AUDITOR VALUES(v_user,'INSERT');
END IF;
end ;
Enabling and Disabling - Dropping Triggers