PostgreSQL triggers: BEFORE, AFTER and INSTEAD OF
Short answer
A trigger runs a function automatically when rows are inserted, updated, deleted or truncated. First write a trigger function (no arguments, returns trigger), then attach it with CREATE TRIGGER. [S1][S2]
CREATE TRIGGER set_updated BEFORE UPDATE ON items
FOR EACH ROW EXECUTE FUNCTION touch_updated_at();
Key points
- BEFORE, AFTER or INSTEAD OF sets when the function runs. [S2]
- INSTEAD OF triggers must be FOR EACH ROW and only work on views. [S2]
Claims
- id: C1 claim: The trigger function must be defined before the trigger. source: S1 evidence: "The trigger function must be defined before the trigger itself can be created."
- id: C2 claim: The same trigger function can be used for multiple triggers. source: S1 evidence: "The same trigger function can be used for multiple triggers."
- id: C3 claim: CREATE TRIGGER creates a new trigger. source: S2 evidence: "CREATE TRIGGER creates a new trigger."
- id: C4 claim: INSTEAD OF triggers must be FOR EACH ROW and only on views. source: S2 evidence: "must be marked FOR EACH ROW, and can only be defined on views"
Sources
- [S1] PostgreSQL: Documentation: 18: 37.1. Overview of Trigger Behavior. PostgreSQL Global Development Group. https://www.postgresql.org/docs/current/trigger-definition.html . License: PostgreSQL License. Accessed 2026-11-04.
- [S2] PostgreSQL: Documentation: 18: CREATE TRIGGER. PostgreSQL Global Development Group. https://www.postgresql.org/docs/current/sql-createtrigger.html . License: PostgreSQL License. Accessed 2026-11-04.
License: this note is CC BY 4.0 (https://creativecommons.org/licenses/by/4.0/). Summary by iinventedlight (AI-assisted).
License: CC-BY-4.0 · Summary by iinventedlight (AI-assisted). Sources: PostgreSQL Global Development Group, PostgreSQL: Documentation: 18: 37.1. Overview of Trigger Behavior, PostgreSQL License; PostgreSQL Global Development Group, PostgreSQL: Documentation: 18: CREATE TRIGGER, PostgreSQL License.
Cite this
iinventedlight. 2026. "PostgreSQL triggers: BEFORE, AFTER and INSTEAD OF." iinventedlight Library, iil:note:vwmqqjg1, version of 2026-11-04. https://iinventedlight.com/library/notes/postgres-triggers/. License: CC-BY-4.0.
@misc{iil_note_vwmqqjg1,
author = {{iinventedlight}},
title = {{PostgreSQL triggers: BEFORE, AFTER and INSTEAD OF}},
howpublished = {iinventedlight Library},
year = {2026},
date = {2026-11-04},
url = {https://iinventedlight.com/library/notes/postgres-triggers/},
note = {Permanent ID iil:note:vwmqqjg1. License: CC-BY-4.0.},
}
Spotted a mistake? Use the MCP feedback tool or email hello@iinventedlight.com.
For language models and agents: start at /llms.txt. This page in Markdown: /library/notes/postgres-triggers.md.