CREATE_TRIGGER(7)
โจ CREATE_TRIGGER โจ
okay bestie, welcome to the CREATE_TRIGGER(7) page, straight out of the PostgreSQL 18.6 Documentation ๐ซถ this is the one that teaches you how to make a trigger โ a lil function that fires itself when stuff happens to your table. no cap.
๐ 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 ๐ธ
CREATE TRIGGER creates a new trigger. and CREATE OR REPLACE TRIGGER? it will either create a new trigger or replace an existing one โ iconic behaviour, honestly. the trigger gets associated with the table, view, or foreign table you name, and it will execute the function function_name you give it whenever certain operations happen on that table. it's giving "i was watching the whole time" energy ๐
So if you want to swap out the current definition of a trigger you already have, you use CREATE OR REPLACE TRIGGER and you specify the existing trigger's name and its parent table. and then all the other properties get replaced too. everything. not just the bits you wanted to change. periodt.
Now, the timing. a trigger can be set to fire:
- before the operation is even attempted on a row โ so before constraints get checked and before the
INSERT,UPDATE, orDELETEis attempted - after the operation has completed โ so after constraints get checked and after the
INSERT,UPDATE, orDELETEhas completed - instead of the operation โ and this one's specifically for inserts, updates, or deletes on a view
If the trigger fires before or instead of the event, it's allowed to skip the operation entirely for the current row, or it can change the row being inserted โ but changing the row only works for INSERT and UPDATE operations, that's the rule. and if the trigger fires after the event? then all the changes are โvisibleโ to the trigger, including the effects of <em>other</em> triggers. full picture, no secrets ๐
๐ฆ row-level vs statement-level ๐ฆ
A trigger marked FOR EACH ROW gets called once for every single row that the operation modifies. like, 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. ten whole calls. she's thorough ๐
In contrast, a trigger marked FOR EACH STATEMENT only executes once for any given operation, no matter how many rows it modifies. and yes, bestie, that includes the case where it modifies zero rows โ an operation that modifies zero rows will still result in the execution of any applicable FOR EACH STATEMENT triggers. zero rows, still firing. she showed up anyway ๐ญ
Triggers specified to fire INSTEAD OF the trigger event must be marked FOR EACH ROW, and they can only be defined on views. and BEFORE and AFTER triggers on a view must be marked as FOR EACH STATEMENT.
Also? triggers may be defined to fire for TRUNCATE, though only FOR EACH STATEMENT.
๐ the vibe check table (which triggers go where) ๐
The following table summarizes which types of triggers may be used on tables, views, and foreign tables โ i'm gonna break it down bullet-style so it's easy to read, no cap:
BEFOREINSERT/UPDATE/DELETE- row-level โ Tables and foreign tables
- statement-level โ Tables, views, and foreign tables
TRUNCATE- row-level โ โ
- statement-level โ Tables and foreign tables
AFTERINSERT/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 OFINSERT/UPDATE/DELETE- row-level โ Views
- statement-level โ โ
TRUNCATE- row-level โ โ
- statement-level โ โ
๐ง the WHEN condition ๐ง
A trigger definition can also specify a Boolean WHEN condition, which gets tested to see whether the trigger should be fired at all. like a little bouncer at the door ๐ชโจ
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, ngl, the feature is not so useful for them, since the condition can't refer to any values in the table. it's just vibes at that point.
๐ firing order & constraint triggers ๐
If multiple triggers of the same kind are defined for the same event, they will be fired in alphabetical order by name. so if you're naming your triggers, bestie, know that the alphabet is the DJ ๐ง
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 โ so, not foreign tables, sorry ๐ซ
They can be fired either at the end of the statement causing the triggering event, or at the end of the containing transaction; in that latter case they are said to be deferred. A pending deferred-trigger firing can also be forced to happen immediately by using SET CONSTRAINTS. And constraint triggers are expected to raise an exception when the constraints they implement are violated. that's literally their whole job.
๐ transition relations (the REFERENCING option) ๐
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. main character energy for your whole statement ๐
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 TABLEmay only be specified once, and only for a trigger that can fire onUPDATEorDELETE; it creates a transition relation containing the before-images of all rows updated or deleted by the statement.- Similarly,
NEW TABLEmay only be specified once, and only for a trigger that can fire onUPDATEorINSERT; it creates a transition relation containing the after-images of all rows updated or inserted by the statement.
๐ one last lil thing ๐
SELECT does not modify any rows, so you cannot create SELECT triggers. i know. i know. ๐ญ Rules and views may provide workable solutions to problems that seem to need SELECT triggers though, so don't lose hope.
Refer to Chapter 37 for more information about triggers. ๐โจ
๐ PARAMETERS ๐
okay so this is the part where we go through every single lil ingredient you can drop into a CREATE TRIGGER, one by one. no skipping, we're doing all of them ๐
name
the name you're giving your brand-new trigger โจ it must be distinct from the name of any other trigger on the same table, no duplicates allowed. also โ plot twist โ it cannot be schema-qualified, because the trigger just inherits the schema of its table. and if it's a constraint trigger? then this is also the name you use when you wanna change the trigger's behavior with SET CONSTRAINTS. multitasking icon ๐
BEFORE / AFTER / INSTEAD OF
this is the vibe check on when your function runs โ before the event, after the event, or instead of it. and heads up: a constraint trigger can only be specified as AFTER. that's just the rules bestie ๐คท
event
one of INSERT, UPDATE, DELETE, or TRUNCATE. this is literally the thing that fires the trigger, the whole point ๐ฅ you can stack multiple events with ORโฆ except when transition relations are being requested. not then. nope.
for UPDATE events you can also get specific about columns, using this syntax:
UPDATE OF column_name1 [, column_name2 ... ]
and the trigger only fires 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 is the target of the UPDATE. sneaky but correct ๐ฆ
INSTEAD OF UPDATE events do not allow a list of columns. and you can't specify a column list when requesting transition relations either. that's just how it is.
table_name
the name (optionally schema-qualified) of the table, view, or foreign table the trigger is for. yes, foreign tables count too ๐
referenced_table_name
the (possibly schema-qualified) name of another table that the constraint references. this one's for foreign-key constraints and it is not recommended for general use. it can only be specified for constraint triggers. iykyk ๐
DEFERRABLE / NOT DEFERRABLE / INITIALLY IMMEDIATE / INITIALLY DEFERRED
the default timing of the trigger. for the full rundown on these constraint options, go read the CREATE TABLE (CREATE_TABLE(7)) docs. and again โ only for constraint triggers ๐ซ
REFERENCING
this keyword sits immediately before you declare one or two relation names that give you access to the transition relations of the triggering statement. it's giving โจ behind-the-scenes footage โจ
OLD TABLE / NEW TABLE
this clause says whether the following relation name is for the before-image transition relation or the after-image transition relation. past you, or future you ๐ธ
transition_relation_name
the (unqualified) name to be used within the trigger for this transition relation. keep it unqualified, bestie.
FOR EACH ROW / FOR EACH STATEMENT
does your trigger function fire once for every row affected by the event, or just once per SQL statement? if you don't say anything, FOR EACH STATEMENT is the default. and constraint triggers can only ever be FOR EACH ROW. periodt ๐
condition
a Boolean expression that decides 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 obviously INSERT triggers can't refer to OLD, and DELETE triggers can't refer to NEW. like, there's nothing there to look at ๐ญ
INSTEAD OFtriggers do not supportWHENconditions.
currently, WHEN expressions cannot contain subqueries.
and real talk 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, the trigger just isn't queued for deferred execution. no queue, no problem ๐
function_name
a user-supplied function, declared as taking no arguments and returning type trigger, which gets executed 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. the keyword PROCEDURE here is historical and deprecated. don't use it, it's so 2009 ๐
arguments
an optional comma-separated list of arguments to hand to the function when the trigger executes. these are literal string constants. simple names and numeric constants can be written here too, but they'll all be converted to strings. to find out how these arguments can be accessed inside the function, check the description of the implementation language of the trigger function โ it might be different from normal function arguments. plot twist energy ๐
โจ NOTES โจ
okay, housekeeping time. ๐งน
to create or replace a trigger on a table, you need the TRIGGER privilege on that table. and you also need EXECUTE privilege on the trigger function. two keys, both required ๐
use DROP TRIGGER to remove a trigger. bye bestie ๐
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 used 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 you define 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 yes, it's possible for a column's value to change even when the trigger does not fire, 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. confusing? yes. that's just how it is ๐
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 especially that the NEW row the condition sees 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. sorry, not yet ๐ซ
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 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. this can result in significant speedups in statements that modify many rows โ if the trigger only needs to fire for a few of them. efficiency queen ๐
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 will see only the inserted rows, while an UPDATE trigger will see only the updated rows. everybody sees 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 (and note: such actions are never deferred). relevant triggers on the affected table will fire, which 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 โ 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. no double dipping ๐
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, then 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 fire. follow the chain ๐
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 has been 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 ๐
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. just how it is, bestie.
currently, the OR REPLACE option is not supported for constraint triggers.
replacing an existing trigger within a transaction that has already performed updating actions on the trigger's table is not recommended. trigger firing decisions, or portions of firing decisions, that have already been made will not be reconsidered โ so the effects could be surprising. consider yourself warned ๐ณ
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 ๐
๐ EXAMPLES ๐
okay bestie, this is the part where it all comes together. real triggers, real tables, let's GO โจ
Say you want to run the function check_account_update every single time a row in the accounts table is about to be updated. Like, right before. Anticipating it. Main character energy:
CREATE TRIGGER check_update
BEFORE UPDATE ON accounts
FOR EACH ROW
EXECUTE FUNCTION check_account_update();
Now bestie, what if you're picky and you only want that function to run when the column balance is actually named as a target in the UPDATE command? Same trigger, tiny glow-up:
CREATE OR REPLACE TRIGGER check_update
BEFORE UPDATE OF balance ON accounts
FOR EACH ROW
EXECUTE FUNCTION check_account_update();
And this form? This one is even more selective โ it only fires if the column balance has actually changed value. Not just been mentioned, actually changed. the way that works is so satisfying:
CREATE TRIGGER check_update
BEFORE UPDATE ON accounts
FOR EACH ROW
WHEN (OLD.balance IS DISTINCT FROM NEW.balance)
EXECUTE FUNCTION check_account_update();
Want to log updates to accounts, but only when something actually changed? Because logging no-op updates is giving wasteful, and we don't do that here:
CREATE TRIGGER log_update
AFTER UPDATE ON accounts
FOR EACH ROW
WHEN (OLD.* IS DISTINCT FROM NEW.*)
EXECUTE FUNCTION log_account_update();
Now for views ๐ฆ โ you can run the function view_insert_row for each row to insert rows into the tables underneath a view:
CREATE TRIGGER view_insert
INSTEAD OF INSERT ON my_view
FOR EACH ROW
EXECUTE FUNCTION view_insert_row();
Statement-level check incoming ๐
run the function check_transfer_balances_to_zero once per statement to confirm that the transfer rows offset to a net of zero:
CREATE TRIGGER transfer_insert
AFTER INSERT ON transfer
REFERENCING NEW TABLE AS inserted
FOR EACH STATEMENT
EXECUTE FUNCTION check_transfer_balances_to_zero();
And last one, bestie, this one is lowkey iconic โ run the function check_matching_pairs for each row to confirm that changes get made to matching pairs at the same time, meaning by the same statement:
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();
psst โ Section 37.4 has a whole complete example of a trigger function written in C, if you wanna go feral with it ๐
๐ COMPATIBILITY ๐
okay so real talk: the CREATE TRIGGER statement in PostgreSQL implements a subset of the SQL standard. It's not the whole thing, and honestly? we're at peace with that. Here's what's currently missing:
- 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. - 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. 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 specifies that multiple triggers should be fired in time-of-creation order. PostgreSQL uses name order instead, which was judged to be more convenient. we stand by it โจ
SQL specifies that BEFORE DELETE triggers on cascaded deletes fire after the cascaded DELETE completes. The PostgreSQL behavior is for BEFORE DELETE to always fire before the delete action, even a cascading one. This is considered more consistent. ๐
โ ๏ธ heads up bestie, there's also nonstandard behavior if BEFORE triggers modify rows or prevent updates during an update that is caused by a referential action. This can lead to constraint violations or stored data that does not honor the referential constraint. like, actually be careful here 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. periodt. ๐
๐ซถ SEE ALSO ๐ซถ
ALTER TRIGGER(ALTER_TRIGGER(7))DROP TRIGGER(DROP_TRIGGER(7))CREATE FUNCTION(CREATE_FUNCTION(7))SET CONSTRAINTS(SET_CONSTRAINTS(7))
go read those next, bestie, they're literally the rest of the story ๐ธ
and that's a wrap on CREATE TRIGGER(7), brought to you by PostgreSQL 18.6, dated 2026 โ courtesy of the PostgreSQL crew, who ate and left no crumbs ๐๐
โจ
๐ฆ where this page comes from
- alpine 3.23: postgresql18-doc 18.6-r0 ยท PostgreSQL
- alpine 3.24: postgresql18-doc 18.6-r0 ยท PostgreSQL
- arch rolling: postgresql 18.6-4 ยท PostgreSQL
- fedora 43: postgresql 18.6-1.fc43 ยท PostgreSQL
- fedora 43: postgresql 18.6-1.fc43 ยท PostgreSQL
- fedora 44: postgresql 18.6-1.fc44 ยท PostgreSQL
- fedora 44: postgresql 18.6-1.fc44 ยท PostgreSQL
- nixos 26.05: postgresql 18.6
- ubuntu resolute: postgresql-client-18 18.6-0ubuntu0.26.04.1 ยท PostgreSQL
- ubuntu stonking: postgresql-client-18 18.6-3build2 ยท PostgreSQL
- ๐ girlified by deepseek-ai/DeepSeek-V4.1-Flash on : a language model's rewrite of the original, under its terms