Which of the following is the correct syntax to create a trigger function for audit logging in PostgreSQL?
easy📝 Syntax Q12 of 15
PostgreSQL - Triggers in PostgreSQL
Which of the following is the correct syntax to create a trigger function for audit logging in PostgreSQL?
ACREATE TRIGGER audit_log BEFORE INSERT ON audit_table EXECUTE FUNCTION log_changes();
BCREATE FUNCTION audit_log() RETURNS void AS $$ BEGIN UPDATE audit_table SET changed = TRUE; END; $$ LANGUAGE sql;
CCREATE FUNCTION audit_log() RETURNS trigger AS $$ BEGIN INSERT INTO audit_table VALUES (OLD.*); RETURN NEW; END; $$ LANGUAGE plpgsql;
DCREATE FUNCTION audit_log() RETURNS trigger AS $$ BEGIN INSERT INTO audit_table VALUES (NEW.*); RETURN OLD; END; $$ LANGUAGE plpgsql;
Step-by-Step Solution
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 C
Quick Check:
Trigger function syntax = CREATE FUNCTION audit_log() RETURNS trigger AS $$ BEGIN INSERT INTO audit_table VALUES (OLD.*); RETURN NEW; END; $$ LANGUAGE plpgsql; [OK]
Quick Trick:Trigger functions return 'trigger' and use plpgsql [OK]
Common Mistakes:
Using RETURNS void instead of RETURNS trigger
Returning OLD instead of NEW
Wrong language like SQL instead of plpgsql
Master "Triggers in PostgreSQL" in PostgreSQL
9 interactive learning modes - each teaches the same concept differently