TRIGGER
A triggeris a stored PL/SQL program unit
that is automatically executed (fired) by
Oracle whenever a specified event occurs on
a table, view, schema, or database.
3.
TRIGGERS ARE MAINLYUSED
FOR:
Enforcing business rules
Auditing changes (history of
updates/deletes)
Automatic actions (like logging, cascading
updates)
Preventing invalid transactions
4.
TYPES OF TRIGGERS
1. Based on Timing (When they fire)
BEFORE Trigger Executes before the
→
triggering statement
(INSERT/UPDATE/DELETE).
AFTER Trigger Executes after the
→
triggering statement.
INSTEAD OF Trigger Used for
→ views
(cannot directly insert/update/delete on
views).
5.
TRIGGERS
2. Basedon Events
DML Triggers Fire on INSERT, UPDATE,
→
DELETE.
DDL Triggers Fire on CREATE, ALTER, DROP
→
(schema-level events).
Database Triggers Fire on events like
→
LOGON, LOGOFF, STARTUP, SHUTDOWN.
6.
TRIGGERS
3. Basedon Level
Row-level trigger Executes once for each
→
row affected. (FOR EACH ROW)
Statement-level trigger Executes once
→
per statement, regardless of row count.
7.
SYNTAX FOR TRIGGERS
CREATE[OR REPLACE] TRIGGER trigger_name
{BEFORE | AFTER | INSTEAD OF}
{INSERT [OR] | UPDATE [OR] | DELETE}
ON table_name
[FOR EACH ROW] -- optional (row-level trigger)
[WHEN (condition)] -- optional
DECLARE
-- variable declarations
BEGIN
-- trigger body
END;
/
8.
DML TRIGGERS
TheData Definition Language (DDL)
command events such as Create_table,
Create_view, drop_table, Drop_view, and
Alter_table cause the DDL triggers to be
activated.
They allow us to track changes in the
structure of the database. The trigger will
prevent any table creation, alteration, or
deletion in the database.
9.
EXAMPLE: PREVENT TABLE
DELETIONS
CREATETRIGGER prevent_table_creation
ON DATABASE
FOR CREATE_TABLE, ALTER_TABLE,
DROP_TABLE
AS
BEGIN
PRINT 'you can not create, drop and alter
table in this database';
ROLLBACK;
END;
DML TRIGGERS
DMLtriggers fire when we manipulate data
with commands like INSERT, UPDATE, or
DELETE.
These triggers are perfect for scenarios
where we need to validate data before it is
inserted, log changes to a table, or cascade
updates across related tables.
12.
EXAMPLE: PREVENT
UNAUTHORIZED UPDATES
Let’s say you want to prevent users from
updating the data in a sensitive students table.
We can set up a trigger to handle that.
CREATE TRIGGER prevent_update
ON students
FOR UPDATE, INSERT, DELETE
AS
BEGIN
RAISERROR ('You can not insert, update and
delete rows in this table.', 16, 1);
END;