1.BEFORE, AFTER and INSTEAD OF Triggers
BEFORE triggers fire before the write is attempted and can modify the row or cancel the operation entirely (by returning NULL). AFTER triggers fire once the write has actually happened and cannot change it — they see the final state. INSTEAD OF triggers replace the operation entirely and only exist on views, which have no storage of their own to write to.
Key features
- BEFORE row-level triggers can return a modified NEW row (INSERT/UPDATE) or return NULL to silently skip the operation for that row
- AFTER triggers cannot modify the row or cancel the operation — the write has already happened by the time they run
- INSTEAD OF triggers are only valid on views, are always row-level (FOR EACH ROW), and their return value is ignored
- A BEFORE trigger must return the same row unchanged if it does not intend to modify or skip it — returning nothing changes behavior
- For generated columns, BEFORE triggers see the OLD generated value but not yet the NEW one; only AFTER triggers see the final NEW value
BEFORE vs AFTER vs INSTEAD OF
- BEFORE — can modify NEW or return NULL to skip
- leads to the actual write (may veto or reshape)
- the actual write — row is inserted/updated/deleted
- leads to AFTER (already committed to this transaction)
- AFTER — sees the final state, cannot change it
Command
-- BEFORE: normalize a value before it is stored
CREATE TRIGGER normalize_email BEFORE INSERT OR UPDATE ON users
FOR EACH ROW EXECUTE FUNCTION lower_email();
-- AFTER: react to a write that has already happened
CREATE TRIGGER log_order_insert AFTER INSERT ON orders
FOR EACH ROW EXECUTE FUNCTION write_audit_log();
-- INSTEAD OF: a view has no rows to write to directly
CREATE TRIGGER insert_via_view INSTEAD OF INSERT ON active_users_view
FOR EACH ROW EXECUTE FUNCTION redirect_insert_to_users();BEFORE can modify NEW or return NULL to veto the write; AFTER only observes a write that already happened and cannot undo it; INSTEAD OF replaces the operation entirely and exists only on views, which have nothing of their own to write to.