0
0
PostgreSQLquery~10 mins

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

Choose your learning style9 modes available
Concept Flow - Trigger for audit logging
Data Change Event
Trigger Fires
Trigger Function Executes
Insert Audit Record
Original Operation Completes
When a data change happens, the trigger activates, runs a function that logs the change, then the original operation finishes.
Execution Sample
PostgreSQL
CREATE FUNCTION audit_log() RETURNS trigger AS $$
BEGIN
  INSERT INTO audit_table VALUES (NEW.id, NEW.data, now());
  RETURN NEW;
END;
$$ LANGUAGE plpgsql;

CREATE TRIGGER audit_trigger
AFTER INSERT ON main_table
FOR EACH ROW EXECUTE FUNCTION audit_log();
This code creates a trigger function that logs inserts into an audit table whenever a new row is added to main_table.
Execution Table
StepEventTrigger ActionAudit InsertResult
1Insert row into main_tableTrigger fires after insertInsert audit record with NEW row data and timestampRow inserted in main_table and audit_table
2Insert row into main_tableTrigger fires after insertInsert audit record with NEW row data and timestampRow inserted in main_table and audit_table
3No more insertsNo triggerNo audit insertProcess ends
💡 No more insert events, trigger does not fire, audit logging stops
Variable Tracker
VariableStartAfter 1After 2Final
NEW.idnull101102102
NEW.datanull'First row''Second row''Second row'
now()null2024-06-01 10:00:002024-06-01 10:05:002024-06-01 10:05:00
Key Moments - 3 Insights
Why does the trigger function use RETURN NEW?
RETURN NEW passes the new row back to the database so the insert can complete successfully, as shown in execution_table step 1 and 2.
When exactly does the trigger fire?
The trigger fires AFTER the insert event on main_table, as shown in execution_table step 1 and 2 under 'Trigger Action'.
What happens if the audit insert fails?
If the audit insert fails, the whole insert operation rolls back, preventing inconsistent data, because triggers run within the same transaction.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the audit insert action at step 2?
AInsert audit record with NEW row data and timestamp
BNo audit insert
CTrigger does not fire
DDelete audit record
💡 Hint
Check the 'Audit Insert' column at row 2 in the execution_table
At which step does the trigger stop firing?
AStep 1
BStep 2
CStep 3
DNever stops
💡 Hint
Look at the 'Trigger Action' column in execution_table row 3
If the trigger function returned NULL instead of NEW, what would happen?
AThe insert would succeed normally
BThe insert would be canceled and no row added
CThe audit record would not be inserted
DThe trigger would fire twice
💡 Hint
Refer to key_moments about RETURN NEW and how it affects the insert operation
Concept Snapshot
Trigger for audit logging in PostgreSQL:
- Create a trigger function that inserts audit info
- Use AFTER INSERT trigger on target table
- Trigger fires on each row insert
- Function inserts audit record and returns NEW
- Ensures audit logs match data changes
- Trigger runs inside transaction, so failures rollback
Full Transcript
In PostgreSQL, audit logging can be done using triggers. When a row is inserted into a table, a trigger can fire after the insert event. This trigger runs a function that inserts a record into an audit table, capturing details like the new row's id, data, and the current timestamp. The trigger function must return NEW to allow the insert to complete. If the audit insert fails, the entire transaction rolls back, ensuring data consistency. The execution table shows each step: insert event, trigger firing, audit insert, and completion. Variables like NEW.id and NEW.data hold the new row's values during trigger execution. This method helps track changes automatically and reliably.