Bird
Raised Fist0
SQLquery~10 mins

Trigger for audit logging in SQL - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Trigger for audit logging
Data Change Event
↓
Trigger Fires
↓
Capture Old and New Data
↓
Insert Audit Record
↓
Original Operation Completes
When data changes, the trigger activates, captures old and new data, and inserts a record into the audit log before the original operation finishes.
Execution Sample
SQL
CREATE TRIGGER audit_trigger
AFTER UPDATE ON employees
FOR EACH ROW
BEGIN
  INSERT INTO audit_log(employee_id, old_salary, new_salary, changed_at)
  VALUES (OLD.id, OLD.salary, NEW.salary, CURRENT_TIMESTAMP);
END;
This trigger logs salary changes in the employees table into audit_log after each update.
Execution Table
StepEventTrigger ActionData CapturedAudit Log Inserted
1Update employee salaryTrigger fires after updateOLD.id=101, OLD.salary=5000, NEW.salary=5500Insert audit_log(101, 5000, 5500, timestamp)
2Audit record insertedAudit log updatedAudit record with old and new salary savedAudit log contains new entry
3Original update completesNo trigger actionN/AAudit log unchanged
💡 Trigger completes after inserting audit record; original update finishes successfully.
Variable Tracker
VariableStartAfter Step 1After Step 2Final
OLD.id101101101101
OLD.salary5000500050005000
NEW.salary5500550055005500
audit_log entriesemptyempty1 new record1 new record
Key Moments - 2 Insights
Why does the trigger use OLD and NEW values?
The trigger uses OLD to get the data before the change and NEW to get the data after the change, so it can record what exactly was modified (see execution_table step 1).
When does the trigger run in relation to the update?
This trigger runs AFTER the update operation, ensuring the audit log records the final changed data (execution_table step 1 shows 'Trigger fires after update').
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what data does the trigger capture at step 1?
ABoth old and new salary values
BOnly the new salary value
COnly the old salary value
DNo data is captured
💡 Hint
Check the 'Data Captured' column in execution_table row 1.
At which step is the audit log updated with a new record?
AStep 1
BStep 2
CStep 3
DNo step updates the audit log
💡 Hint
Look at the 'Audit Log Inserted' column in execution_table row 2.
If the trigger was BEFORE UPDATE instead of AFTER UPDATE, what would change?
AThe audit log would record the new data before the update happens
BThe audit log would not record any data
CThe audit log would record the old data before the update happens
DThe trigger would not fire at all
💡 Hint
Consider when OLD and NEW values are available relative to the update operation.
Concept Snapshot
Trigger for audit logging syntax:
CREATE TRIGGER name AFTER UPDATE ON table
FOR EACH ROW
INSERT INTO audit_log(...) VALUES (OLD.col, NEW.col, CURRENT_TIMESTAMP);

Behavior:
- Fires after data change
- Captures old and new values
- Inserts audit record

Key rule: Use OLD and NEW to track changes.
Full Transcript
This visual execution shows how a trigger for audit logging works in SQL. When an update happens on the employees table, the trigger fires after the update. It captures the old and new salary values using OLD and NEW references. Then it inserts a record into the audit_log table with these values and the current timestamp. Finally, the original update operation completes. Variables like OLD.id and OLD.salary remain constant during the trigger, while the audit_log gains a new entry. Key points include understanding why OLD and NEW are used and when the trigger runs relative to the update. The quiz questions help reinforce these ideas by referencing the execution steps and variable changes.

Practice

(1/5)
1. What is the main purpose of a trigger used for audit logging in SQL?
easy
A. To automatically record changes made to data in a table
B. To speed up query execution on large tables
C. To create backups of the database periodically
D. To enforce user permissions on tables

Solution

  1. Step 1: Understand what audit logging means

    Audit logging means keeping a record of changes made to data, such as who changed it and when.
  2. Step 2: Identify the role of triggers in audit logging

    Triggers automatically run when data changes and can insert records into an audit table to log these changes.
  3. Final Answer:

    To automatically record changes made to data in a table -> Option A
  4. Quick Check:

    Audit logging = record data changes automatically [OK]
Hint: Triggers run automatically on data changes for logging [OK]
Common Mistakes:
  • Thinking triggers speed up queries
  • Confusing audit logging with backups
  • Believing triggers manage user permissions
2. Which of the following is the correct syntax to create a trigger that fires after an INSERT on a table named employees?
easy
A. CREATE TRIGGER trg AFTER INSERT ON employees FOR EACH ROW BEGIN ... END;
B. CREATE TRIGGER trg BEFORE UPDATE ON employees FOR EACH ROW BEGIN ... END;
C. CREATE TRIGGER trg AFTER DELETE ON employees FOR EACH ROW BEGIN ... END;
D. CREATE TRIGGER trg ON employees AFTER INSERT BEGIN ... END;

Solution

  1. Step 1: Identify correct trigger timing and event

    The question asks for a trigger after INSERT, so it must say AFTER INSERT.
  2. Step 2: Check syntax correctness

    CREATE TRIGGER trg AFTER INSERT ON employees FOR EACH ROW BEGIN ... END; uses correct syntax: CREATE TRIGGER name AFTER INSERT ON table FOR EACH ROW BEGIN ... END;
  3. Final Answer:

    CREATE TRIGGER trg AFTER INSERT ON employees FOR EACH ROW BEGIN ... END; -> Option A
  4. Quick Check:

    Trigger syntax = CREATE TRIGGER ... AFTER INSERT ON ... [OK]
Hint: Use AFTER INSERT ON table FOR EACH ROW for insert triggers [OK]
Common Mistakes:
  • Using BEFORE UPDATE instead of AFTER INSERT
  • Omitting FOR EACH ROW clause
  • Wrong trigger event like DELETE instead of INSERT
3. Given this trigger snippet for audit logging:
CREATE TRIGGER audit_update AFTER UPDATE ON products FOR EACH ROW BEGIN INSERT INTO audit_log (product_id, old_price, new_price) VALUES (OLD.id, OLD.price, NEW.price); END;

What will be inserted into audit_log when a product's price changes from 100 to 120?
medium
A. (product_id: NULL, old_price: 100, new_price: 120)
B. (product_id: product's id, old_price: NULL, new_price: NULL)
C. (product_id: product's id, old_price: 120, new_price: 100)
D. (product_id: product's id, old_price: 100, new_price: 120)

Solution

  1. Step 1: Understand OLD and NEW in triggers

    OLD refers to the row before update, NEW refers to the row after update.
  2. Step 2: Analyze the insert statement

    The trigger inserts OLD.id, OLD.price, and NEW.price, so product_id is the old id, old_price is 100, new_price is 120.
  3. Final Answer:

    (product_id: product's id, old_price: 100, new_price: 120) -> Option D
  4. Quick Check:

    OLD = before update, NEW = after update [OK]
Hint: OLD = old row, NEW = new row in update triggers [OK]
Common Mistakes:
  • Mixing OLD and NEW values
  • Assuming NULL values for unchanged columns
  • Confusing product_id with price values
4. You wrote this trigger to log deletions:
CREATE TRIGGER log_delete AFTER DELETE ON orders FOR EACH ROW BEGIN INSERT INTO audit_orders (order_id, deleted_at) VALUES (NEW.id, NOW()); END;

Why does this trigger cause an error?
medium
A. Missing FOR EACH STATEMENT clause
B. Using NEW keyword in a DELETE trigger causes an error
C. NOW() function is not allowed in triggers
D. Trigger must be BEFORE DELETE, not AFTER DELETE

Solution

  1. Step 1: Recall OLD and NEW usage in triggers

    In DELETE triggers, only OLD is available because the row is removed; NEW does not exist.
  2. Step 2: Identify the error cause

    The trigger uses NEW.id in a DELETE trigger, which causes an error because NEW is undefined.
  3. Final Answer:

    Using NEW keyword in a DELETE trigger causes an error -> Option B
  4. Quick Check:

    DELETE triggers use OLD, not NEW [OK]
Hint: Use OLD in DELETE triggers, NEW causes errors [OK]
Common Mistakes:
  • Using NEW instead of OLD in DELETE triggers
  • Confusing FOR EACH ROW and FOR EACH STATEMENT
  • Thinking NOW() is disallowed in triggers
5. You want to create an audit trigger that logs INSERT and UPDATE actions on the customers table into customer_audit. Which approach correctly handles both actions in one trigger?
hard
A. Create two separate triggers: one AFTER INSERT and one AFTER UPDATE
B. Create one AFTER INSERT trigger and ignore UPDATE actions
C. Create one trigger AFTER INSERT OR UPDATE and use conditional logic inside
D. Create a BEFORE DELETE trigger to log INSERT and UPDATE

Solution

  1. Step 1: Understand trigger event options

    Some SQL systems allow triggers on multiple events like AFTER INSERT OR UPDATE.
  2. Step 2: Use conditional logic inside trigger

    Inside the trigger, check if the event is INSERT or UPDATE to log accordingly.
  3. Step 3: Compare options

    Create one trigger AFTER INSERT OR UPDATE and use conditional logic inside correctly combines both events in one trigger with logic; Create two separate triggers: one AFTER INSERT and one AFTER UPDATE uses two triggers, which is valid but not one trigger.
  4. Final Answer:

    Create one trigger AFTER INSERT OR UPDATE and use conditional logic inside -> Option C
  5. Quick Check:

    One trigger can handle multiple events with conditions [OK]
Hint: Use AFTER INSERT OR UPDATE with IF inside trigger [OK]
Common Mistakes:
  • Trying to log UPDATE in an INSERT-only trigger
  • Using BEFORE DELETE for INSERT/UPDATE logging
  • Not using conditional logic inside multi-event triggers
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard