CREATE_TRIGGER(7pg17)
π 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, orDELETEis attempted - after the operation has completed β after constraints are checked and the
INSERT,UPDATE, orDELETEhas 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:
BEFOREINSERT/UPDATE/DELETEβ row-level: tables and foreign tables; statement-level: tables, views, and foreign tablesTRUNCATEβ row-level: β; statement-level: tables and foreign tables
AFTERINSERT/UPDATE/DELETEβ row-level: tables and foreign tables; statement-level: tables, views, and foreign tablesTRUNCATEβ row-level: β; statement-level: tables and foreign tables
INSTEAD OFINSERT/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 withSET 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 asAFTER. That's the whole rule, no wiggle room. β¨eventβ one ofINSERT,UPDATE,DELETE, orTRUNCATE; it says which event fires the trigger. You can stack multiple events usingOR, 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 theCREATE 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 STATEMENTis the default. And heads up: constraint triggers can only be specifiedFOR EACH ROW. No exceptions. πconditionβ a Boolean expression that determines whether the trigger function actually gets executed. IfWHENis specified, the function is only called if the condition returns true. InFOR EACH ROWtriggers, theWHENcondition can refer to columns of the old and/or new row values by writingOLD.column_nameorNEW.column_namerespectively. And of course β obviously βINSERTtriggers can't refer toOLD, andDELETEtriggers can't refer toNEW. 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 typetrigger, 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
TRIGGERprivilege on that table. You also needEXECUTEprivilege on the trigger function. Both. No cap. π - Use
DROP TRIGGERto 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_namesyntax) fires when any of its columns are listed as targets in theUPDATEcommand'sSETlist. 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 byBEFORE UPDATEtriggers are not considered. Conversely, a command likeUPDATE ... SET x = x ...will fire a trigger on columnx, even though the column's value did not change. I know. I know. π - In a
BEFOREtrigger, theWHENcondition is evaluated just before the function is or would be executed, so usingWHENis not materially different from testing the same condition at the beginning of the trigger function. Note in particular that theNEWrow seen by the condition is the current value, as possibly modified by earlier triggers. Also, aBEFOREtrigger'sWHENcondition is not allowed to examine the system columns of theNEWrow (likectid), because those won't have been set yet. Not set yet = can't look. π - In an
AFTERtrigger, theWHENcondition 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 anAFTERtrigger'sWHENcondition 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
INSERTwith anON CONFLICT DO UPDATEclause 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 anINSERTtrigger sees only the inserted rows, while anUPDATEtrigger sees only the updated rows. Everyone gets their own lane. π - Row updates or deletions caused by foreign-key enforcement actions β like
ON UPDATE CASCADEorON 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 anAFTER ROWtrigger 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 OFtrigger. If the action is handled by anINSTEADrule, 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
REFERENCINGclause, 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 REPLACEoption 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
AFTERtriggers are specified using theREFERENCINGclause in the standard way, the row variables used inFOR EACH ROWtriggers may not be specified in aREFERENCINGclause. 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 aREFERENCINGclause containingOLD ROW AS OLD NEW ROW AS NEW. iykyk πΈ - The standard allows transition tables to be used with column-specific
UPDATEtriggers, 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 π
ALTER TRIGGER(ALTER_TRIGGER(7))DROP TRIGGER(DROP_TRIGGER(7))CREATE FUNCTION(CREATE_FUNCTION(7))SET CONSTRAINTS(SET_CONSTRAINTS(7))
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
- opensuse-leap 16.0: postgresql17 17.11-160000.1.1 Β· PostgreSQL
- opensuse-leap 16.0: postgresql17 17.11-160000.1.1 Β· PostgreSQL
- opensuse-leap 16.0: postgresql17 17.11-160000.1.1 Β· PostgreSQL
- opensuse-leap 16.0: postgresql17 17.11-160000.1.1 Β· PostgreSQL
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash-1017 on : a language model's rewrite of the original, under its terms