About Triggers in PLSQL
Syntax:
CREATE OR REPLACE TRIGGER audit_salary_change -- "Create a guard named audit_salary_change"
BEFORE UPDATE -- "Catch them BEFORE they update anything"
ON employees -- "Watch the 'employees' table"
FOR EACH ROW -- "Check EVERY single employee being updated!"
DECLARE
-- (This is where you can declare variables if you need them)
BEGIN
-- (This is the action)
-- Let's say we want to log the event or check if the change is valid:
INSERT INTO audit_log (msg) VALUES ('A salary is being changed!');
END;
/
Q: What is a Trigger?
ANS:
"A database trigger is a stored PL/SQL block that automatically executes—or 'fires'—in response to a specific event in the database, such as an INSERT, UPDATE, or DELETE operation.
Unlike stored procedures, which have to be called manually, a trigger runs implicitly behind the scenes whenever its associated event occurs. We primarily use them to enforce complex business rules, maintain audit logs, validate data before it gets saved, and automatically generate values like primary keys."
Q: Why do we need Triggers?
We use triggers to automate critical database tasks so we don't have to rely on users or applications to remember them. Specifically, they serve three main purposes:
Enforcing business rules by validating data before it's saved.
Auditing changes by automatically logging who modified data and when.
Auto-generating values, like primary keys, whenever new records are inserted."
Q: What is the difference between a BEFORE and an AFTER trigger?
A
BEFOREtrigger fires before the DML event completes, which makes it ideal for validating data or modifying values—like formatting text or generating primary keys—before they are written to the table.
An
AFTERtrigger fires once the DML operation has succeeded, so it is best used for auditing, logging history, or updating secondary tables where you need the final data to be confirmed first.
Q: What is the difference between a Statement-Level and a Row-Level trigger?
By default, a trigger is "statement-level", meaning it fires only once per SQL statement, regardless of whether that statement affects 1 row or 1,000 rows.
If we include the "FOR-EACH" ROW clause, it becomes a row-level trigger, meaning it fires once for every individual row affected by the operation—which is necessary whenever we need to inspect or compare specific column values.
Q: What are :OLD and :NEW pseudorecords?
They are special references available only in row-level triggers that let us access row data before and after a change.
:OLD holds the original column values before an UPDATE or DELETE, while :NEW holds the incoming values for an INSERT or UPDATE.
For ex:- In a salary audit trigger, I can compare :OLD.salary and :NEW.salary to log the exact raise.
Q: Can we use COMMIT or ROLLBACK inside a trigger?
No, standard triggers cannot contain transaction control statements like COMMIT or ROLLBACK because they execute as part of the triggering transaction—committing inside a trigger would prematurely commit the user's unfinished transaction.
The only exception is if the trigger is explicitly declared with PRAGMA AUTONOMOUS_TRANSACTION, which is sometimes used for independent error logging.
Q: What is a "Mutating Table" error, and how do you avoid it?
An ORA-04091 mutating table error happens when a row-level trigger tries to query or modify the very same table that triggered it, because that table is currently mid-change and in an inconsistent state.
To avoid it, we can redesign the logic using a "compound trigger" or move the logic into a statement-level trigger
Real-Time
Q: How would you write a trigger to prevent an employee's salary from being decreased?
CREATE OR REPLACE TRIGGER prevent_salary_drop
BEFORE UPDATE OF salary ON employees
FOR EACH ROW
BEGIN
IF :NEW.salary < :OLD.salary THEN
RAISE_APPLICATION_ERROR(-20001, 'Salary cannot be decreased!');
END IF;
END;
/
I would create a BEFORE UPDATE row-level trigger specifically on the salary column of the employees table. Inside the block, I compare the :NEW.salary value with the :OLD.salary value. If the new salary is less than the old salary, I use RAISE_APPLICATION_ERROR to stop the update and return a custom error message to the user
DDL & Database-Level Triggers
So far, we've talked about DML triggers (watching data inside tables). DDL and Database-level triggers watch the structure of the database and user activity.
DDL Triggers (CREATE, ALTER, DROP)
Prevent accidental changes to your database schema or audit who modified table structures.
Ex:- Blocking anyone from dropping tables in a production schema
CREATE OR REPLACE TRIGGER prevent_table_drop
BEFORE DROP ON SCHEMA
BEGIN
RAISE_APPLICATION_ERROR(-20002, 'Dropping objects is not allowed in this schema!');
END;
/
Database Event Triggers (LOGON, LOGOFF, SERVERERROR)
Security monitoring and session setup.
Ex:
Recording every time a user logs into the database (AFTER LOGON ON DATABASE) into a security audit table.
Note:
While DML triggers track data changes (INSERT, UPDATE, DELETE) on a specific table,
DDL triggers fire on schema changes like CREATE, ALTER, or DROP, and Database triggers fire on system events like LOGON or SERVERERROR.
We use them mainly for schema security and user session auditing.
Q: How many Triggers can be created on table?
12
Q: What is the order of execution of Triggers?
Before stmt
Before row
After row
After stmt
Short Notes
Trigger:
A stored PL/SQL block that fires implicitly on DML (INSERT, UPDATE, DELETE), DDL (CREATE, ALTER, DROP), or database events (LOGON).
Why to use Trigger:
Enforce rules/validations, maintain audit trails, and auto-generate values (like primary keys).
Timing (BEFORE vs. AFTER):
BEFORE validates or modifies incoming data; AFTER logs history or updates other tables once the change succeeds.
Levels (Statement vs. Row):
Statement-level (default) runs once per SQL command; Row-level (FOR EACH ROW) runs once per affected row and unlocks :OLD and :NEW pseudorecords.
Key Rules:
No COMMIT/ROLLBACK inside standard triggers (unless using PRAGMA AUTONOMOUS_TRANSACTION), and watch out for mutating table errors (ORA-04091) when querying the triggering table in a row-level trigger.

Comments
Post a Comment