Write an audit trigger
- SQL course
- Advanced
- Lesson 52/81
- 4 min
Log changes with an audit trigger.
Audit trigger
An audit trigger records table changes to a log table. It answers who, what, when.
CREATE TRIGGER audit_product
AFTER UPDATE ON products
FOR EACH ROW
BEGIN
INSERT INTO audit_log (table_name, old_value, new_value, changed_at)
VALUES ('products', OLD.name, NEW.name, NOW());
END;This query writes changes to an audit table.
The trigger audit_product is created.
Audit trigger — details
An audit trigger keeps a change history. Used for investigation and compliance.
An entry usually holds the table name, the old and new values, the user who made the change and a timestamp from NOW().
Practice Audit trigger
Write an audit_product trigger: record changes to audit_log.
Starter code
-- audit trigger
CREATE TRIGGER audit_productSample solution
CREATE TRIGGER audit_product
AFTER UPDATE ON products
FOR EACH ROW
BEGIN
INSERT INTO audit_log (table_name, old_value, new_value, changed_at)
VALUES ('products', OLD.name, NEW.name, NOW());
ENDExpected output
Trigger oluşturuldu
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Add NOW
VALUES ('products', OLD.name, NEW.name, ____());
VALUES ('products', OLD.name, NEW.name, NOW());
Explanation: NOW() records the date and time when the change happened.
2 Write an audit trigger: match the terms
| Term | Meaning |
|---|---|
audit |
audit |
log |
record |
who/what/when |
question |
change |
history |
3 What does an audit trigger record?
- Indexes
- The query plan
- The changes Correct answer
- Views
Explanation: An audit trigger records changes.