]> granicus.if.org Git - postgresql/blob - doc/src/sgml/ref/create_trigger.sgml
Trim trailing whitespace
[postgresql] / doc / src / sgml / ref / create_trigger.sgml
1 <!--
2 doc/src/sgml/ref/create_trigger.sgml
3 PostgreSQL documentation
4 -->
5
6 <refentry id="SQL-CREATETRIGGER">
7  <indexterm zone="sql-createtrigger">
8   <primary>CREATE TRIGGER</primary>
9  </indexterm>
10
11  <indexterm>
12   <primary>transition tables</primary>
13   <seealso>ephemeral named relation</seealso>
14  </indexterm>
15
16  <refmeta>
17   <refentrytitle>CREATE TRIGGER</refentrytitle>
18   <manvolnum>7</manvolnum>
19   <refmiscinfo>SQL - Language Statements</refmiscinfo>
20  </refmeta>
21
22  <refnamediv>
23   <refname>CREATE TRIGGER</refname>
24   <refpurpose>define a new trigger</refpurpose>
25  </refnamediv>
26
27  <refsynopsisdiv>
28 <synopsis>
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> )
37
38 <phrase>where <replaceable class="parameter">event</replaceable> can be one of:</phrase>
39
40     INSERT
41     UPDATE [ OF <replaceable class="parameter">column_name</replaceable> [, ... ] ]
42     DELETE
43     TRUNCATE
44 </synopsis>
45  </refsynopsisdiv>
46
47  <refsect1>
48   <title>Description</title>
49
50   <para>
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
55    certain events occur.
56   </para>
57
58   <para>
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>
72    to the trigger.
73   </para>
74
75   <para>
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.
89   </para>
90
91   <para>
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</>.
96   </para>
97
98   <para>
99    In addition, triggers may be defined to fire for
100    <command>TRUNCATE</command>, though only
101    <literal>FOR EACH STATEMENT</literal>.
102   </para>
103
104   <para>
105    The following table summarizes which types of triggers may be used on
106    tables, views, and foreign tables:
107   </para>
108
109   <informaltable id="supported-trigger-types">
110    <tgroup cols="4">
111     <thead>
112      <row>
113       <entry>When</entry>
114       <entry>Event</entry>
115       <entry>Row-level</entry>
116       <entry>Statement-level</entry>
117      </row>
118     </thead>
119     <tbody>
120      <row>
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>
125      </row>
126      <row>
127       <entry align="center"><command>TRUNCATE</></entry>
128       <entry align="center">&mdash;</entry>
129       <entry align="center">Tables</entry>
130      </row>
131      <row>
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>
136      </row>
137      <row>
138       <entry align="center"><command>TRUNCATE</></entry>
139       <entry align="center">&mdash;</entry>
140       <entry align="center">Tables</entry>
141      </row>
142      <row>
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">&mdash;</entry>
147      </row>
148      <row>
149       <entry align="center"><command>TRUNCATE</></entry>
150       <entry align="center">&mdash;</entry>
151       <entry align="center">&mdash;</entry>
152      </row>
153     </tbody>
154    </tgroup>
155   </informaltable>
156
157   <para>
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
164    in the table.
165   </para>
166
167   <para>
168    If multiple triggers of the same kind are defined for the same event,
169    they will be fired in alphabetical order by name.
170   </para>
171
172   <para>
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.
184   </para>
185
186   <para>
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</>.
193   </para>
194
195   <para>
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.
199   </para>
200
201   <para>
202    Refer to <xref linkend="triggers"> for more information about triggers.
203   </para>
204  </refsect1>
205
206  <refsect1>
207   <title>Parameters</title>
208
209   <variablelist>
210    <varlistentry>
211     <term><replaceable class="parameter">name</replaceable></term>
212     <listitem>
213      <para>
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 &mdash; 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</>.
220      </para>
221     </listitem>
222    </varlistentry>
223
224    <varlistentry>
225     <term><literal>BEFORE</literal></term>
226     <term><literal>AFTER</literal></term>
227     <term><literal>INSTEAD OF</literal></term>
228     <listitem>
229      <para>
230       Determines whether the function is called before, after, or instead of
231       the event.  A constraint trigger can only be specified as
232       <literal>AFTER</>.
233      </para>
234     </listitem>
235    </varlistentry>
236
237    <varlistentry>
238     <term><replaceable class="parameter">event</replaceable></term>
239     <listitem>
240      <para>
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>.
245      </para>
246
247      <para>
248       For <literal>UPDATE</literal> events, it is possible to
249       specify a list of columns using this syntax:
250 <synopsis>
251 UPDATE OF <replaceable>column_name1</replaceable> [, <replaceable>column_name2</replaceable> ... ]
252 </synopsis>
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.
255      </para>
256
257      <para><literal>INSTEAD OF UPDATE</> events do not support lists of columns.
258      </para>
259     </listitem>
260    </varlistentry>
261
262    <varlistentry>
263     <term><replaceable class="parameter">table_name</replaceable></term>
264     <listitem>
265      <para>
266       The name (optionally schema-qualified) of the table, view, or foreign
267       table the trigger is for.
268      </para>
269     </listitem>
270    </varlistentry>
271
272    <varlistentry>
273     <term><replaceable class="PARAMETER">referenced_table_name</replaceable></term>
274     <listitem>
275      <para>
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
279       constraint triggers.
280      </para>
281     </listitem>
282    </varlistentry>
283
284    <varlistentry>
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>
289     <listitem>
290      <para>
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
294       triggers.
295      </para>
296     </listitem>
297    </varlistentry>
298
299    <varlistentry>
300     <term><literal>REFERENCING</literal></term>
301     <listitem>
302      <para>
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.
309      </para>
310     </listitem>
311    </varlistentry>
312
313    <varlistentry>
314     <term><literal>OLD TABLE</literal></term>
315     <term><literal>NEW TABLE</literal></term>
316     <listitem>
317      <para>
318       This specifies whether the named relation contains the before or after
319       images for rows affected by the statement which fired the trigger.
320      </para>
321     </listitem>
322    </varlistentry>
323
324    <varlistentry>
325     <term><replaceable class="PARAMETER">transition_relation_name</replaceable></term>
326     <listitem>
327      <para>
328       The (unqualified) name to be used within the trigger for this relation.
329      </para>
330     </listitem>
331    </varlistentry>
332
333    <varlistentry>
334     <term><literal>FOR EACH ROW</literal></term>
335     <term><literal>FOR EACH STATEMENT</literal></term>
336
337     <listitem>
338      <para>
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</>.
344      </para>
345     </listitem>
346    </varlistentry>
347
348    <varlistentry>
349     <term><replaceable class="parameter">condition</replaceable></term>
350     <listitem>
351      <para>
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</>.
364      </para>
365
366      <para><literal>INSTEAD OF</> triggers do not support <literal>WHEN</>
367       conditions.
368      </para>
369
370      <para>
371       Currently, <literal>WHEN</literal> expressions cannot contain
372       subqueries.
373      </para>
374
375      <para>
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.
380      </para>
381     </listitem>
382    </varlistentry>
383
384    <varlistentry>
385     <term><replaceable class="parameter">function_name</replaceable></term>
386     <listitem>
387      <para>
388       A user-supplied function that is declared as taking no arguments
389       and returning type <literal>trigger</>, which is executed when
390       the trigger fires.
391      </para>
392     </listitem>
393    </varlistentry>
394
395    <varlistentry>
396     <term><replaceable class="parameter">arguments</replaceable></term>
397     <listitem>
398      <para>
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.
407      </para>
408     </listitem>
409    </varlistentry>
410   </variablelist>
411  </refsect1>
412
413  <refsect1 id="SQL-CREATETRIGGER-notes">
414   <title>Notes</title>
415
416   <para>
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.
420   </para>
421
422   <para>
423    Use <xref linkend="sql-droptrigger"> to remove a trigger.
424   </para>
425
426   <para>
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.
436   </para>
437
438   <para>
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.
448   </para>
449
450   <para>
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
458    rows.
459   </para>
460
461   <para>
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</>.
468   </para>
469  </refsect1>
470
471  <refsect1 id="SQL-CREATETRIGGER-examples">
472   <title>Examples</title>
473
474   <para>
475    Execute the function <function>check_account_update</> whenever
476    a row of the table <literal>accounts</> is about to be updated:
477
478 <programlisting>
479 CREATE TRIGGER check_update
480     BEFORE UPDATE ON accounts
481     FOR EACH ROW
482     EXECUTE PROCEDURE check_account_update();
483 </programlisting>
484
485    The same, but only execute the function if column <literal>balance</>
486    is specified as a target in the <command>UPDATE</> command:
487
488 <programlisting>
489 CREATE TRIGGER check_update
490     BEFORE UPDATE OF balance ON accounts
491     FOR EACH ROW
492     EXECUTE PROCEDURE check_account_update();
493 </programlisting>
494
495    This form only executes the function if column <literal>balance</>
496    has in fact changed value:
497
498 <programlisting>
499 CREATE TRIGGER check_update
500     BEFORE UPDATE ON accounts
501     FOR EACH ROW
502     WHEN (OLD.balance IS DISTINCT FROM NEW.balance)
503     EXECUTE PROCEDURE check_account_update();
504 </programlisting>
505
506    Call a function to log updates of <literal>accounts</>, but only if
507    something changed:
508
509 <programlisting>
510 CREATE TRIGGER log_update
511     AFTER UPDATE ON accounts
512     FOR EACH ROW
513     WHEN (OLD.* IS DISTINCT FROM NEW.*)
514     EXECUTE PROCEDURE log_account_update();
515 </programlisting>
516
517    Execute the function <function>view_insert_row</> for each row to insert
518    rows into the tables underlying a view:
519
520 <programlisting>
521 CREATE TRIGGER view_insert
522     INSTEAD OF INSERT ON my_view
523     FOR EACH ROW
524     EXECUTE PROCEDURE view_insert_row();
525 </programlisting>
526
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
529    zero:
530
531 <programlisting>
532 CREATE TRIGGER transfer_insert
533     AFTER INSERT ON transfer
534     REFERENCING NEW TABLE AS inserted
535     FOR EACH STATEMENT
536     EXECUTE PROCEDURE check_transfer_balances_to_zero();
537 </programlisting>
538
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
541    same statement):
542
543 <programlisting>
544 CREATE TRIGGER paired_items_update
545     AFTER UPDATE ON paired_items
546     REFERENCING NEW TABLE AS newtab OLD TABLE AS oldtab
547     FOR EACH ROW
548     EXECUTE PROCEDURE check_matching_pairs();
549 </programlisting>
550   </para>
551
552   <para>
553    <xref linkend="trigger-example"> contains a complete example of a trigger
554    function written in C.
555   </para>
556  </refsect1>
557
558  <refsect1 id="SQL-CREATETRIGGER-compatibility">
559   <title>Compatibility</title>
560
561   <!--
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.
567   -->
568
569   <para>
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
573    missing:
574
575    <itemizedlist>
576     <listitem>
577      <para>
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
585       ROW AS NEW</>.
586      </para>
587     </listitem>
588
589     <listitem>
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.
596      </para>
597     </listitem>
598
599    </itemizedlist>
600   </para>
601
602   <para>
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.
606   </para>
607
608   <para>
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.
618   </para>
619
620   <para>
621    The ability to specify multiple actions for a single trigger using
622    <literal>OR</literal> is a <productname>PostgreSQL</> extension of
623    the SQL standard.
624   </para>
625
626   <para>
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.
630   </para>
631
632   <para>
633    <command>CREATE CONSTRAINT TRIGGER</command> is a
634    <productname>PostgreSQL</productname> extension of the <acronym>SQL</>
635    standard.
636   </para>
637
638  </refsect1>
639
640  <refsect1>
641   <title>See Also</title>
642
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>
648   </simplelist>
649  </refsect1>
650 </refentry>