A trigger is the only database object that runs without being called. You do not invoke it from
your application, you do not schedule it, and you do not pass it parameters. The database fires
it automatically when a table changes — and that autonomy is exactly what makes triggers powerful
and dangerous at the same time. This guide covers the mechanics: BEFORE vs AFTER, row-level vs
statement-level, the :OLD and :NEW pseudo-records, the mutating table error that trips up every
PL/SQL developer eventually, compound triggers that fix it, INSTEAD OF triggers on views, and
MySQL Events for scheduled automation. The eighteen interview questions at the end are the ones
that actually come up, with answers that go past the textbook definition.
🎯 Key Takeaways
Triggers fire automatically — no CALL, no schedule
Row triggers see :OLD and :NEW; statement triggers do not
BEFORE can change the row; AFTER cannot
Mutating table is fixed with a compound trigger
MySQL Events are scheduled, not event-driven
18 Interview QuestionsBeginner to AdvancedOracle & MySQLUpdated Dec 2, 2026
KW
Kailas Warade
✓ Verified Author
Data Engineer · Oracle Certified · SQL & PL/SQL
Kailas works with SQL, PL/SQL, Python, and PySpark to build data pipelines.
He writes the SQL interview guides at Sankalan Data Tech, focused on
practical, real-world answers.
🏆 Oracle Certified💼 Data Engineer📝 SQL & PL/SQL Guides📍 Pune, India
A trigger is a named block of code stored in the database that fires automatically when a
specific event occurs on a table or view. The event is usually a DML statement —
INSERT, UPDATE, or DELETE — though some databases
support triggers on DDL and system events like logon and shutdown.
The key word is automatically. You do not call a trigger. You do not pass
it parameters. You do not schedule it. The database fires it as a side effect of the DML
statement, before or after the row is written. This is fundamentally different from a
stored procedure, which sits idle until someone invokes it.
Triggers are built from three parts: the event (what DML statement fires
it), the condition (optional logic inside the body that decides whether to
act), and the action (the code that runs). A simple audit
trigger fires on UPDATE, checks whether the salary column actually changed,
and inserts a row into an audit table. That is the entire pattern.
The reason triggers matter in interviews is not that they are hard to write. It is that
they are easy to misuse. A trigger that reads its own table will fail. A trigger that calls
another trigger can cascade in ways nobody expected. A trigger that hides business logic
makes debugging a nightmare because the code does not appear in the application. Knowing
when to use one — and when not to — is what separates a good answer from a memorized one.
The Sample Data We Use in Every Example
The examples below use an employees table and a companion
salary_audit table. Every trigger in this guide either audits changes to the
first or writes to the second.
Two things about this data make the trigger examples useful:
Multiple employees in the same department — useful for showing how a statement-level trigger fires once while a row-level trigger fires per row.
Distinct salary values — makes before-and-after auditing obvious in the output.
Row-Level vs Statement-Level Triggers
This is the first distinction every interviewer probes, and the one candidates get wrong
most often. It is not cosmetic — it changes how many times your code runs and whether you
can see the affected rows.
Aspect
Row-level trigger
Statement-level trigger
Fires
Once per affected row
Once per statement
Keyword
FOR EACH ROW
No keyword (default)
:OLD / :NEW
Available
Not available
Typical use
Auditing, validation, derived columns
Statement logging, security checks
Performance
Slower — overhead per row
Faster — overhead per statement
A row-level trigger
CREATE OR REPLACE TRIGGER trg_salary_audit
AFTER UPDATE OF salary ON employees
FOR EACH ROW
BEGIN
INSERT INTO salary_audit (employee_id, old_salary, new_salary, changed_by, change_date)
VALUES (:OLD.employee_id, :OLD.salary, :NEW.salary, USER, SYSDATE);
END;
/
If this trigger fires on UPDATE employees SET salary = salary * 1.1 WHERE department_id = 10,
it runs twice — once for Alice and once for Charlie — because two rows
changed. Two audit rows are written.
A statement-level trigger
CREATE OR REPLACE TRIGGER trg_dept_update_log
AFTER UPDATE ON employees
BEGIN
INSERT INTO statement_log (event_name, fired_by, fired_at)
VALUES ('UPDATE on employees', USER, SYSDATE);
END;
/
The same UPDATE statement fires this trigger once. One log row. No
:OLD or :NEW — the trigger has no visibility into which rows
changed, only that a statement ran.
The rule: if you need to see the data that changed, use row-level. If you only need to
know that a statement happened, use statement-level and take the performance win.
BEFORE vs AFTER, and :OLD / :NEW
The second distinction is timing. BEFORE fires before the row hits the table. AFTER fires
after. The one thing that actually matters in practice: only BEFORE triggers can
change the row being written.
Modifying :NEW in a BEFORE trigger
CREATE OR REPLACE TRIGGER trg_salary_cap
BEFORE INSERT OR UPDATE OF salary ON employees
FOR EACH ROW
BEGIN
-- Enforce an upper bound at the database layer
IF :NEW.salary > 200000 THEN
:NEW.salary := 200000;
END IF;
END;
/
This trigger silently caps salaries above 200,000 before the row is written. An AFTER
trigger cannot do this — the row is already in the table, and changing
:NEW would have no effect.
The :OLD and :NEW pseudo-records
They are the trigger's window into the row. What is available depends on the DML statement:
DML statement
:OLD
:NEW
INSERT
Undefined
The new row values
UPDATE
Values before the change
Values after the change
DELETE
The deleted row values
Undefined
The classic audit pattern compares them to record only genuine changes:
CREATE OR REPLACE TRIGGER trg_salary_change_only
AFTER UPDATE OF salary ON employees
FOR EACH ROW
WHEN (OLD.salary != NEW.salary)
BEGIN
INSERT INTO salary_audit (employee_id, old_salary, new_salary, changed_by, change_date)
VALUES (:OLD.employee_id, :OLD.salary, :NEW.salary, USER, SYSDATE);
END;
/
The WHEN clause filters out updates that did not actually change the salary.
Without it, an update to any other column that happens to include salary in the SET list
would still write an audit row — noise that makes the audit table useless.
The Mutating Table Error
Every PL/SQL developer hits ORA-04091 eventually. A row-level trigger tries to read or
modify the same table that fired it, and the database refuses.
-- This trigger will fail with ORA-04091
CREATE OR REPLACE TRIGGER trg_bad_validation
BEFORE INSERT ON employees
FOR EACH ROW
DECLARE
v_count NUMBER;
BEGIN
-- Reading the same table the trigger is on
SELECT COUNT(*) INTO v_count FROM employees WHERE department_id = :NEW.department_id;
IF v_count >= 10 THEN
RAISE_APPLICATION_ERROR(-20001, 'Department is full');
END IF;
END;
/
The table is mid-change. Some rows have been inserted, some have not. If the trigger read
the table, it would see an inconsistent snapshot — a state that never existed before or
after the statement. Oracle blocks the read rather than return misleading data.
The error message is worth memorizing because it is unmistakable:
ORA-04091: table SCOTT.EMPLOYEES is mutating, trigger/function may not see it
The classic workaround — a package variable to defer the check to an AFTER STATEMENT
trigger — works but requires two triggers and shared state. That is the pattern that
compound triggers were designed to replace.
Compound Triggers — The Fix
A compound trigger groups all four timing points into a single trigger body. You can
collect per-row data in the row phase and process the whole set once the statement is
complete — which is exactly what the mutating table error needs.
CREATE OR REPLACE TRIGGER trg_compound_validation
FOR INSERT ON employees
COMPOUND TRIGGER
-- Shared state: collects department ids as rows are inserted
TYPE dept_tab IS TABLE OF employees.department_id%TYPE;
g_depts dept_tab := dept_tab();
BEFORE EACH ROW IS
BEGIN
g_depts.EXTEND;
g_depts(g_depts.LAST) := :NEW.department_id;
END BEFORE EACH ROW;
AFTER STATEMENT IS
v_count NUMBER;
BEGIN
FOR i IN 1 .. g_depts.COUNT LOOP
SELECT COUNT(*) INTO v_count
FROM employees
WHERE department_id = g_depts(i);
IF v_count >= 10 THEN
RAISE_APPLICATION_ERROR(-20001, 'Department ' || g_depts(i) || ' is full');
END IF;
END LOOP;
END AFTER STATEMENT;
END;
/
The BEFORE EACH ROW section does not touch the table — it just records the
department ids in a collection. The AFTER STATEMENT section runs once, after
all rows are in place, and queries the table safely.
Compound triggers also solve a subtler problem: they eliminate the need for package-level
variables to share state between two separate triggers. The state lives inside the trigger
body, scoped to a single statement, and is cleaned up automatically.
INSTEAD OF Triggers on Views
A view built from a join cannot normally accept INSERT, UPDATE, or DELETE. The database
does not know which base table each column belongs to. An INSTEAD OF trigger intercepts the
DML and does the work on the base tables manually.
CREATE OR REPLACE VIEW v_employee_dept AS
SELECT e.employee_id, e.employee_name, e.salary, d.department_name
FROM employees e
JOIN departments d ON e.department_id = d.department_id;
CREATE OR REPLACE TRIGGER trg_instead_of_insert
INSTEAD OF INSERT ON v_employee_dept
FOR EACH ROW
DECLARE
v_dept_id NUMBER;
BEGIN
-- Resolve the department name back to an id
SELECT department_id INTO v_dept_id
FROM departments
WHERE department_name = :NEW.department_name;
INSERT INTO employees (employee_id, employee_name, salary, department_id)
VALUES (:NEW.employee_id, :NEW.employee_name, :NEW.salary, v_dept_id);
END;
/
Now an INSERT against the view works. The trigger fires instead of the (impossible)
direct write, and the actual INSERT goes to the base table with the correct foreign key.
INSTEAD OF triggers are the standard mechanism for making complex join views updatable.
They are also the only trigger type that can be defined on a view rather than a table.
MySQL Events — Scheduled Automation
The second half of the title is a different mechanism entirely. A MySQL Event is not
triggered by DML — it is triggered by the clock. Think of it as a cron job that lives
inside the database.
Enabling the scheduler
Events only run if the event scheduler is on. It is off by default on many installations.
-- Check current state
SHOW VARIABLES LIKE 'event_scheduler';
-- Turn it on for the running server
SET GLOBAL event_scheduler = ON;
To make it persist across restarts, set it in the configuration file:
[mysqld]
event_scheduler = ON
Creating an event
CREATE EVENT ev_purge_old_audit
ON SCHEDULE EVERY 1 DAY
STARTS CURRENT_TIMESTAMP + INTERVAL 1 HOUR
DO
BEGIN
DELETE FROM salary_audit
WHERE change_date < DATE_SUB(NOW(), INTERVAL 90 DAY);
END;
The ON SCHEDULE EVERY 1 DAY clause sets the interval. The
STARTS clause delays the first run. The body can be a single statement or a
BEGIN…END block.
One-time vs recurring events
-- One-time event: runs once and is dropped
CREATE EVENT ev_one_shot
ON SCHEDULE AT CURRENT_TIMESTAMP + INTERVAL 1 HOUR
DO
INSERT INTO salary_audit (employee_id, old_salary, new_salary, changed_by, change_date)
VALUES (0, 0, 0, 'SYSTEM', NOW());
Recurring events keep firing on the interval until dropped or disabled. One-time events
run once and disappear (unless ON COMPLETION PRESERVE is set).
Managing events
-- List all events
SHOW EVENTS;
-- Disable without dropping
ALTER EVENT ev_purge_old_audit DISABLE;
-- Re-enable
ALTER EVENT ev_purge_old_audit ENABLE;
-- Drop permanently
DROP EVENT ev_purge_old_audit;
The key distinction from triggers: a trigger reacts to data changes, an event reacts to
time. Use a trigger when something must happen exactly when a row changes. Use an event
when something must happen on a schedule — cleanup, aggregation, report generation.
18 Interview Questions and Answers
These are the trigger and event questions that come up most often. Every answer stands on
its own — read them in any order, or work through them in sequence to build up the full
picture.
/
🔍
No matching questions found
Try a keyword like trigger, mutating, or event.
A trigger is a stored block of code that fires automatically when a specific event
occurs on a table or view. A stored procedure is a named block of code that runs
only when something calls it explicitly.
The difference is the invocation model. You call a procedure:
EXEC update_salary(101, 60000);
You do not call a trigger. It fires as a side effect of a DML statement:
UPDATE employees SET salary = 60000 WHERE employee_id = 101;
-- The trigger fires automatically, whether you want it to or not
That distinction drives everything else. Triggers cannot take parameters. They
cannot return values. They cannot be called directly from application code. They
fire every time the event happens, for every user, with no opt-out.
Procedures are the right place for business logic that the application invokes
deliberately. Triggers are the right place for cross-cutting concerns that must
never be skipped — auditing, integrity checks, derived columns that every writer
needs.
A row-level trigger fires once for every row the statement affects. A
statement-level trigger fires once for the entire statement, no matter how many
rows it touches.
-- Row-level: fires per row
CREATE OR REPLACE TRIGGER trg_row
AFTER UPDATE ON employees
FOR EACH ROW
BEGIN
DBMS_OUTPUT.PUT_LINE('Changed employee ' || :OLD.employee_id);
END;
/
-- Statement-level: fires once
CREATE OR REPLACE TRIGGER trg_stmt
AFTER UPDATE ON employees
BEGIN
DBMS_OUTPUT.PUT_LINE('An update statement ran');
END;
/
If the UPDATE changes five rows, the row trigger prints five lines and the
statement trigger prints one. The row trigger can read :OLD and
:NEW; the statement trigger cannot — it has no visibility into
individual rows.
Use row-level when the logic depends on the data that changed — auditing,
validation, computing derived values. Use statement-level when it only depends on
the fact that a statement ran — logging, permission checks, cache invalidation.
Statement triggers are cheaper because they run once.
A BEFORE trigger fires before the row is written to the table. An AFTER trigger
fires after the row is written.
The practical consequence: only BEFORE triggers can change the row being
written. Inside a BEFORE trigger you can assign to :NEW
and the assigned value is what gets stored. Inside an AFTER trigger, assigning to
:NEW has no effect — the row is already in the table.
-- BEFORE: modifies the value that gets stored
CREATE OR REPLACE TRIGGER trg_normalize_name
BEFORE INSERT OR UPDATE ON employees
FOR EACH ROW
BEGIN
:NEW.employee_name := UPPER(:NEW.employee_name);
END;
/
-- AFTER: cannot change the row, only react to it
CREATE OR REPLACE TRIGGER trg_audit
AFTER UPDATE ON employees
FOR EACH ROW
BEGIN
:NEW.employee_name := 'IGNORED'; -- Has no effect
END;
/
Use BEFORE when you need to validate or transform data on its way in. Use AFTER
when you need to react to a change that has already happened — auditing,
cascading updates to other tables, sending notifications.
They are pseudo-records that give the trigger access to the row being changed.
:OLD holds the values before the DML statement; :NEW
holds the values after.
What is available depends on the statement type:
Statement
:OLD
:NEW
INSERT
Undefined
The inserted row
UPDATE
Before values
After values
DELETE
The deleted row
Undefined
The classic use is comparison — only act when a value actually changed:
IF :OLD.salary != :NEW.salary THEN
INSERT INTO salary_audit ...;
END IF;
Two rules worth remembering. First, they are only available in row-level
triggers — statement triggers do not see individual rows, so there is no
:OLD or :NEW. Second, inside the trigger body they
are referenced with a colon, but in a WHEN clause the colon is
omitted:
FOR EACH ROW
WHEN (OLD.salary != NEW.salary) -- no colons in the WHEN clause
ORA-04091 happens when a row-level trigger tries to read or modify the same table
that fired it. The table is mid-change, so the database blocks access to prevent
the trigger from seeing an inconsistent snapshot.
-- Fails with ORA-04091
CREATE OR REPLACE TRIGGER trg_bad
BEFORE INSERT ON employees
FOR EACH ROW
DECLARE
v_count NUMBER;
BEGIN
SELECT COUNT(*) INTO v_count FROM employees; -- mutating read
END;
/
The statement-level trigger is safe — it fires after all rows are in place, so
reading the table is fine. The problem is specific to row-level triggers, which
fire while the table is still changing.
The modern fix is a compound trigger: collect the row data during the row phase
without touching the table, then query the table once in the after-statement
phase.
CREATE OR REPLACE TRIGGER trg_fixed
FOR INSERT ON employees
COMPOUND TRIGGER
TYPE id_tab IS TABLE OF employees.employee_id%TYPE;
g_ids id_tab := id_tab();
BEFORE EACH ROW IS
BEGIN
g_ids.EXTEND;
g_ids(g_ids.LAST) := :NEW.employee_id;
END BEFORE EACH ROW;
AFTER STATEMENT IS
v_count NUMBER;
BEGIN
SELECT COUNT(*) INTO v_count FROM employees; -- safe now
END AFTER STATEMENT;
END;
/
The older fix — an AFTER STATEMENT trigger plus a package variable to share state
— still works but requires two objects and shared global state. Compound triggers
keep everything in one place.
A compound trigger is a single trigger object that contains four timing sections:
BEFORE STATEMENT, BEFORE EACH ROW,
AFTER EACH ROW, and AFTER STATEMENT.
CREATE OR REPLACE TRIGGER trg_compound
FOR UPDATE ON employees
COMPOUND TRIGGER
BEFORE STATEMENT IS
BEGIN
DBMS_OUTPUT.PUT_LINE('Statement starting');
END BEFORE STATEMENT;
BEFORE EACH ROW IS
BEGIN
DBMS_OUTPUT.PUT_LINE('Row about to change: ' || :OLD.employee_id);
END BEFORE EACH ROW;
AFTER EACH ROW IS
BEGIN
DBMS_OUTPUT.PUT_LINE('Row changed: ' || :NEW.employee_id);
END AFTER EACH ROW;
AFTER STATEMENT IS
BEGIN
DBMS_OUTPUT.PUT_LINE('Statement complete');
END AFTER STATEMENT;
END;
/
You do not have to implement all four sections — only the ones you need. The value
is that they share the same trigger body, so they can share declared variables and
collections without a package.
Use a compound trigger when:
You hit a mutating table error and need to defer table access to after the statement.
You need to collect per-row data and process it as a set once the statement completes.
You want to avoid the two-trigger-plus-package-variable pattern that older code uses.
The one caveat: compound triggers are an Oracle feature. If the project targets
MySQL or SQL Server, you need a different approach.
An INSTEAD OF trigger fires in place of a DML statement on a view. The
database does not perform the DML directly — the trigger body does the work,
usually against the base tables.
It exists because many views cannot accept DML directly. A view that joins
employees and departments has no single base table to
insert into. The database cannot decide which table a new row belongs to. An
INSTEAD OF trigger makes that decision explicit:
CREATE OR REPLACE TRIGGER trg_v_insert
INSTEAD OF INSERT ON v_employee_dept
FOR EACH ROW
DECLARE
v_dept_id NUMBER;
BEGIN
SELECT department_id INTO v_dept_id
FROM departments
WHERE department_name = :NEW.department_name;
INSERT INTO employees (employee_id, employee_name, salary, department_id)
VALUES (:NEW.employee_id, :NEW.employee_name, :NEW.salary, v_dept_id);
END;
/
Now INSERT INTO v_employee_dept … works. The trigger resolves the
department name to an id and inserts into the real table.
Two things are specific to INSTEAD OF triggers. First, they are the only trigger
type defined on a view rather than a table. Second, they only exist for views —
on a table, the database can do the DML directly, so there is nothing to replace.
A MySQL Event is a scheduled task that runs on the clock. A trigger runs on data
changes. They solve different problems.
Aspect
Trigger
Event
Fires on
DML statement
Time / schedule
Created with
CREATE TRIGGER
CREATE EVENT
Needs scheduler
No
Yes (event_scheduler=ON)
Typical use
Auditing, validation
Cleanup, aggregation, reports
-- Event: runs every day at 2 AM
CREATE EVENT ev_nightly_cleanup
ON SCHEDULE EVERY 1 DAY
STARTS '2026-12-03 02:00:00'
DO
DELETE FROM salary_audit
WHERE change_date < DATE_SUB(NOW(), INTERVAL 90 DAY);
The trigger fires the instant a row changes. The event fires at the scheduled
time, regardless of what data changed. If the job is "purge audit rows older than
90 days", an event is the right tool — there is no DML event that would fire at
exactly the right moment.
Events are MySQL-specific. PostgreSQL has pg_cron, SQL Server has
SQL Server Agent jobs, Oracle has DBMS_SCHEDULER. The concept is
universal even though the syntax is not.
The scheduler is off by default on many MySQL installations. Events are created
successfully but never run until it is turned on.
Check the current state:
SHOW VARIABLES LIKE 'event_scheduler';
Turn it on at runtime:
SET GLOBAL event_scheduler = ON;
That change does not survive a server restart. To make it permanent, add it to the
configuration file:
# my.cnf or my.ini, under [mysqld]
event_scheduler = ON
Three possible values for the variable:
ON — scheduler runs, events execute.
OFF — scheduler is stopped, events do not execute.
DISABLED — scheduler cannot be started at runtime; only a config change enables it.
Check the scheduler status with SHOW PROCESSLIST — when enabled, a
process named event_scheduler appears in the list.
Yes. A trigger body is a PL/SQL block, so it can call procedures and functions
like any other block. That is useful for logic shared across multiple triggers.
CREATE OR REPLACE PROCEDURE log_change (
p_employee_id IN NUMBER,
p_old_salary IN NUMBER,
p_new_salary IN NUMBER
) AS
BEGIN
INSERT INTO salary_audit (employee_id, old_salary, new_salary, changed_by, change_date)
VALUES (p_employee_id, p_old_salary, p_new_salary, USER, SYSDATE);
END;
/
CREATE OR REPLACE TRIGGER trg_audit_via_proc
AFTER UPDATE OF salary ON employees
FOR EACH ROW
BEGIN
log_change(:OLD.employee_id, :OLD.salary, :NEW.salary);
END;
/
The procedure cannot read or modify the triggering table — the same mutating
table restriction applies to anything the trigger calls. If the procedure touches
employees, you get ORA-04091 even though the code lives outside the
trigger.
One more caution: if the procedure commits, the trigger's transaction commits
mid-statement, which is almost never what you want. Keep procedures called from
triggers commit-free.
The triggering DML statement fails, and any rows it had changed are rolled back.
The exception propagates to the caller unless the caller catches it.
CREATE OR REPLACE TRIGGER trg_reject_negative_salary
BEFORE INSERT OR UPDATE OF salary ON employees
FOR EACH ROW
BEGIN
IF :NEW.salary < 0 THEN
RAISE_APPLICATION_ERROR(-20002, 'Salary cannot be negative');
END IF;
END;
/
If someone runs UPDATE employees SET salary = -100 WHERE employee_id = 101,
the trigger raises an error, the update fails, and the caller sees:
ORA-20002: Salary cannot be negative
ORA-06512: at "SCOTT.TRG_REJECT_NEGATIVE_SALARY", line 3
Use RAISE_APPLICATION_ERROR rather than RAISE when you
want a custom message. The error code has to be between -20000 and -20999, and the
message has to be 2048 characters or fewer.
One important subtlety: if the exception is handled inside the trigger, the DML
statement succeeds. A trigger that catches its own error and logs it
leaves the row in place. That is sometimes intentional — "log the problem and
continue" — but more often it is a bug that lets bad data through.
Triggers solve real problems, but they bring problems of their own. Knowing the
downsides is what makes the decision about when to use one.
Invisible logic. A trigger fires without appearing in the
application code. Someone reading the application sees an INSERT and assumes that
is all that happens. The trigger's changes are invisible unless you know to look.
Hard to debug. When something goes wrong inside a trigger, the
error stack points at the trigger, not the application code that fired it. Tracing
a problem back to its source takes longer.
Cascading fires. A trigger on table A updates table B, which has
a trigger that updates table C, which has a trigger that updates table A — and you
have an infinite loop or a mutating table error several levels removed from where
you started.
Performance overhead. Every DML statement pays for every trigger
that fires. On a bulk load of a million rows, a row-level trigger fires a million
times. That is a real cost.
Not portable. Trigger syntax differs substantially between
Oracle, MySQL, SQL Server, and PostgreSQL. Logic in a trigger has to be rewritten
when the database changes.
Hidden dependencies. A trigger that reads a table creates a
dependency on it. Dropping or altering that table can invalidate the trigger or
break the DML that fires it.
The rule of thumb: use triggers for auditing, integrity enforcement, and derived
columns that every writer must have. Keep business logic in the application or in
stored procedures that the application calls deliberately.
The standard pattern is an AFTER UPDATE row-level trigger that compares
:OLD and :NEW and writes the difference to an audit
table.
CREATE OR REPLACE TRIGGER trg_salary_audit
AFTER UPDATE OF salary ON employees
FOR EACH ROW
WHEN (OLD.salary != NEW.salary)
BEGIN
INSERT INTO salary_audit (
audit_id, employee_id, old_salary, new_salary, changed_by, change_date
) VALUES (
salary_audit_seq.NEXTVAL, :OLD.employee_id, :OLD.salary, :NEW.salary, USER, SYSDATE
);
END;
/
The WHEN clause is the important part. Without it, an update that
sets salary = salary still writes an audit row. With it, only genuine
changes are recorded.
A complete audit setup usually includes three more elements:
An audit table with columns for old values, new values, user, timestamp, and the operation type.
A sequence or identity column for the audit primary key — audit tables rarely use the source table's keys.
A view over the audit table that joins back to the source table for readable reports.
For full auditing that covers INSERT, UPDATE, and DELETE, use three triggers or a
compound trigger with separate sections for each operation.
The terminology varies by database, but the distinction is about scope: how much
of the database the trigger watches.
DML triggers — the triggers described in every earlier question —
fire on INSERT, UPDATE, DELETE against a specific table or view. This is what most
people mean by "trigger".
DDL triggers fire on DDL statements like CREATE, ALTER, DROP,
TRUNCATE, GRANT, REVOKE. You can scope them to a schema or to the whole database.
-- Oracle: schema-level DDL trigger
CREATE OR REPLACE TRIGGER trg_ddl_audit
BEFORE DDL ON SCHEMA
BEGIN
INSERT INTO ddl_audit (event_name, fired_by, fired_at)
VALUES (ORA_SYSEVENT, USER, SYSDATE);
END;
/
System triggers fire on database events like
LOGON, LOGOFF, STARTUP, SHUTDOWN,
and SERVERERROR. They are scoped to the whole database.
-- Oracle: log every connection
CREATE OR REPLACE TRIGGER trg_logon
AFTER LOGON ON DATABASE
BEGIN
INSERT INTO connection_log (username, logon_time)
VALUES (USER, SYSDATE);
END;
/
The practical distinction: DML triggers are about data, DDL and system triggers are
about the database itself. The latter are used for security auditing, compliance
logging, and preventing unauthorized schema changes.
Disabling is a normal part of trigger management — during bulk loads, during
migrations, or when the trigger logic is being rewritten.
-- Oracle
ALTER TRIGGER trg_salary_audit DISABLE;
ALTER TRIGGER trg_salary_audit ENABLE;
-- MySQL
ALTER TABLE employees DISABLE TRIGGER trg_salary_audit;
Disabling a trigger does not drop it. The definition stays, and re-enabling brings
it back with the same logic. That matters when you need to load data without
triggering audit logic — the trigger is still there for normal use afterwards.
The trigger's status shows in the data dictionary:
-- Oracle
SELECT trigger_name, status
FROM user_triggers
WHERE table_name = 'EMPLOYEES';
A DISABLED trigger does not fire. An ENABLED trigger
does. An INVALID trigger is one that failed to compile — it also does
not fire, but that is a bug to fix, not a choice.
One warning: disabling a trigger does not disable the DML that fires it. An
INSERT into employees still happens while the trigger is
disabled — it just does not get audited.
Yes. Oracle and most databases allow multiple triggers on the same table for the
same event. Their firing order is not guaranteed unless you specify it explicitly.
-- Oracle: order the firing
CREATE OR REPLACE TRIGGER trg_first
BEFORE UPDATE ON employees
FOR EACH ROW
FOLLOWS trg_second
BEGIN
...
END;
/
The FOLLOWS clause (available in Oracle 11g and later) controls order
explicitly. Without it, firing order is unpredictable — usually the order triggers
were created, but not guaranteed.
Multiple triggers on the same event are usually a design smell. If two triggers
are both auditing salary changes, the logic is split in ways that make debugging
harder. A single trigger with clear internal structure is easier to maintain.
The exception is when triggers are owned by different teams or modules — a
security audit trigger written by compliance and a business audit trigger written
by the application team can coexist if they touch different tables. Even then,
coordination between them is worth the effort.
Triggers participate in the same transaction as the DML that fires them. If the
transaction rolls back, the trigger's changes roll back with it.
BEGIN
UPDATE employees SET salary = 60000 WHERE employee_id = 101;
-- Trigger inserts into salary_audit automatically
ROLLBACK;
-- The UPDATE and the audit INSERT are both undone
END;
That behaviour is usually what you want. An audit row that survives a rollback
would be lying about data that never existed.
There are exceptions where audit history should persist even after a rollback —
failed login attempts, for example. That is normally implemented with an
autonomous transaction:
CREATE OR REPLACE PROCEDURE log_failed_attempt AS
PRAGMA AUTONOMOUS_TRANSACTION;
BEGIN
INSERT INTO failed_attempts (username, attempted_at) VALUES (USER, SYSDATE);
COMMIT; -- commits independently of the calling transaction
END;
/
Use autonomous transactions sparingly. They break the transactional model, and a
bug in the autonomous code can commit data the calling transaction intended to
roll back.
One more interaction: DDL commits. If a trigger runs DDL (via
dynamic SQL, since DDL is not directly supported in triggers), the DDL commits the
current transaction before and after running. That is rarely intended inside a
trigger, and it is one reason to avoid DDL in trigger bodies.
A well-behaved trigger has a specific shape: it validates its input, does not
touch its own table, handles exceptions deliberately, and stays out of transaction
control.
CREATE OR REPLACE TRIGGER trg_employee_salary_guard
BEFORE INSERT OR UPDATE OF salary, department_id ON employees
FOR EACH ROW
DECLARE
v_max_salary employees.salary%TYPE;
BEGIN
-- Validate: reject negative values
IF :NEW.salary < 0 THEN
RAISE_APPLICATION_ERROR(-20001, 'Salary cannot be negative');
END IF;
-- Look up a value from another table (safe — different table)
SELECT MAX(salary) INTO v_max_salary
FROM salary_bands
WHERE department_id = :NEW.department_id;
IF :NEW.salary > v_max_salary THEN
RAISE_APPLICATION_ERROR(-20002, 'Salary exceeds band for department');
END IF;
EXCEPTION
WHEN NO_DATA_FOUND THEN
RAISE_APPLICATION_ERROR(-20003, 'No salary band for department ' || :NEW.department_id);
WHEN OTHERS THEN
RAISE_APPLICATION_ERROR(-20004, 'Salary validation failed: ' || SQLERRM);
END;
/
The pieces of that template:
BEFORE, because it validates on the way in and can reject before anything is written.
OF salary, department_id, so it only fires when the relevant columns are updated — not on every UPDATE.
No read from employees, because that would trigger the mutating table error.
RAISE_APPLICATION_ERROR with distinct codes, so callers can distinguish validation failures from other errors.
Explicit exception handling for the realistic failure modes, not just WHEN OTHERS.
That combination — BEFORE, column-scoped, no self-reference, explicit error codes
— is the shape of a trigger that will not surprise anyone in production.
Mistakes I Keep Seeing in Interviews
These come up repeatedly. None of them are exotic, and every one of them is easy to avoid
once you know it is coming.
Mistake one: confusing row-level and statement-level triggers. Candidates
write a trigger that reads :NEW without FOR EACH ROW, or expect a
statement trigger to fire per row. The keywords are one word apart and the behaviour is
completely different.
Mistake two: assuming an AFTER trigger can modify the row. It cannot —
the row is already written. Only BEFORE triggers can change :NEW.
Mistake three: not knowing the mutating table error exists. When asked
"what happens if a trigger reads its own table", the correct answer is ORA-04091, and the
fix is a compound trigger.
Mistake four: putting business logic in triggers. Triggers should handle
cross-cutting concerns — audit, integrity, derived columns. Complex business rules belong
in stored procedures or application code where they can be tested and traced.
Mistake five: no exception handling. A trigger that fails for any reason
takes down the DML statement that fired it. Catching and logging the exception — or
raising a clear custom error — is not optional.
Mistake six: committing inside a trigger. A COMMIT in a trigger commits
the whole transaction mid-statement. That leaves the application unable to roll back and
is one of the hardest bugs to track down later.
Follow-Up Questions Interviewers Ask
Getting the first answer right is only half the interview. What usually decides the
outcome is what happens next. Here is what to prepare for on the trigger and event topics.
After "What is a trigger?" — expect
"How does a trigger differ from a stored procedure?"
"When would you not use a trigger?"
"Can a trigger take parameters?"
"What is the difference between a trigger and a constraint?"
After "Row-level vs statement-level" — expect
"Which one is faster and why?"
"When do you need :OLD and :NEW?"
"What happens with a bulk update of 1000 rows?"
"How would you log a statement that changed zero rows?"
After "Mutating table" — expect
"What causes ORA-04091?"
"What are two ways to fix it?"
"Why doesn't a statement-level trigger hit the same error?"
"What is a compound trigger and what are its sections?"
After "MySQL Events" — expect
"What is the difference between an event and a trigger?"
"How do you enable the event scheduler?"
"What is the equivalent of a MySQL event in Oracle?"
"What happens to a one-time event after it runs?"
For every question above, prepare a second-level answer. The candidates who pass are not
the ones who memorized the first answer — they are the ones who kept going for another
thirty seconds and said something useful about why it matters.
Quick Quiz
Three questions to check whether the topics above have landed.
1. What happens when a row-level trigger reads the table that fired it?
2. Which trigger type can modify :NEW and change what gets stored?
3. What is the MySQL equivalent of a scheduled job that runs at 2 AM daily?