CREATE_TRIGGER(7pg17)

πŸ“¦ version 17.11, in opensuse-leap 16.0

πŸ’… CREATE_TRIGGER β€” define a new trigger πŸ’…

okay bestie, this is the CREATE TRIGGER(7) page from the PostgreSQL 17.11 Documentation. we're gonna make triggers make sense, fr fr. πŸ¦‹

✨ NAME ✨

CREATE_TRIGGER β€” define a new trigger.

πŸŽ€ SYNOPSIS πŸŽ€

CREATE [ OR REPLACE ] [ CONSTRAINT ] TRIGGER name { BEFORE | AFTER | INSTEAD OF } { event [ OR ... ] }
    ON table_name
    [ FROM referenced_table_name ]
    [ NOT DEFERRABLE | [ DEFERRABLE ] [ INITIALLY IMMEDIATE | INITIALLY DEFERRED ] ]
    [ REFERENCING { { OLD | NEW } TABLE [ AS ] transition_relation_name } [ ... ] ]
    [ FOR [ EACH ] { ROW | STATEMENT } ]
    [ WHEN ( condition ) ]
    EXECUTE { FUNCTION | PROCEDURE } function_name ( arguments )

where event can be one of:

INSERT
UPDATE [ OF column_name [, ... ] ]
DELETE
TRUNCATE

πŸ’– DESCRIPTION πŸ’–

okay so CREATE TRIGGER makes a brand-new trigger. CREATE OR REPLACE TRIGGER will either create a new trigger or replace an existing one. the trigger gets attached to the specified table, view, or foreign table, and it will execute the specified function function_name when certain operations are performed on that table. πŸ‘‘

if you wanna replace the current definition of an existing trigger, use CREATE OR REPLACE TRIGGER, specifying the existing trigger's name and parent table. all other properties are replaced. periodt. πŸ’…

the trigger can be specified to fire:

  • before the operation is attempted on a row β€” before constraints are checked and the INSERT, UPDATE, or DELETE is attempted
  • after the operation has completed β€” after constraints are checked and the INSERT, UPDATE, or DELETE has completed
  • instead of the operation β€” in the case of inserts, updates, or deletes on a view

if the trigger fires before or instead of the event, the trigger can skip the operation for the current row, or change the row being inserted (for INSERT and UPDATE operations only). if the trigger fires after the event, all changes β€” including the effects of other triggers β€” are β€œvisible” to the trigger. πŸ‘€

a trigger marked FOR EACH ROW is called once for every row that the operation modifies. for example, a DELETE that affects 10 rows will cause any ON DELETE triggers on the target relation to be called 10 separate times, once for each deleted row. in contrast, a trigger marked FOR EACH STATEMENT only executes once for any given operation, regardless of how many rows it modifies β€” and in particular, an operation that modifies zero rows will still result in the execution of any applicable FOR EACH STATEMENT triggers. no cap. 🫢

triggers specified to fire INSTEAD OF the trigger event must be marked FOR EACH ROW, and can only be defined on views. BEFORE and AFTER triggers on a view must be marked as FOR EACH STATEMENT. πŸŽ€

in addition, triggers may be defined to fire for TRUNCATE, though only FOR EACH STATEMENT. πŸ’€

here's the vibe check on which types of triggers may be used on tables, views, and foreign tables:

  • BEFORE
    • INSERT/UPDATE/DELETE β€” row-level: tables and foreign tables; statement-level: tables, views, and foreign tables
    • TRUNCATE β€” row-level: β€”; statement-level: tables and foreign tables
  • AFTER
    • INSERT/UPDATE/DELETE β€” row-level: tables and foreign tables; statement-level: tables, views, and foreign tables
    • TRUNCATE β€” row-level: β€”; statement-level: tables and foreign tables
  • INSTEAD OF
    • INSERT/UPDATE/DELETE β€” row-level: views; statement-level: β€”
    • TRUNCATE β€” row-level: β€”; statement-level: β€”

also, a trigger definition can specify a Boolean WHEN condition, which will be tested to see whether the trigger should be fired. in row-level triggers, the WHEN condition can examine the old and/or new values of columns of the row. statement-level triggers can also have WHEN conditions, although the feature is not so useful for them since the condition cannot refer to any values in the table. iykyk. 🌸

if multiple triggers of the same kind are defined for the same event, they will be fired in alphabetical order by name. πŸ“š

when the CONSTRAINT option is specified, this command creates a constraint trigger. this is the same as a regular trigger except that the timing of the trigger firing can be adjusted using SET CONSTRAINTS. constraint triggers must be AFTER ROW triggers on plain tables (not foreign tables). they can be fired either at the end of the statement causing the triggering event, or at the end of the containing transaction; in the latter case they are said to be deferred. a pending deferred-trigger firing can also be forced to happen immediately by using SET CONSTRAINTS. constraint triggers are expected to raise an exception when the constraints they implement are violated. 🚨

the REFERENCING option enables collection of transition relations, which are row sets that include all of the rows inserted, deleted, or modified by the current SQL statement. this feature lets the trigger see a global view of what the statement did, not just one row at a time. this option is only allowed for an AFTER trigger on a plain table (not a foreign table). the trigger should not be a constraint trigger. also, if the trigger is an UPDATE trigger, it must not specify a column_name list when using this option. OLD TABLE may only be specified once, and only for a trigger that can fire on UPDATE or DELETE; it creates a transition relation containing the before-images of all rows updated or deleted by the statement. similarly, NEW TABLE may only be specified once, and only for a trigger that can fire on UPDATE or INSERT; it creates a transition relation containing the after-images of all rows updated or inserted by the statement. πŸ¦‹

SELECT does not modify any rows so you cannot create SELECT triggers. rules and views may provide workable solutions to problems that seem to need SELECT triggers. πŸ™ˆ

refer to Chapter 37 for more information about triggers. ✨

πŸ’œ PARAMETERS πŸ’œ

Okay bestie, this is the part where we go through literally every single knob and dial. No skipping, no "you'll figure it out" β€” we're doing all of them. 🫢

  • name β€” the name you're giving your shiny new trigger. It has to be different from the name of any other trigger on that same table (no twinsies allowed, sorry πŸ’…). It also cannot be schema-qualified β€” your trigger just inherits the schema of its table, periodt. And if it's a constraint trigger, this is also the name you'll use when you change the trigger's behaviour with SET CONSTRAINTS.
  • BEFORE, AFTER, INSTEAD OF β€” this decides when the function gets called: before the event, after the event, or instead of the event. Big main-character decision energy. One caveat tho: a constraint trigger can only be specified as AFTER. That's the whole rule, no wiggle room. ✨
  • event β€” one of INSERT, UPDATE, DELETE, or TRUNCATE; it says which event fires the trigger. You can stack multiple events using OR, except when transition relations are requested (then it's one at a time, bestie).

For UPDATE events you can also hand it a list of columns, like this:

UPDATE OF column_name1 [, column_name2 ... ]

The trigger will only fire if at least one of the listed columns is mentioned as a target of the UPDATE command, or if one of the listed columns is a generated column that depends on a column that's the target of the UPDATE. Sneaky but iconic. 🌸

INSTEAD OF UPDATE events do not allow a list of columns. And a column list can't be specified when requesting transition relations either. So yeah, pick your lane. 😭

  • table_name β€” the name (optionally schema-qualified) of the table, view, or foreign table the trigger is for. That's the whole vibe.
  • referenced_table_name β€” the (possibly schema-qualified) name of another table referenced by the constraint. This one's for foreign-key constraints and is not recommended for general use β€” it's giving "only if you know what you're doing". This can only be specified for constraint triggers.
  • DEFERRABLE, NOT DEFERRABLE, INITIALLY IMMEDIATE, INITIALLY DEFERRED β€” the default timing of the trigger. Head over to the CREATE TABLE (CREATE_TABLE(7)) docs for the deets on these constraint options, they're covered there. Again: only for constraint triggers. πŸŽ€
  • REFERENCING β€” this keyword sits immediately before the declaration of one or two relation names that give you access to the transition relations of the triggering statement. It's basically the introvert's door to the data. πŸ¦‹
  • OLD TABLE, NEW TABLE β€” tells you whether the relation name that follows is for the before-image transition relation or the after-image transition relation. Old pic vs. new pic, honestly. πŸ“Έ
  • transition_relation_name β€” the (unqualified!) name to be used within the trigger for this transition relation. Note: unqualified. Not schema'd. Keep it simple bestie.
  • FOR EACH ROW, FOR EACH STATEMENT β€” this specifies whether the trigger function fires once for every row affected by the trigger event, or just once per SQL statement. If you specify neither, FOR EACH STATEMENT is the default. And heads up: constraint triggers can only be specified FOR EACH ROW. No exceptions. πŸ’€
  • condition β€” a Boolean expression that determines whether the trigger function actually gets executed. If WHEN is specified, the function is only called if the condition returns true. In FOR EACH ROW triggers, the WHEN condition can refer to columns of the old and/or new row values by writing OLD.column_name or NEW.column_name respectively. And of course β€” obviously β€” INSERT triggers can't refer to OLD, and DELETE triggers can't refer to NEW. Like, there's nothing there. πŸ™ˆ

INSTEAD OF triggers do not support WHEN conditions.

Currently, WHEN expressions cannot contain subqueries. Nope. Not yet.

One thing to keep in your notes: for constraint triggers, evaluation of the WHEN condition is not deferred β€” it happens immediately after the row update operation is performed. If the condition doesn't evaluate to true, then the trigger isn't queued for deferred execution at all. So it just… doesn't happen. πŸ’…

  • function_name β€” a user-supplied function declared as taking no arguments and returning type trigger, which runs when the trigger fires. That's the whole job description.

In the syntax of CREATE TRIGGER, the keywords FUNCTION and PROCEDURE are equivalent, but the referenced function must in any case be a function, not a procedure. So the keyword PROCEDURE here is historical and deprecated β€” it's a legacy moment, we don't stan. 😭

  • arguments β€” an optional comma-separated list of arguments handed to the function when the trigger executes. These arguments are literal string constants. Simple names and numeric constants can be written here too, but they all get converted to strings. Please check the description of the implementation language of the trigger function to find out how these arguments can be accessed within the function β€” it might be different from normal function arguments. Fr fr, check the docs, don't just assume. πŸ“

🌸 NOTES 🌸

  • To create or replace a trigger on a table, you need the TRIGGER privilege on that table. You also need EXECUTE privilege on the trigger function. Both. No cap. πŸ”‘
  • Use DROP TRIGGER to remove a trigger. That's the cleanup crew. 🧹
  • Creating a row-level trigger on a partitioned table will cause an identical "clone" trigger to be created on each of its existing partitions ✨ β€” and any partitions created or attached later will get an identical trigger too. If there's already a conflictingly-named trigger on a child partition, you get an error, unless you use CREATE OR REPLACE TRIGGER, in which case that trigger gets replaced with a clone trigger. And when a partition is detached from its parent, its clone triggers are removed. Clean.
  • A column-specific trigger (the one defined with the UPDATE OF column_name syntax) fires when any of its columns are listed as targets in the UPDATE command's SET list. And here's the messy part bestie: it's possible for a column's value to change even when the trigger is not fired, because changes made to the row's contents by BEFORE UPDATE triggers are not considered. Conversely, a command like UPDATE ... SET x = x ... will fire a trigger on column x, even though the column's value did not change. I know. I know. 😭
  • In a BEFORE trigger, the WHEN condition is evaluated just before the function is or would be executed, so using WHEN is not materially different from testing the same condition at the beginning of the trigger function. Note in particular that the NEW row seen by the condition is the current value, as possibly modified by earlier triggers. Also, a BEFORE trigger's WHEN condition is not allowed to examine the system columns of the NEW row (like ctid), because those won't have been set yet. Not set yet = can't look. πŸ’…
  • In an AFTER trigger, the WHEN condition is evaluated just after the row update occurs, and it determines whether an event gets queued to fire the trigger at the end of the statement. So when an AFTER trigger's WHEN condition doesn't return true, there's no need to queue an event, and no need to re-fetch the row at end of statement. That can result in significant speedups in statements that modify a lot of rows, if the trigger only needs to fire for a few of them. Performance slay. πŸ”₯
  • In some cases a single SQL command can fire more than one kind of trigger. For instance, an INSERT with an ON CONFLICT DO UPDATE clause may cause both insert and update operations, so it'll fire both kinds of triggers as needed. The transition relations supplied to triggers are specific to their event type; so an INSERT trigger sees only the inserted rows, while an UPDATE trigger sees only the updated rows. Everyone gets their own lane. πŸ‘‘
  • Row updates or deletions caused by foreign-key enforcement actions β€” like ON UPDATE CASCADE or ON DELETE SET NULL β€” are treated as part of the SQL command that caused them (note that such actions are never deferred). Relevant triggers on the affected table will be fired, so this is another way an SQL command might fire triggers that don't directly match its type. In simple cases, triggers that request transition relations will see all changes caused in their table by a single original SQL command as a single transition relation. However β€” and this is the plot twist β€” there are cases where the presence of an AFTER ROW trigger that requests transition relations will cause the foreign-key enforcement actions triggered by a single SQL command to be split into multiple steps, each with its own transition relation(s). In those cases, any statement-level triggers that are present will be fired once per creation of a transition relation set, ensuring the triggers see each affected row in a transition relation once and only once. We love a guarantee. πŸ’–
  • Statement-level triggers on a view are fired only if the action on the view is handled by a row-level INSTEAD OF trigger. If the action is handled by an INSTEAD rule, then whatever statements are emitted by the rule are executed in place of the original statement naming the view β€” so the triggers that get fired are those on the tables named in the replacement statements. Similarly, if the view is automatically updatable, the action is handled by automatically rewriting the statement into an action on the view's base table, so the base table's statement-level triggers are the ones that get fired. It's giving "who's actually doing the work here". πŸ¦‹
  • Modifying a partitioned table, or a table with inheritance children, fires statement-level triggers attached to the explicitly named table, but not statement-level triggers for its partitions or child tables. In contrast, row-level triggers are fired on the rows in affected partitions or child tables, even if they're not explicitly named in the query. If a statement-level trigger was defined with transition relations named by a REFERENCING clause, then before and after images of rows are visible from all affected partitions or child tables. In the case of inheritance children, the row images include only columns that are present in the table the trigger is attached to. Details matter, bestie. 🌈
  • Currently, row-level triggers with transition relations cannot be defined on partitions or inheritance child tables. Also, triggers on partitioned tables may not be INSTEAD OF. That's just how it is right now. ⭐
  • Currently, the OR REPLACE option is not supported for constraint triggers. Sorry babe. πŸ’€
  • Replacing an existing trigger within a transaction that has already performed updating actions on the trigger's table is not recommended β€” like, genuinely, don't. Trigger firing decisions, or portions of firing decisions, that have already been made will not be reconsidered, so the effects could be surprising. Surprising in the bad way. 😭
  • There are a few built-in trigger functions that can solve common problems without you having to write your own trigger code β€” see Section 9.29. Free real estate, honestly. πŸŽ€

πŸŽ€ EXAMPLES πŸŽ€

Okay bestie, this is the part where it all clicks. Real triggers, real syntax, let's go πŸ’–

Example one: run the function check_account_update every single time a row in the table accounts is about to be updated. Before it happens. Like a bouncer checking your outfit before you get in πŸ‘‘

CREATE TRIGGER check_update
    BEFORE UPDATE ON accounts
    FOR EACH ROW
    EXECUTE FUNCTION check_account_update();

Example two: same trigger, but ✨glow up✨ β€” now it only fires if the column balance is named as a target in the UPDATE command:

CREATE OR REPLACE TRIGGER check_update
    BEFORE UPDATE OF balance ON accounts
    FOR EACH ROW
    EXECUTE FUNCTION check_account_update();

Example three: this version is pickier β€” it only runs the function if the column balance actually changed value. Not just mentioned, actually changed. The way it should be πŸ’…

CREATE TRIGGER check_update
    BEFORE UPDATE ON accounts
    FOR EACH ROW
    WHEN (OLD.balance IS DISTINCT FROM NEW.balance)
    EXECUTE FUNCTION check_account_update();

Example four: want to log updates to accounts, but only when something actually changed? Same energy:

CREATE TRIGGER log_update
    AFTER UPDATE ON accounts
    FOR EACH ROW
    WHEN (OLD.* IS DISTINCT FROM NEW.*)
    EXECUTE FUNCTION log_account_update();

Example five: here we run view_insert_row for each row, inserting rows into the tables underneath a view. INSTEAD OF, doing the work for the view, main character energy fr fr 🌈

CREATE TRIGGER view_insert
    INSTEAD OF INSERT ON my_view
    FOR EACH ROW
    EXECUTE FUNCTION view_insert_row();

Example six: this one runs check_transfer_balances_to_zero once per statement to confirm the transfer rows offset to a net of zero. Balance check, no cap 🧚

CREATE TRIGGER transfer_insert
    AFTER INSERT ON transfer
    REFERENCING NEW TABLE AS inserted
    FOR EACH STATEMENT
    EXECUTE FUNCTION check_transfer_balances_to_zero();

Example seven: run check_matching_pairs for each row to confirm changes are made to matching pairs at the same time (by the same statement). Cute, coordinated, iconic 🫢

CREATE TRIGGER paired_items_update
    AFTER UPDATE ON paired_items
    REFERENCING NEW TABLE AS newtab OLD TABLE AS oldtab
    FOR EACH ROW
    EXECUTE FUNCTION check_matching_pairs();

Also pssst β€” Section 37.4 has a whole complete example of a trigger function written in C, if that's your thing πŸ‘€


πŸ’€ COMPATIBILITY πŸ’€

So the CREATE TRIGGER statement in PostgreSQL implements a subset of the SQL standard. Read: it's giving "we didn't do all of it." Here's what's currently missing, bestie:

  • While transition table names for AFTER triggers are specified using the REFERENCING clause in the standard way, the row variables used in FOR EACH ROW triggers may not be specified in a REFERENCING clause. They're available in a manner that depends on the language the trigger function is written in β€” but it's fixed for any one language. Some languages effectively behave as though there's a REFERENCING clause containing OLD ROW AS OLD NEW ROW AS NEW. iykyk 🌸
  • The standard allows transition tables to be used with column-specific UPDATE triggers, but then the set of rows that should be visible in the transition tables depends on the trigger's column list. PostgreSQL does not currently implement this. Ngl, it's just not here yet πŸ™ˆ
  • PostgreSQL only allows the execution of a user-defined function for the triggered action. The standard allows a bunch of other SQL commands β€” like CREATE TABLE β€” to be the triggered action. But bestie, this limitation is not hard to work around: just create a user-defined function that executes the commands you want. Problem solved, slay πŸ’…

SQL says multiple triggers should fire in time-of-creation order. PostgreSQL uses name order, which was judged to be more convenient. Periodt.

SQL also specifies that BEFORE DELETE triggers on cascaded deletes fire after the cascaded DELETE completes. PostgreSQL's behavior? BEFORE DELETE always fires before the delete action, even a cascading one. This is considered more consistent. πŸ”₯

⚠️ Heads up, this is important: there is also nonstandard behavior if BEFORE triggers modify rows or prevent updates during an update that's caused by a referential action. This can lead to constraint violations, or stored data that does not honor the referential constraint. So like, be careful with that one fr fr 😭

The ability to specify multiple actions for a single trigger using OR is a PostgreSQL extension of the SQL standard ⭐

The ability to fire triggers for TRUNCATE is a PostgreSQL extension of the SQL standard β€” and so is the ability to define statement-level triggers on views.

CREATE CONSTRAINT TRIGGER is a PostgreSQL extension of the SQL standard. So is the OR REPLACE option. We love an extension moment πŸ‘‘


πŸ¦‹ SEE ALSO πŸ¦‹

Go read these next, bestie, they're all linked together like a little Unix friend group πŸ’œ


That's the whole page, you made it!! πŸŽ‰ This one's from PostgreSQL 17.11, dated 2026, and it's the CREATE TRIGGER(7) page. Go forth and trigger responsibly, bestie πŸ’–βœ¨πŸŽ€

πŸ“¦ where this page comes from