Maintaining tamper-proof audit trails, tracking who modified salary records, and preventing invalid modifications cannot rely on application developers remembering to write audit code. A SQL Trigger is an event-driven routine that fires automatically whenever an INSERT, UPDATE, or DELETE executes against a monitored table.
• BEFORE INSERT / AFTER INSERT
• BEFORE UPDATE / AFTER UPDATE
• BEFORE DELETE / AFTER DELETE
| DML Event | OLD.column Available? | NEW.column Available? |
|---|---|---|
| INSERT | No (row did not exist yet) | Yes (incoming values to be written) |
| UPDATE | Yes (original values before edit) | Yes (revised values after edit) |
| DELETE | Yes (values being removed) | No (row is gone) |
-- 1. Create audit log table
CREATE TABLE salary_audit_log (
audit_id INT AUTO_INCREMENT PRIMARY KEY,
emp_id INT NOT NULL,
old_salary DECIMAL(10, 2),
new_salary DECIMAL(10, 2),
changed_by VARCHAR(50),
changed_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
-- 2. Create AFTER UPDATE Trigger on employees
DELIMITER //
CREATE TRIGGER trg_audit_salary_update
AFTER UPDATE ON employees
FOR EACH ROW
BEGIN
-- Log only if salary was actually modified
IF OLD.salary <> NEW.salary THEN
INSERT INTO salary_audit_log (emp_id, old_salary, new_salary, changed_by)
VALUES (OLD.emp_id, OLD.salary, NEW.salary, USER());
END IF;
END //
DELIMITER ;
Next, let us master query profiling, indexing diagnostics, and tuning using SQL Query Optimization & EXPLAIN Plans!
A Trigger is a specialized stored program that automatically executes ('fires') in response to a specific DML event (INSERT, UPDATE, or DELETE) occurring on a specific table.
OLD refers to the existing values of a row BEFORE modification (available in UPDATE and DELETE triggers). NEW refers to the incoming values of a row AFTER modification (available in INSERT and UPDATE triggers).
A BEFORE trigger fires before the row data is written to disk (ideal for data validation, scrubbing, or assigning computed values). An AFTER trigger fires after the modification succeeds (ideal for logging audit history or syncing external tables).
Proceed to the next class in sequence to build production mastery of relational database architecture.
Continue to Class 49: Query Optimization → Previous: ← Stored Procedures | Full Syllabus
Writing reusable procedural database routines.
Logging who modified records, old values, and timestamps.
When to enforce business rules with constraints vs triggers.
Why cascading triggers can severely degrade write performance.