What if your database could silently watch every change and keep perfect records for you?
Why Trigger for audit logging in PostgreSQL? - Purpose & Use Cases
Start learning this pattern below
Jump into concepts and practice - no test required
Imagine you have a busy database where many users update important records every day. You want to keep track of every change to know who did what and when. Doing this by checking logs or asking users manually is like trying to remember every detail of a long conversation--it's confusing and unreliable.
Manually tracking changes means writing extra code everywhere, missing some updates, or forgetting to log important details. It's slow, easy to make mistakes, and hard to keep consistent. This can lead to lost data history and trouble finding out what happened if something goes wrong.
Using a trigger for audit logging means the database automatically records every change as it happens. It's like having a smart assistant who watches every update and writes down the details for you, without you needing to remember or do extra work.
UPDATE users SET name = 'Alice' WHERE id = 1; -- Then separately INSERT INTO audit_log ...
CREATE TRIGGER audit_trigger AFTER UPDATE ON users FOR EACH ROW EXECUTE FUNCTION audit_log_function();
This lets you trust that every change is safely recorded, making it easy to review history, find mistakes, and meet compliance rules without extra effort.
A bank uses audit triggers to automatically log every transaction change, so if there's ever a dispute, they can quickly see who changed what and when.
Manual logging is slow and error-prone.
Triggers automate audit logging reliably.
Automatic logs help track changes and improve trust.
Practice
Solution
Step 1: Understand what triggers do
Triggers run code automatically when data changes occur in a table.Step 2: Connect triggers to audit logging
Audit logging means recording who changed what and when, which triggers help automate.Final Answer:
To automatically record changes made to data in a table -> Option BQuick Check:
Trigger = automatic audit record [OK]
- Thinking triggers speed up queries
- Confusing triggers with backups
- Assuming triggers create tables
Solution
Step 1: Check function return type and language
Trigger functions must return type 'trigger' and use 'plpgsql' language.Step 2: Verify correct use of OLD and NEW
For audit logging on updates/deletes, OLD.* is used to capture previous data; function returns NEW to continue operation.Final Answer:
CREATE FUNCTION audit_log() RETURNS trigger AS $$ BEGIN INSERT INTO audit_table VALUES (OLD.*); RETURN NEW; END; $$ LANGUAGE plpgsql; -> Option CQuick Check:
Trigger function syntax = CREATE FUNCTION audit_log() RETURNS trigger AS $$ BEGIN INSERT INTO audit_table VALUES (OLD.*); RETURN NEW; END; $$ LANGUAGE plpgsql; [OK]
- Using RETURNS void instead of RETURNS trigger
- Returning OLD instead of NEW
- Wrong language like SQL instead of plpgsql
CREATE FUNCTION audit_func() RETURNS trigger AS $$ BEGIN INSERT INTO audit_log(user_name, action_time) VALUES (current_user, now()); RETURN NEW; END; $$ LANGUAGE plpgsql;
CREATE TRIGGER audit_trigger AFTER INSERT ON employees FOR EACH ROW EXECUTE FUNCTION audit_func();
What happens when a new row is inserted into
employees?Solution
Step 1: Understand AFTER INSERT trigger behavior
AFTER INSERT triggers run after a new row is added, so the insert succeeds first.Step 2: Analyze trigger function actions
The function inserts a row intoaudit_logwith current user and timestamp, logging the event.Final Answer:
A new row is added toaudit_logwith current user and timestamp -> Option AQuick Check:
AFTER INSERT triggers log data after insert [OK]
- Thinking AFTER INSERT prevents insert
- Assuming trigger deletes data
- Believing no action happens after insert
CREATE FUNCTION audit_changes() RETURNS trigger AS $$ BEGIN INSERT INTO audit_log VALUES (NEW.*); RETURN NEW; END; $$ LANGUAGE plpgsql;
But when the trigger fires (e.g., on INSERT or UPDATE to the table), you get an error. What is the likely cause?
Solution
Step 1: Check compatibility of NEW.* with audit_log table
NEW.* expands to all columns of the triggering table, which must match audit_log columns exactly.Step 2: Identify mismatch causes error
If audit_log has different columns or order, the insert fails when the trigger fires.Final Answer:
The audit_log table does not match the NEW record structure -> Option DQuick Check:
Column mismatch causes insert error [OK]
- Thinking RETURN NEW is invalid
- Assuming language must be SQL
- Believing triggers cannot insert data
products table. Which trigger function code correctly captures both old and new data for audit logging?Solution
Step 1: Identify correct use of OLD and NEW in UPDATE triggers
OLD contains previous row data, NEW contains updated data; audit log needs both.Step 2: Check function logic and return value
Insert old and new names correctly, then return NEW to allow update to proceed.Final Answer:
CREATE FUNCTION audit_update() RETURNS trigger AS $$ BEGIN INSERT INTO audit_log(old_name, new_name) VALUES (OLD.name, NEW.name); RETURN NEW; END; $$ LANGUAGE plpgsql; -> Option AQuick Check:
OLD before, NEW after update [OK]
- Swapping OLD and NEW values
- Returning OLD instead of NEW
- Using UPDATE instead of INSERT in audit log
