2

I am new to PostgreSQL and wondering if there is a way to create one trigger function for insert and update operations which can be called from multiple tables?

2
  • 1
    Yes, that's possible, see e.g. here: wiki.postgresql.org/wiki/Audit_trigger_91plus Commented Jun 1, 2015 at 20:04
  • Thanks for the Link. In my case i have 20 main tables & 20 staging tables. Any event like insert or update on the main tables the data should be inserted/updated on their respective staging tables. Can I accomplish this by creating only one trigger function and call it from different tables? Commented Jun 1, 2015 at 20:31

1 Answer 1

3

Yes, you can create one trigger procedure and call it from different tables. From within the trigger procedure you can access several special variables which provide metadata about the table which called the trigger i.e.TG_TABLE_NAME and TG_TABLE_SCHEMA. Using those metadata you can accurately define what the trigger have to do depending on which table called it.

From the documentation:

TG_TABLE_NAME Data type name; the name of the table that caused the trigger invocation.

TG_TABLE_SCHEMA Data type name; the name of the schema of the table that caused the trigger invocation.

The variable TG_OP provide the operation which caused the trigger to be called:

TG_OP Data type text; a string of INSERT, UPDATE, DELETE, or TRUNCATE telling for which operation the trigger was fired.

Other very useful special variables are NEW and OLD. They contain the old and the new data which are changed by the database operation:

NEW Data type RECORD; variable holding the new database row for INSERT/UPDATE operations in row-level triggers. This variable is unassigned in statement-level triggers and for DELETE operations.

OLD Data type RECORD; variable holding the old database row for UPDATE/DELETE operations in row-level triggers. This variable is unassigned in statement-level triggers and for INSERT operations.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.