Bird
0
0

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:
  1. Step 1: Check function return type and language

    Trigger functions must return type 'trigger' and use 'plpgsql' language.
  2. 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.
  3. Final Answer:

    CREATE FUNCTION audit_log() RETURNS trigger AS $$ BEGIN INSERT INTO audit_table VALUES (OLD.*); RETURN NEW; END; $$ LANGUAGE plpgsql; -> Option C
  4. 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

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More PostgreSQL Quizzes