]> begriffs open source - ai-pg/blob - full-docs/html/trigger-definition.html
Include links to all subsection html pages, with shorter paths too
[ai-pg] / full-docs / html / trigger-definition.html
1 <?xml version="1.0" encoding="UTF-8" standalone="no"?>
2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /><title>37.1. Overview of Trigger Behavior</title><link rel="stylesheet" type="text/css" href="stylesheet.css" /><link rev="made" href="pgsql-docs@lists.postgresql.org" /><meta name="generator" content="DocBook XSL Stylesheets Vsnapshot" /><link rel="prev" href="triggers.html" title="Chapter 37. Triggers" /><link rel="next" href="trigger-datachanges.html" title="37.2. Visibility of Data Changes" /></head><body id="docContent" class="container-fluid col-10"><div class="navheader"><table width="100%" summary="Navigation header"><tr><th colspan="5" align="center">37.1. Overview of Trigger Behavior</th></tr><tr><td width="10%" align="left"><a accesskey="p" href="triggers.html" title="Chapter 37. Triggers">Prev</a> </td><td width="10%" align="left"><a accesskey="u" href="triggers.html" title="Chapter 37. Triggers">Up</a></td><th width="60%" align="center">Chapter 37. Triggers</th><td width="10%" align="right"><a accesskey="h" href="index.html" title="PostgreSQL 18.0 Documentation">Home</a></td><td width="10%" align="right"> <a accesskey="n" href="trigger-datachanges.html" title="37.2. Visibility of Data Changes">Next</a></td></tr></table><hr /></div><div class="sect1" id="TRIGGER-DEFINITION"><div class="titlepage"><div><div><h2 class="title" style="clear: both">37.1. Overview of Trigger Behavior <a href="#TRIGGER-DEFINITION" class="id_link">#</a></h2></div></div></div><p>
3     A trigger is a specification that the database should automatically
4     execute a particular function whenever a certain type of operation is
5     performed.  Triggers can be attached to tables (partitioned or not),
6     views, and foreign tables.
7   </p><p>
8     On tables and foreign tables, triggers can be defined to execute either
9     before or after any <code class="command">INSERT</code>, <code class="command">UPDATE</code>,
10     or <code class="command">DELETE</code> operation, either once per modified row,
11     or once per <acronym class="acronym">SQL</acronym> statement.
12     <code class="command">UPDATE</code> triggers can moreover be set to fire only if
13     certain columns are mentioned in the <code class="literal">SET</code> clause of
14     the <code class="command">UPDATE</code> statement.  Triggers can also fire
15     for <code class="command">TRUNCATE</code> statements.  If a trigger event occurs,
16     the trigger's function is called at the appropriate time to handle the
17     event.
18    </p><p>
19     On views, triggers can be defined to execute instead of
20     <code class="command">INSERT</code>, <code class="command">UPDATE</code>, or
21     <code class="command">DELETE</code> operations.
22     Such <code class="literal">INSTEAD OF</code> triggers
23     are fired once for each row that needs to be modified in the view.
24     It is the responsibility of the
25     trigger's function to perform the necessary modifications to the view's
26     underlying base table(s) and, where appropriate, return the modified
27     row as it will appear in the view.  Triggers on views can also be defined
28     to execute once per <acronym class="acronym">SQL</acronym> statement, before or after
29     <code class="command">INSERT</code>, <code class="command">UPDATE</code>, or
30     <code class="command">DELETE</code> operations.
31     However, such triggers are fired only if there is also
32     an <code class="literal">INSTEAD OF</code> trigger on the view.  Otherwise,
33     any statement targeting the view must be rewritten into a statement
34     affecting its underlying base table(s), and then the triggers
35     that will be fired are the ones attached to the base table(s).
36    </p><p>
37     The trigger function must be defined before the trigger itself can be
38     created.  The trigger function must be declared as a
39     function taking no arguments and returning type <code class="literal">trigger</code>.
40     (The trigger function receives its input through a specially-passed
41     <code class="structname">TriggerData</code> structure, not in the form of ordinary function
42     arguments.)
43    </p><p>
44     Once a suitable trigger function has been created, the trigger is
45     established with
46     <a class="xref" href="sql-createtrigger.html" title="CREATE TRIGGER"><span class="refentrytitle">CREATE TRIGGER</span></a>.
47     The same trigger function can be used for multiple triggers.
48    </p><p>
49     <span class="productname">PostgreSQL</span> offers both <em class="firstterm">per-row</em>
50     triggers and <em class="firstterm">per-statement</em> triggers.  With a per-row
51     trigger, the trigger function
52     is invoked once for each row that is affected by the statement
53     that fired the trigger. In contrast, a per-statement trigger is
54     invoked only once when an appropriate statement is executed,
55     regardless of the number of rows affected by that statement. In
56     particular, a statement that affects zero rows will still result
57     in the execution of any applicable per-statement triggers. These
58     two types of triggers are sometimes called <em class="firstterm">row-level</em>
59     triggers and <em class="firstterm">statement-level</em> triggers,
60     respectively. Triggers on <code class="command">TRUNCATE</code> may only be
61     defined at statement level, not per-row.
62    </p><p>
63     Triggers are also classified according to whether they fire
64     <em class="firstterm">before</em>, <em class="firstterm">after</em>, or
65     <em class="firstterm">instead of</em> the operation. These are referred to
66     as <code class="literal">BEFORE</code> triggers, <code class="literal">AFTER</code> triggers, and
67     <code class="literal">INSTEAD OF</code> triggers respectively.
68     Statement-level <code class="literal">BEFORE</code> triggers naturally fire before the
69     statement starts to do anything, while statement-level <code class="literal">AFTER</code>
70     triggers fire at the very end of the statement.  These types of
71     triggers may be defined on tables, views, or foreign tables.  Row-level
72     <code class="literal">BEFORE</code> triggers fire immediately before a particular row is
73     operated on, while row-level <code class="literal">AFTER</code> triggers fire at the end of
74     the statement (but before any statement-level <code class="literal">AFTER</code> triggers).
75     These types of triggers may only be defined on tables and
76     foreign tables, not views.
77     <code class="literal">INSTEAD OF</code> triggers may only be
78     defined on views, and only at row level; they fire immediately as each
79     row in the view is identified as needing to be operated on.
80    </p><p>
81     The execution of an <code class="literal">AFTER</code> trigger can be deferred
82     to the end of the transaction, rather than the end of the statement,
83     if it was defined as a <em class="firstterm">constraint trigger</em>.
84     In all cases, a trigger is executed as part of the same transaction as
85     the statement that triggered it, so if either the statement or the
86     trigger causes an error, the effects of both will be rolled back.
87     Also, the trigger will always run as the role that queued the trigger
88     event, unless the trigger function is marked as <code class="literal">SECURITY
89     DEFINER</code>, in which case it will run as the function owner.
90    </p><p>
91     If an <code class="command">INSERT</code> contains an <code class="literal">ON CONFLICT
92     DO UPDATE</code> clause, it is possible for row-level
93     <code class="literal">BEFORE</code> <code class="command">INSERT</code> and then
94     <code class="literal">BEFORE</code> <code class="command">UPDATE</code> triggers
95     to be executed on triggered rows.  Such interactions can be
96     complex if the triggers are not idempotent because change made by
97     <code class="literal">BEFORE</code> <code class="command">INSERT</code> triggers will be
98     seen by <code class="literal">BEFORE</code> <code class="command">UPDATE</code> triggers,
99     including changes to <code class="varname">EXCLUDED</code> columns.
100    </p><p>
101     Note that statement-level
102     <code class="command">UPDATE</code> triggers are executed when <code class="literal">ON
103     CONFLICT DO UPDATE</code> is specified, regardless of whether or not
104     any rows were affected by the <code class="command">UPDATE</code> (and
105     regardless of whether the alternative <code class="command">UPDATE</code>
106     path was ever taken).  An <code class="command">INSERT</code> with an
107     <code class="literal">ON CONFLICT DO UPDATE</code> clause will execute
108     statement-level <code class="literal">BEFORE</code> <code class="command">INSERT</code>
109     triggers first, then statement-level <code class="literal">BEFORE</code>
110     <code class="command">UPDATE</code> triggers, followed by statement-level
111     <code class="literal">AFTER</code> <code class="command">UPDATE</code> triggers and finally
112     statement-level <code class="literal">AFTER</code> <code class="command">INSERT</code>
113     triggers.
114    </p><p>
115     A statement that targets a parent table in an inheritance or partitioning
116     hierarchy does not cause the statement-level triggers of affected child
117     tables to be fired; only the parent table's statement-level triggers are
118     fired.  However, row-level triggers of any affected child tables will be
119     fired.
120    </p><p>
121     If an <code class="command">UPDATE</code> on a partitioned table causes a row to move
122     to another partition, it will be performed as a <code class="command">DELETE</code>
123     from the original partition followed by an <code class="command">INSERT</code> into
124     the new partition. In this case, all row-level <code class="literal">BEFORE</code>
125     <code class="command">UPDATE</code> triggers and all row-level
126     <code class="literal">BEFORE</code> <code class="command">DELETE</code> triggers are fired on
127     the original partition. Then all row-level <code class="literal">BEFORE</code>
128     <code class="command">INSERT</code> triggers are fired on the destination partition.
129     The possibility of surprising outcomes should be considered when all these
130     triggers affect the row being moved. As far as <code class="literal">AFTER ROW</code>
131     triggers are concerned, <code class="literal">AFTER</code> <code class="command">DELETE</code>
132     and <code class="literal">AFTER</code> <code class="command">INSERT</code> triggers are
133     applied; but <code class="literal">AFTER</code> <code class="command">UPDATE</code> triggers
134     are not applied because the <code class="command">UPDATE</code> has been converted to
135     a <code class="command">DELETE</code> and an <code class="command">INSERT</code>. As far as
136     statement-level triggers are concerned, none of the
137     <code class="command">DELETE</code> or <code class="command">INSERT</code> triggers are fired,
138     even if row movement occurs; only the <code class="command">UPDATE</code> triggers
139     defined on the target table used in the <code class="command">UPDATE</code> statement
140     will be fired.
141    </p><p>
142     No separate triggers are defined for <code class="command">MERGE</code>. Instead,
143     statement-level or row-level <code class="command">UPDATE</code>,
144     <code class="command">DELETE</code>, and <code class="command">INSERT</code> triggers are fired
145     depending on (for statement-level triggers) what actions are specified in
146     the <code class="command">MERGE</code> query and (for row-level triggers) what
147     actions are performed.
148    </p><p>
149     While running a <code class="command">MERGE</code> command, statement-level
150     <code class="literal">BEFORE</code> and <code class="literal">AFTER</code> triggers are
151     fired for events specified in the actions of the <code class="command">MERGE</code>
152     command, irrespective of whether or not the action is ultimately performed.
153     This is the same as an <code class="command">UPDATE</code> statement that updates
154     no rows, yet statement-level triggers are fired.
155     The row-level triggers are fired only when a row is actually updated,
156     inserted or deleted. So it's perfectly legal that while statement-level
157     triggers are fired for certain types of action, no row-level triggers
158     are fired for the same kind of action.
159    </p><p>
160     Trigger functions invoked by per-statement triggers should always
161     return <code class="symbol">NULL</code>. Trigger functions invoked by per-row
162     triggers can return a table row (a value of
163     type <code class="structname">HeapTuple</code>) to the calling executor,
164     if they choose.  A row-level trigger fired before an operation has
165     the following choices:
166
167     </p><div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem"><p>
168        It can return <code class="symbol">NULL</code> to skip the operation for the
169        current row. This instructs the executor to not perform the
170        row-level operation that invoked the trigger (the insertion,
171        modification, or deletion of a particular table row).
172       </p></li><li class="listitem"><p>
173        For row-level <code class="command">INSERT</code>
174        and <code class="command">UPDATE</code> triggers only, the returned row
175        becomes the row that will be inserted or will replace the row
176        being updated.  This allows the trigger function to modify the
177        row being inserted or updated.
178       </p></li></ul></div><p>
179
180     A row-level <code class="literal">BEFORE</code> trigger that does not intend to cause
181     either of these behaviors must be careful to return as its result the same
182     row that was passed in (that is, the <code class="varname">NEW</code> row
183     for <code class="command">INSERT</code> and <code class="command">UPDATE</code>
184     triggers, the <code class="varname">OLD</code> row for
185     <code class="command">DELETE</code> triggers).
186    </p><p>
187     A row-level <code class="literal">INSTEAD OF</code> trigger should either return
188     <code class="symbol">NULL</code> to indicate that it did not modify any data from
189     the view's underlying base tables, or it should return the view
190     row that was passed in (the <code class="varname">NEW</code> row
191     for <code class="command">INSERT</code> and <code class="command">UPDATE</code>
192     operations, or the <code class="varname">OLD</code> row for
193     <code class="command">DELETE</code> operations). A nonnull return value is
194     used to signal that the trigger performed the necessary data
195     modifications in the view.  This will cause the count of the number
196     of rows affected by the command to be incremented. For
197     <code class="command">INSERT</code> and <code class="command">UPDATE</code> operations only, the trigger
198     may modify the <code class="varname">NEW</code> row before returning it.  This will
199     change the data returned by
200     <code class="command">INSERT RETURNING</code> or <code class="command">UPDATE RETURNING</code>,
201     and is useful when the view will not show exactly the same data
202     that was provided.
203    </p><p>
204     The return value is ignored for row-level triggers fired after an
205     operation, and so they can return <code class="symbol">NULL</code>.
206    </p><p>
207     Some considerations apply for generated
208     columns.<a id="id-1.8.4.5.19.1" class="indexterm"></a>  Stored generated columns are computed after
209     <code class="literal">BEFORE</code> triggers and before <code class="literal">AFTER</code>
210     triggers.  Therefore, the generated value can be inspected in
211     <code class="literal">AFTER</code> triggers.  In <code class="literal">BEFORE</code> triggers,
212     the <code class="literal">OLD</code> row contains the old generated value, as one
213     would expect, but the <code class="literal">NEW</code> row does not yet contain the
214     new generated value and should not be accessed.  In the C language
215     interface, the content of the column is undefined at this point; a
216     higher-level programming language should prevent access to a stored
217     generated column in the <code class="literal">NEW</code> row in a
218     <code class="literal">BEFORE</code> trigger.  Changes to the value of a generated
219     column in a <code class="literal">BEFORE</code> trigger are ignored and will be
220     overwritten.
221     Virtual generated columns are never computed when triggers fire.  In the C
222     language interface, their content is undefined in a trigger function.
223     Higher-level programming languages should prevent access to virtual
224     generated columns in triggers.
225    </p><p>
226     If more than one trigger is defined for the same event on the same
227     relation, the triggers will be fired in alphabetical order by
228     trigger name.  In the case of <code class="literal">BEFORE</code> and
229     <code class="literal">INSTEAD OF</code> triggers, the possibly-modified row returned by
230     each trigger becomes the input to the next trigger.  If any
231     <code class="literal">BEFORE</code> or <code class="literal">INSTEAD OF</code> trigger returns
232     <code class="symbol">NULL</code>, the operation is abandoned for that row and subsequent
233     triggers are not fired (for that row).
234    </p><p>
235     A trigger definition can also specify a Boolean <code class="literal">WHEN</code>
236     condition, which will be tested to see whether the trigger should
237     be fired.  In row-level triggers the <code class="literal">WHEN</code> condition can
238     examine the old and/or new values of columns of the row.  (Statement-level
239     triggers can also have <code class="literal">WHEN</code> conditions, although the feature
240     is not so useful for them.)  In a <code class="literal">BEFORE</code> trigger, the
241     <code class="literal">WHEN</code>
242     condition is evaluated just before the function is or would be executed,
243     so using <code class="literal">WHEN</code> is not materially different from testing the
244     same condition at the beginning of the trigger function.  However, in
245     an <code class="literal">AFTER</code> trigger, the <code class="literal">WHEN</code> condition is evaluated
246     just after the row update occurs, and it determines whether an event is
247     queued to fire the trigger at the end of statement.  So when an
248     <code class="literal">AFTER</code> trigger's
249     <code class="literal">WHEN</code> condition does not return true, it is not necessary
250     to queue an event nor to re-fetch the row at end of statement.  This
251     can result in significant speedups in statements that modify many
252     rows, if the trigger only needs to be fired for a few of the rows.
253     <code class="literal">INSTEAD OF</code> triggers do not support
254     <code class="literal">WHEN</code> conditions.
255    </p><p>
256     Typically, row-level <code class="literal">BEFORE</code> triggers are used for checking or
257     modifying the data that will be inserted or updated.  For example,
258     a <code class="literal">BEFORE</code> trigger might be used to insert the current time into a
259     <code class="type">timestamp</code> column, or to check that two elements of the row are
260     consistent. Row-level <code class="literal">AFTER</code> triggers are most sensibly
261     used to propagate the updates to other tables, or make consistency
262     checks against other tables.  The reason for this division of labor is
263     that an <code class="literal">AFTER</code> trigger can be certain it is seeing the final
264     value of the row, while a <code class="literal">BEFORE</code> trigger cannot; there might
265     be other <code class="literal">BEFORE</code> triggers firing after it.  If you have no
266     specific reason to make a trigger <code class="literal">BEFORE</code> or
267     <code class="literal">AFTER</code>, the <code class="literal">BEFORE</code> case is more efficient, since
268     the information about
269     the operation doesn't have to be saved until end of statement.
270    </p><p>
271     If a trigger function executes SQL commands then these
272     commands might fire triggers again. This is known as cascading
273     triggers.  There is no direct limitation on the number of cascade
274     levels.  It is possible for cascades to cause a recursive invocation
275     of the same trigger; for example, an <code class="command">INSERT</code>
276     trigger might execute a command that inserts an additional row
277     into the same table, causing the <code class="command">INSERT</code> trigger
278     to be fired again.  It is the trigger programmer's responsibility
279     to avoid infinite recursion in such scenarios.
280    </p><p>
281     If a foreign key constraint specifies referential actions (that
282     is, cascading updates or deletes), those actions are performed via
283     ordinary SQL <code class="command">UPDATE</code> or <code class="command">DELETE</code>
284     commands on the referencing table.
285     In particular, any triggers that exist on the referencing table
286     will be fired for those changes.  If such a trigger modifies or
287     blocks the effect of one of these commands, the end result could
288     be to break referential integrity.  It is the trigger programmer's
289     responsibility to avoid that.
290    </p><p>
291     <a id="id-1.8.4.5.25.1" class="indexterm"></a>
292     When a trigger is being defined, arguments can be specified for
293     it. The purpose of including arguments in the
294     trigger definition is to allow different triggers with similar
295     requirements to call the same function.  As an example, there
296     could be a generalized trigger function that takes as its
297     arguments two column names and puts the current user in one and
298     the current time stamp in the other.  Properly written, this
299     trigger function would be independent of the specific table it is
300     triggering on.  So the same function could be used for
301     <code class="command">INSERT</code> events on any table with suitable
302     columns, to automatically track creation of records in a
303     transaction table for example. It could also be used to track
304     last-update events if defined as an <code class="command">UPDATE</code>
305     trigger.
306    </p><p>
307     Each programming language that supports triggers has its own method
308     for making the trigger input data available to the trigger function.
309     This input data includes the type of trigger event (e.g.,
310     <code class="command">INSERT</code> or <code class="command">UPDATE</code>) as well as any
311     arguments that were listed in <code class="command">CREATE TRIGGER</code>.
312     For a row-level trigger, the input data also includes the
313     <code class="varname">NEW</code> row for <code class="command">INSERT</code> and
314     <code class="command">UPDATE</code> triggers, and/or the <code class="varname">OLD</code> row
315     for <code class="command">UPDATE</code> and <code class="command">DELETE</code> triggers.
316    </p><p>
317     By default, statement-level triggers do not have any way to examine the
318     individual row(s) modified by the statement.  But an <code class="literal">AFTER
319     STATEMENT</code> trigger can request that <em class="firstterm">transition tables</em>
320     be created to make the sets of affected rows available to the trigger.
321     <code class="literal">AFTER ROW</code> triggers can also request transition tables, so
322     that they can see the total changes in the table as well as the change in
323     the individual row they are currently being fired for.  The method for
324     examining the transition tables again depends on the programming language
325     that is being used, but the typical approach is to make the transition
326     tables act like read-only temporary tables that can be accessed by SQL
327     commands issued within the trigger function.
328    </p></div><div class="navfooter"><hr /><table width="100%" summary="Navigation footer"><tr><td width="40%" align="left"><a accesskey="p" href="triggers.html" title="Chapter 37. Triggers">Prev</a> </td><td width="20%" align="center"><a accesskey="u" href="triggers.html" title="Chapter 37. Triggers">Up</a></td><td width="40%" align="right"> <a accesskey="n" href="trigger-datachanges.html" title="37.2. Visibility of Data Changes">Next</a></td></tr><tr><td width="40%" align="left" valign="top">Chapter 37. Triggers </td><td width="20%" align="center"><a accesskey="h" href="index.html" title="PostgreSQL 18.0 Documentation">Home</a></td><td width="40%" align="right" valign="top"> 37.2. Visibility of Data Changes</td></tr></table></div></body></html>