2 doc/src/sgml/ref/create_trigger.sgml
3 PostgreSQL documentation
6 <refentry id="SQL-CREATETRIGGER">
7 <indexterm zone="sql-createtrigger">
8 <primary>CREATE TRIGGER</primary>
12 <primary>transition tables</primary>
13 <seealso>ephemeral named relation</seealso>
17 <refentrytitle>CREATE TRIGGER</refentrytitle>
18 <manvolnum>7</manvolnum>
19 <refmiscinfo>SQL - Language Statements</refmiscinfo>
23 <refname>CREATE TRIGGER</refname>
24 <refpurpose>define a new trigger</refpurpose>
29 CREATE [ CONSTRAINT ] TRIGGER <replaceable class="PARAMETER">name</replaceable> { BEFORE | AFTER | INSTEAD OF } { <replaceable class="PARAMETER">event</replaceable> [ OR ... ] }
30 ON <replaceable class="PARAMETER">table_name</replaceable>
31 [ FROM <replaceable class="parameter">referenced_table_name</replaceable> ]
32 [ NOT DEFERRABLE | [ DEFERRABLE ] [ INITIALLY IMMEDIATE | INITIALLY DEFERRED ] ]
33 [ REFERENCING { { OLD | NEW } TABLE [ AS ] <replaceable class="PARAMETER">transition_relation_name</replaceable> } [ ... ] ]
34 [ FOR [ EACH ] { ROW | STATEMENT } ]
35 [ WHEN ( <replaceable class="parameter">condition</replaceable> ) ]
36 EXECUTE PROCEDURE <replaceable class="PARAMETER">function_name</replaceable> ( <replaceable class="PARAMETER">arguments</replaceable> )
38 <phrase>where <replaceable class="parameter">event</replaceable> can be one of:</phrase>
41 UPDATE [ OF <replaceable class="parameter">column_name</replaceable> [, ... ] ]
48 <title>Description</title>
51 <command>CREATE TRIGGER</command> creates a new trigger. The
52 trigger will be associated with the specified table, view, or foreign table
53 and will execute the specified
54 function <replaceable class="parameter">function_name</replaceable> when
59 The trigger can be specified to fire before the
60 operation is attempted on a row (before constraints are checked and
61 the <command>INSERT</command>, <command>UPDATE</command>, or
62 <command>DELETE</command> is attempted); or after the operation has
63 completed (after constraints are checked and the
64 <command>INSERT</command>, <command>UPDATE</command>, or
65 <command>DELETE</command> has completed); or instead of the operation
66 (in the case of inserts, updates or deletes on a view).
67 If the trigger fires before or instead of the event, the trigger can skip
68 the operation for the current row, or change the row being inserted (for
69 <command>INSERT</command> and <command>UPDATE</command> operations
70 only). If the trigger fires after the event, all changes, including
71 the effects of other triggers, are <quote>visible</quote>
76 A trigger that is marked <literal>FOR EACH ROW</literal> is called
77 once for every row that the operation modifies. For example, a
78 <command>DELETE</command> that affects 10 rows will cause any
79 <literal>ON DELETE</literal> triggers on the target relation to be
80 called 10 separate times, once for each deleted row. In contrast, a
81 trigger that is marked <literal>FOR EACH STATEMENT</literal> only
82 executes once for any given operation, regardless of how many rows
83 it modifies (in particular, an operation that modifies zero rows
84 will still result in the execution of any applicable <literal>FOR
85 EACH STATEMENT</literal> triggers). Note that with an
86 <command>INSERT</command> with an <literal>ON CONFLICT DO UPDATE</>
87 clause, both <command>INSERT</command> and
88 <command>UPDATE</command> statement level trigger will be fired.
92 Triggers that are specified to fire <literal>INSTEAD OF</> the trigger
93 event must be marked <literal>FOR EACH ROW</>, and can only be defined
94 on views. <literal>BEFORE</> and <literal>AFTER</> triggers on a view
95 must be marked as <literal>FOR EACH STATEMENT</>.
99 In addition, triggers may be defined to fire for
100 <command>TRUNCATE</command>, though only
101 <literal>FOR EACH STATEMENT</literal>.
105 The following table summarizes which types of triggers may be used on
106 tables, views, and foreign tables:
109 <informaltable id="supported-trigger-types">
115 <entry>Row-level</entry>
116 <entry>Statement-level</entry>
121 <entry align="center" morerows="1"><literal>BEFORE</></entry>
122 <entry align="center"><command>INSERT</>/<command>UPDATE</>/<command>DELETE</></entry>
123 <entry align="center">Tables and foreign tables</entry>
124 <entry align="center">Tables, views, and foreign tables</entry>
127 <entry align="center"><command>TRUNCATE</></entry>
128 <entry align="center">—</entry>
129 <entry align="center">Tables</entry>
132 <entry align="center" morerows="1"><literal>AFTER</></entry>
133 <entry align="center"><command>INSERT</>/<command>UPDATE</>/<command>DELETE</></entry>
134 <entry align="center">Tables and foreign tables</entry>
135 <entry align="center">Tables, views, and foreign tables</entry>
138 <entry align="center"><command>TRUNCATE</></entry>
139 <entry align="center">—</entry>
140 <entry align="center">Tables</entry>
143 <entry align="center" morerows="1"><literal>INSTEAD OF</></entry>
144 <entry align="center"><command>INSERT</>/<command>UPDATE</>/<command>DELETE</></entry>
145 <entry align="center">Views</entry>
146 <entry align="center">—</entry>
149 <entry align="center"><command>TRUNCATE</></entry>
150 <entry align="center">—</entry>
151 <entry align="center">—</entry>
158 Also, a trigger definition can specify a Boolean <literal>WHEN</>
159 condition, which will be tested to see whether the trigger should
160 be fired. In row-level triggers the <literal>WHEN</> condition can
161 examine the old and/or new values of columns of the row. Statement-level
162 triggers can also have <literal>WHEN</> conditions, although the feature
163 is not so useful for them since the condition cannot refer to any values
168 If multiple triggers of the same kind are defined for the same event,
169 they will be fired in alphabetical order by name.
173 When the <literal>CONSTRAINT</> option is specified, this command creates a
174 <firstterm>constraint trigger</>. This is the same as a regular trigger
175 except that the timing of the trigger firing can be adjusted using
176 <xref linkend="SQL-SET-CONSTRAINTS">.
177 Constraint triggers must be <literal>AFTER ROW</> triggers on tables. They
178 can be fired either at the end of the statement causing the triggering
179 event, or at the end of the containing transaction; in the latter case they
180 are said to be <firstterm>deferred</>. A pending deferred-trigger firing
181 can also be forced to happen immediately by using <command>SET
182 CONSTRAINTS</>. Constraint triggers are expected to raise an exception
183 when the constraints they implement are violated.
187 The <literal>REFERENCING</> option is only allowed for an <literal>AFTER</>
188 trigger which is not a constraint trigger. <literal>OLD TABLE</> may only
189 be specified once, and only on a trigger which can fire on
190 <literal>UPDATE</> or <literal>DELETE</>. <literal>NEW TABLE</> may only
191 be specified once, and only on a trigger which can fire on
192 <literal>UPDATE</> or <literal>INSERT</>.
196 <command>SELECT</command> does not modify any rows so you cannot
197 create <command>SELECT</command> triggers. Rules and views are more
198 appropriate in such cases.
202 Refer to <xref linkend="triggers"> for more information about triggers.
207 <title>Parameters</title>
211 <term><replaceable class="parameter">name</replaceable></term>
214 The name to give the new trigger. This must be distinct from
215 the name of any other trigger for the same table.
216 The name cannot be schema-qualified — the trigger inherits the
217 schema of its table. For a constraint trigger, this is also the name to
218 use when modifying the trigger's behavior using
219 <command>SET CONSTRAINTS</>.
225 <term><literal>BEFORE</literal></term>
226 <term><literal>AFTER</literal></term>
227 <term><literal>INSTEAD OF</literal></term>
230 Determines whether the function is called before, after, or instead of
231 the event. A constraint trigger can only be specified as
238 <term><replaceable class="parameter">event</replaceable></term>
241 One of <literal>INSERT</literal>, <literal>UPDATE</literal>,
242 <literal>DELETE</literal>, or <literal>TRUNCATE</literal>;
243 this specifies the event that will fire the trigger. Multiple
244 events can be specified using <literal>OR</literal>.
248 For <literal>UPDATE</literal> events, it is possible to
249 specify a list of columns using this syntax:
251 UPDATE OF <replaceable>column_name1</replaceable> [, <replaceable>column_name2</replaceable> ... ]
253 The trigger will only fire if at least one of the listed columns
254 is mentioned as a target of the <command>UPDATE</> command.
257 <para><literal>INSTEAD OF UPDATE</> events do not support lists of columns.
263 <term><replaceable class="parameter">table_name</replaceable></term>
266 The name (optionally schema-qualified) of the table, view, or foreign
267 table the trigger is for.
273 <term><replaceable class="PARAMETER">referenced_table_name</replaceable></term>
276 The (possibly schema-qualified) name of another table referenced by the
277 constraint. This option is used for foreign-key constraints and is not
278 recommended for general use. This can only be specified for
285 <term><literal>DEFERRABLE</literal></term>
286 <term><literal>NOT DEFERRABLE</literal></term>
287 <term><literal>INITIALLY IMMEDIATE</literal></term>
288 <term><literal>INITIALLY DEFERRED</literal></term>
291 The default timing of the trigger.
292 See the <xref linkend="SQL-CREATETABLE"> documentation for details of
293 these constraint options. This can only be specified for constraint
300 <term><literal>REFERENCING</literal></term>
303 This immediately precedes the declaration of one or two relations which
304 can be used to read the before and/or after images of all rows directly
305 affected by the triggering statement. An <literal>AFTER EACH ROW</>
306 trigger is allowed to use both these transition relation names and the
307 row names (<literal>OLD</> and <literal>NEW</>) which reference each
308 individual row for which the trigger fires.
314 <term><literal>OLD TABLE</literal></term>
315 <term><literal>NEW TABLE</literal></term>
318 This specifies whether the named relation contains the before or after
319 images for rows affected by the statement which fired the trigger.
325 <term><replaceable class="PARAMETER">transition_relation_name</replaceable></term>
328 The (unqualified) name to be used within the trigger for this relation.
334 <term><literal>FOR EACH ROW</literal></term>
335 <term><literal>FOR EACH STATEMENT</literal></term>
339 This specifies whether the trigger procedure should be fired
340 once for every row affected by the trigger event, or just once
341 per SQL statement. If neither is specified, <literal>FOR EACH
342 STATEMENT</literal> is the default. Constraint triggers can only
343 be specified <literal>FOR EACH ROW</>.
349 <term><replaceable class="parameter">condition</replaceable></term>
352 A Boolean expression that determines whether the trigger function
353 will actually be executed. If <literal>WHEN</> is specified, the
354 function will only be called if the <replaceable
355 class="parameter">condition</replaceable> returns <literal>true</>.
356 In <literal>FOR EACH ROW</literal> triggers, the <literal>WHEN</>
357 condition can refer to columns of the old and/or new row values
358 by writing <literal>OLD.<replaceable
359 class="parameter">column_name</replaceable></literal> or
360 <literal>NEW.<replaceable
361 class="parameter">column_name</replaceable></literal> respectively.
362 Of course, <literal>INSERT</> triggers cannot refer to <literal>OLD</>
363 and <literal>DELETE</> triggers cannot refer to <literal>NEW</>.
366 <para><literal>INSTEAD OF</> triggers do not support <literal>WHEN</>
371 Currently, <literal>WHEN</literal> expressions cannot contain
376 Note that for constraint triggers, evaluation of the <literal>WHEN</>
377 condition is not deferred, but occurs immediately after the row update
378 operation is performed. If the condition does not evaluate to true then
379 the trigger is not queued for deferred execution.
385 <term><replaceable class="parameter">function_name</replaceable></term>
388 A user-supplied function that is declared as taking no arguments
389 and returning type <literal>trigger</>, which is executed when
396 <term><replaceable class="parameter">arguments</replaceable></term>
399 An optional comma-separated list of arguments to be provided to
400 the function when the trigger is executed. The arguments are
401 literal string constants. Simple names and numeric constants
402 can be written here, too, but they will all be converted to
403 strings. Please check the description of the implementation
404 language of the trigger function to find out how these arguments
405 can be accessed within the function; it might be different from
406 normal function arguments.
413 <refsect1 id="SQL-CREATETRIGGER-notes">
417 To create a trigger on a table, the user must have the
418 <literal>TRIGGER</literal> privilege on the table. The user must
419 also have <literal>EXECUTE</literal> privilege on the trigger function.
423 Use <xref linkend="sql-droptrigger"> to remove a trigger.
427 A column-specific trigger (one defined using the <literal>UPDATE OF
428 <replaceable>column_name</replaceable></literal> syntax) will fire when any
429 of its columns are listed as targets in the <command>UPDATE</>
430 command's <literal>SET</> list. It is possible for a column's value
431 to change even when the trigger is not fired, because changes made to the
432 row's contents by <literal>BEFORE UPDATE</> triggers are not considered.
433 Conversely, a command such as <literal>UPDATE ... SET x = x ...</>
434 will fire a trigger on column <literal>x</>, even though the column's
435 value did not change.
439 In a <literal>BEFORE</> trigger, the <literal>WHEN</> condition is
440 evaluated just before the function is or would be executed, so using
441 <literal>WHEN</> is not materially different from testing the same
442 condition at the beginning of the trigger function. Note in particular
443 that the <literal>NEW</> row seen by the condition is the current value,
444 as possibly modified by earlier triggers. Also, a <literal>BEFORE</>
445 trigger's <literal>WHEN</> condition is not allowed to examine the
446 system columns of the <literal>NEW</> row (such as <literal>oid</>),
447 because those won't have been set yet.
451 In an <literal>AFTER</> trigger, the <literal>WHEN</> condition is
452 evaluated just after the row update occurs, and it determines whether an
453 event is queued to fire the trigger at the end of statement. So when an
454 <literal>AFTER</> trigger's <literal>WHEN</> condition does not return
455 true, it is not necessary to queue an event nor to re-fetch the row at end
456 of statement. This can result in significant speedups in statements that
457 modify many rows, if the trigger only needs to be fired for a few of the
462 In <productname>PostgreSQL</productname> versions before 7.3, it was
463 necessary to declare trigger functions as returning the placeholder
464 type <type>opaque</>, rather than <type>trigger</>. To support loading
465 of old dump files, <command>CREATE TRIGGER</> will accept a function
466 declared as returning <type>opaque</>, but it will issue a notice and
467 change the function's declared return type to <type>trigger</>.
471 <refsect1 id="SQL-CREATETRIGGER-examples">
472 <title>Examples</title>
475 Execute the function <function>check_account_update</> whenever
476 a row of the table <literal>accounts</> is about to be updated:
479 CREATE TRIGGER check_update
480 BEFORE UPDATE ON accounts
482 EXECUTE PROCEDURE check_account_update();
485 The same, but only execute the function if column <literal>balance</>
486 is specified as a target in the <command>UPDATE</> command:
489 CREATE TRIGGER check_update
490 BEFORE UPDATE OF balance ON accounts
492 EXECUTE PROCEDURE check_account_update();
495 This form only executes the function if column <literal>balance</>
496 has in fact changed value:
499 CREATE TRIGGER check_update
500 BEFORE UPDATE ON accounts
502 WHEN (OLD.balance IS DISTINCT FROM NEW.balance)
503 EXECUTE PROCEDURE check_account_update();
506 Call a function to log updates of <literal>accounts</>, but only if
510 CREATE TRIGGER log_update
511 AFTER UPDATE ON accounts
513 WHEN (OLD.* IS DISTINCT FROM NEW.*)
514 EXECUTE PROCEDURE log_account_update();
517 Execute the function <function>view_insert_row</> for each row to insert
518 rows into the tables underlying a view:
521 CREATE TRIGGER view_insert
522 INSTEAD OF INSERT ON my_view
524 EXECUTE PROCEDURE view_insert_row();
527 Execute the function <function>check_transfer_balances_to_zero</> for each
528 statement to confirm that the <literal>transfer</> rows offset to a net of
532 CREATE TRIGGER transfer_insert
533 AFTER INSERT ON transfer
534 REFERENCING NEW TABLE AS inserted
536 EXECUTE PROCEDURE check_transfer_balances_to_zero();
539 Execute the function <function>check_matching_pairs</> for each row to
540 confirm that changes are made to matching pairs at the same time (by the
544 CREATE TRIGGER paired_items_update
545 AFTER UPDATE ON paired_items
546 REFERENCING NEW TABLE AS newtab OLD TABLE AS oldtab
548 EXECUTE PROCEDURE check_matching_pairs();
553 <xref linkend="trigger-example"> contains a complete example of a trigger
554 function written in C.
558 <refsect1 id="SQL-CREATETRIGGER-compatibility">
559 <title>Compatibility</title>
562 It's not clear whether SQL/MED contemplates triggers on foreign tables.
563 Its <drop basic column definition> General Rules do mention the possibility
564 of a reference from a trigger column list. On the other hand, nothing
565 overrides the fact that CREATE TRIGGER only targets base tables. For now,
566 do not document the compatibility status of triggers on foreign tables.
570 The <command>CREATE TRIGGER</command> statement in
571 <productname>PostgreSQL</productname> implements a subset of the
572 <acronym>SQL</> standard. The following functionalities are currently
578 While transition tables for <literal>AFTER</> triggers are specified
579 using the <literal>REFERENCING</> clause in the standard way, the row
580 variables used in <literal>FOR EACH ROW</> triggers may not be
581 specified in <literal>REFERENCING</> clause. They are available in a
582 manner which is dependent on the language in which the trigger function
583 is written. Some languages effectively behave as though there is a
584 <literal>REFERENCING</> clause containing <literal>OLD ROW AS OLD NEW
590 <para><productname>PostgreSQL</productname> only allows the execution
591 of a user-defined function for the triggered action. The standard
592 allows the execution of a number of other SQL commands, such as
593 <command>CREATE TABLE</command>, as the triggered action. This
594 limitation is not hard to work around by creating a user-defined
595 function that executes the desired commands.
603 SQL specifies that multiple triggers should be fired in
604 time-of-creation order. <productname>PostgreSQL</productname> uses
605 name order, which was judged to be more convenient.
609 SQL specifies that <literal>BEFORE DELETE</literal> triggers on cascaded
610 deletes fire <emphasis>after</> the cascaded <literal>DELETE</> completes.
611 The <productname>PostgreSQL</productname> behavior is for <literal>BEFORE
612 DELETE</literal> to always fire before the delete action, even a cascading
613 one. This is considered more consistent. There is also nonstandard
614 behavior if <literal>BEFORE</literal> triggers modify rows or prevent
615 updates during an update that is caused by a referential action. This can
616 lead to constraint violations or stored data that does not honor the
617 referential constraint.
621 The ability to specify multiple actions for a single trigger using
622 <literal>OR</literal> is a <productname>PostgreSQL</> extension of
627 The ability to fire triggers for <command>TRUNCATE</command> is a
628 <productname>PostgreSQL</> extension of the SQL standard, as is the
629 ability to define statement-level triggers on views.
633 <command>CREATE CONSTRAINT TRIGGER</command> is a
634 <productname>PostgreSQL</productname> extension of the <acronym>SQL</>
641 <title>See Also</title>
643 <simplelist type="inline">
644 <member><xref linkend="sql-altertrigger"></member>
645 <member><xref linkend="sql-droptrigger"></member>
646 <member><xref linkend="sql-createfunction"></member>
647 <member><xref linkend="sql-set-constraints"></member>