Bird
Raised Fist0
PostgreSQLquery~10 mins

AFTER trigger behavior in PostgreSQL - Step-by-Step Execution

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Concept Flow - AFTER trigger behavior
DML Statement Executed
Row(s) Modified in Table
AFTER Trigger Fires
Trigger Function Executes
Transaction Continues or Commits
After a data change (INSERT, UPDATE, DELETE), the AFTER trigger runs its function once the row modification is done.
Execution Sample
PostgreSQL
CREATE TRIGGER trg_after_insert
AFTER INSERT ON employees
FOR EACH ROW
EXECUTE FUNCTION log_insert();
This trigger runs the log_insert() function after each new row is inserted into employees.
Execution Table
StepActionTrigger TimingTrigger Fired?Trigger Function Result
1INSERT new employee rowBefore row changeNoNo trigger yet
2Row inserted into employees tableRow change doneNoRow data inserted
3AFTER INSERT trigger firesAfter row changeYeslog_insert() runs, logs insertion
4Trigger function completesAfter triggerYesLog entry created
5Transaction continuesAfter triggerNoReady for commit or next operation
💡 Trigger fires only after the row is inserted, ensuring the row modification is complete before trigger logic runs.
Variable Tracker
VariableStartAfter Step 1After Step 2After Step 3Final
new_rownullContains new employee dataInserted in tableAvailable to trigger functionUnchanged after trigger
log_tableemptyemptyemptyOne new log entry addedContains log entry
Key Moments - 2 Insights
Why does the AFTER trigger run only after the row is inserted?
Because AFTER triggers execute only once the data modification is complete, as shown in execution_table step 3, ensuring the trigger sees the final data state.
Can the AFTER trigger modify the row that was just inserted?
No, AFTER triggers cannot change the row data that caused them because the row is already written; this is clear from step 2 and 3 in the execution_table.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, at which step does the AFTER trigger function run?
AStep 3
BStep 1
CStep 2
DStep 5
💡 Hint
Check the 'Trigger Fired?' column in execution_table rows.
According to variable_tracker, what is the state of new_row after the trigger runs?
Anull
BAvailable and unchanged
CModified by trigger
DDeleted
💡 Hint
Look at the 'new_row' values after Step 3 and Final in variable_tracker.
If the trigger was BEFORE instead of AFTER, when would it run?
AAfter the row is inserted
BAfter transaction commit
CBefore the row is inserted
DNever
💡 Hint
Compare the 'Trigger Timing' column in execution_table for BEFORE vs AFTER triggers.
Concept Snapshot
AFTER triggers run after the data change is done.
They see the final row state.
They cannot modify the triggering row.
Useful for logging or cascading actions.
Defined with AFTER keyword in CREATE TRIGGER.
Fires once per row or statement after change.
Full Transcript
When you perform an INSERT, UPDATE, or DELETE in PostgreSQL, an AFTER trigger runs only after the row has been changed in the table. This means the trigger function sees the final data state. For example, an AFTER INSERT trigger runs after the new row is inserted. It cannot change the row that caused it because the data is already saved. This behavior is useful for logging or other actions that depend on the completed change. The trigger fires once per affected row or once per statement, depending on how it is defined.

Practice

(1/5)
1. What is the main purpose of an AFTER trigger in PostgreSQL?
easy
A. To execute a function after the main database operation completes successfully
B. To prevent a database operation from happening
C. To execute a function before the database operation starts
D. To rollback the transaction if an error occurs

Solution

  1. Step 1: Understand the timing of AFTER triggers

    AFTER triggers run only after the main database action (INSERT, UPDATE, DELETE) has completed successfully.
  2. Step 2: Identify the purpose of AFTER triggers

    They are used to perform actions like logging or notifications after the main operation finishes.
  3. Final Answer:

    To execute a function after the main database operation completes successfully -> Option A
  4. Quick Check:

    AFTER trigger = runs after operation [OK]
Hint: AFTER triggers run only after successful main actions [OK]
Common Mistakes:
  • Confusing AFTER with BEFORE triggers
  • Thinking AFTER triggers can stop the main operation
  • Assuming AFTER triggers run before the operation
2. Which of the following is the correct syntax to create an AFTER INSERT trigger in PostgreSQL?
easy
A. CREATE TRIGGER trg AFTER INSERT ON table_name FOR EACH ROW EXECUTE FUNCTION func_name();
B. CREATE TRIGGER trg AFTER INSERT ON table_name EXECUTE FUNCTION func_name();
C. CREATE TRIGGER trg BEFORE INSERT ON table_name EXECUTE FUNCTION func_name();
D. CREATE TRIGGER trg AFTER INSERT ON table_name FOR EACH STATEMENT EXECUTE FUNCTION func_name();

Solution

  1. Step 1: Recall the correct CREATE TRIGGER syntax

    PostgreSQL requires specifying FOR EACH ROW or FOR EACH STATEMENT for triggers.
  2. Step 2: Identify the correct syntax for AFTER INSERT

    CREATE TRIGGER trg AFTER INSERT ON table_name FOR EACH ROW EXECUTE FUNCTION func_name(); correctly uses AFTER INSERT ON table_name FOR EACH ROW EXECUTE FUNCTION func_name();
  3. Final Answer:

    CREATE TRIGGER trg AFTER INSERT ON table_name FOR EACH ROW EXECUTE FUNCTION func_name(); -> Option A
  4. Quick Check:

    AFTER INSERT + FOR EACH ROW + EXECUTE FUNCTION = CREATE TRIGGER trg AFTER INSERT ON table_name FOR EACH ROW EXECUTE FUNCTION func_name(); [OK]
Hint: AFTER triggers need FOR EACH ROW or STATEMENT [OK]
Common Mistakes:
  • Omitting FOR EACH ROW or FOR EACH STATEMENT
  • Using BEFORE instead of AFTER
  • Using EXECUTE PROCEDURE instead of EXECUTE FUNCTION in modern PostgreSQL
3. Given the following trigger and table, what will be the output after inserting a row?
CREATE TABLE users(id SERIAL PRIMARY KEY, name TEXT);
CREATE FUNCTION log_insert() RETURNS trigger AS $$
BEGIN
  RAISE NOTICE 'Inserted user: %', NEW.name;
  RETURN NEW;
END;
$$ LANGUAGE plpgsql;
CREATE TRIGGER after_user_insert AFTER INSERT ON users FOR EACH ROW EXECUTE FUNCTION log_insert();

INSERT INTO users(name) VALUES ('Alice');
medium
A. No output, the insert happens silently
B. An error occurs because RETURN NEW is invalid in AFTER trigger
C. The insert is rolled back due to the trigger
D. A notice message: 'Inserted user: Alice'

Solution

  1. Step 1: Understand the trigger function behavior

    The function raises a NOTICE with the inserted user's name after insert.
  2. Step 2: Recognize AFTER trigger effects

    AFTER triggers run after the insert, so the notice will be shown, and the insert completes successfully.
  3. Final Answer:

    A notice message: 'Inserted user: Alice' -> Option D
  4. Quick Check:

    AFTER trigger raises notice = A notice message: 'Inserted user: Alice' [OK]
Hint: AFTER triggers can raise notices after insert [OK]
Common Mistakes:
  • Thinking RETURN NEW is invalid in AFTER triggers
  • Expecting no output from the trigger
  • Assuming the insert is rolled back
4. You created an AFTER UPDATE trigger but it never fires. Which of the following is the most likely cause?
medium
A. The trigger was created as BEFORE UPDATE instead of AFTER UPDATE
B. The UPDATE statement does not change any column values
C. The trigger function does not return NEW or OLD
D. The trigger is defined FOR EACH STATEMENT but the function expects FOR EACH ROW

Solution

  1. Step 1: Understand when AFTER UPDATE triggers fire

    AFTER UPDATE triggers fire only if the UPDATE actually changes data.
  2. Step 2: Analyze the cause of no trigger firing

    If the UPDATE sets columns to their existing values, no actual change occurs, so the trigger does not fire.
  3. Final Answer:

    The UPDATE statement does not change any column values -> Option B
  4. Quick Check:

    UPDATE with no change = no AFTER trigger fire [OK]
Hint: AFTER UPDATE triggers fire only on actual data changes [OK]
Common Mistakes:
  • Assuming triggers fire even if no data changes
  • Confusing BEFORE and AFTER triggers
  • Not matching trigger function with trigger type
5. You want to log every DELETE on a table after it happens, but only if the deleted row's status is 'active'. Which is the best way to implement this using an AFTER trigger?
hard
A. Create an AFTER DELETE trigger that logs all deletes without checking status
B. Create a BEFORE DELETE trigger that checks OLD.status and prevents deletion if not 'active'
C. Create an AFTER DELETE trigger that checks if OLD.status = 'active' inside the trigger function before logging
D. Create a BEFORE DELETE trigger that logs only if OLD.status = 'active'

Solution

  1. Step 1: Understand the requirement for conditional logging after delete

    We want to log only after the delete happens and only for rows with status 'active'.
  2. Step 2: Choose the correct trigger timing and condition

    AFTER DELETE trigger can access OLD row data and conditionally log if OLD.status = 'active'.
  3. Final Answer:

    Create an AFTER DELETE trigger that checks if OLD.status = 'active' inside the trigger function before logging -> Option C
  4. Quick Check:

    Conditional logging after delete = AFTER trigger with check [OK]
Hint: Use AFTER DELETE trigger with condition inside function [OK]
Common Mistakes:
  • Using BEFORE trigger which runs before deletion
  • Logging all deletes without condition
  • Trying to prevent deletion instead of logging