A trigger is a PL/SQL program which is stored in the database. It is executed immediately before or after the execution of INSERT, UPDATE, and DELETE commands.
In PL/SQL, a trigger is a set of instructions that are automatically executed (“triggered”) in response to specific events on a particular table or view. These events include INSERT, UPDATE, DELETE, and other data manipulation operations. Triggers are stored in the database and can be useful for enforcing business rules, maintaining data integrity, and automating certain tasks.
There are two main types of triggers in PL/SQL:
- Row-level Trigger: This type of trigger is executed once for each row affected by the triggering event (e.g., each row affected by an INSERT, UPDATE, or DELETE statement). Row-level triggers are defined using the
FOR EACH ROW
clause. - Statement-level Trigger: This type of trigger is executed once, regardless of the number of rows affected by the triggering event. Statement-level triggers are defined without the
FOR EACH ROW
clause.
Triggers can be “BEFORE” or “AFTER” the triggering event. A “BEFORE” trigger is executed before the triggering event occurs, allowing you to perform actions such as validation or modification of data before it is written to the database. An “AFTER” trigger is executed after the triggering event, enabling you to perform actions such as logging or auditing after the data has been written to the database.
Here is a simple example of a trigger in PL/SQL:
CREATE OR REPLACE TRIGGER my_trigger
BEFORE INSERT ON my_table
FOR EACH ROW
BEGIN
-- Trigger logic goes here
-- You can reference :NEW to access the new values being inserted
-- For example, :NEW.column_name
DBMS_OUTPUT.PUT_LINE('Trigger activated for INSERT on my_table');
END;
This trigger will be executed before each row is inserted into the my_table
, and it will print a message using DBMS_OUTPUT.PUT_LINE
.