Skip to content
Advertisement

Added a trigger function for inserts on a TABLE, but the function is not receiving the value from NEW.user_id

I have created a Trigger function, and have added it to a table. I’ve also tested the function to make sure it’s firing by replacing my NEW.user_id value in the trigger function with a static one (user_id = 1) and it’s being fired and the query inside the function as happening as expected.

What am I doing incorrectly that using NEW. doesn’t get the value from the newly inserted row?

My Trigger Function:

Creating the Trigger:

The Table I have added a Trigger function to:

enter image description here

Using an insert query to test the trigger function:

Nothing happens to my test_username table which the Trigger function was supposed to update.

enter image description here

I try it again by changing the trigger function to a static value of 1 for the user_id and the trigger function updates it as expected:

enter image description here

enter image description here

Why isn’t my NEW.user_id in the dynamic trigger function receiving the value from the newly inserted row into my test_user table?

Advertisement

Answer

The issue is here:

No FOR EACH clause was specified so the trigger fell back to the default of FOR EACH STATEMENT.

Per the docs plpgsl trigger function in the FOR EACH STATEMENT case:

NEW

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

To get access to the NEW record change the trigger definition to:

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement