]> granicus.if.org Git - postgresql/blob - doc/src/sgml/ref/create_trigger.sgml
Merge documentation into one book. (Build with "make html".) Replace
[postgresql] / doc / src / sgml / ref / create_trigger.sgml
1 <!--
2 $Header: /cvsroot/pgsql/doc/src/sgml/ref/create_trigger.sgml,v 1.33 2003/03/25 16:15:39 petere Exp $
3 PostgreSQL documentation
4 -->
5
6 <refentry id="SQL-CREATETRIGGER">
7  <refmeta>
8   <refentrytitle id="SQL-CREATETRIGGER-TITLE">CREATE TRIGGER</refentrytitle>
9   <refmiscinfo>SQL - Language Statements</refmiscinfo>
10  </refmeta>
11  <refnamediv>
12   <refname>
13    CREATE TRIGGER
14   </refname>
15   <refpurpose>
16    define a new trigger
17   </refpurpose>
18  </refnamediv>
19  <refsynopsisdiv>
20   <refsynopsisdivinfo>
21    <date>2000-03-25</date>
22   </refsynopsisdivinfo>
23   <synopsis>
24 CREATE TRIGGER <replaceable class="PARAMETER">name</replaceable> { BEFORE | AFTER } { <replaceable class="PARAMETER">event</replaceable> [ OR ... ] }
25     ON <replaceable class="PARAMETER">table</replaceable> [ FOR [ EACH ] { ROW | STATEMENT } ]
26     EXECUTE PROCEDURE <replaceable class="PARAMETER">func</replaceable> ( <replaceable class="PARAMETER">arguments</replaceable> )
27   </synopsis>
28   
29   <refsect2 id="R2-SQL-CREATETRIGGER-1">
30    <refsect2info>
31     <date>1998-09-21</date>
32    </refsect2info>
33    <title>
34     Inputs
35    </title>
36    <para>
37
38     <variablelist>
39      <varlistentry>
40       <term><replaceable class="parameter">name</replaceable></term>
41       <listitem>
42        <para>
43         The name to give the new trigger.  This must be distinct from the name
44         of any other trigger for the same table.
45        </para>
46       </listitem>
47      </varlistentry>
48
49      <varlistentry>
50       <term>BEFORE</term>
51       <term>AFTER</term>
52       <listitem>
53        <para>
54                 Determines whether the function is called before or after the
55                 event.
56        </para>
57       </listitem>
58      </varlistentry>
59
60      <varlistentry>
61       <term><replaceable class="parameter">event</replaceable></term>
62       <listitem>
63        <para>
64                 One of <command>INSERT</command>, <command>DELETE</command> or
65                 <command>UPDATE</command>; this specifies the event that will
66                 fire the trigger. Multiple events can be specified using
67                 <literal>OR</literal>.
68        </para>
69       </listitem>
70      </varlistentry>
71      <varlistentry>
72       <term><replaceable class="parameter">table</replaceable></term>
73       <listitem>
74        <para>
75                 The name (optionally schema-qualified) of the table the
76                 trigger is for.
77        </para>
78       </listitem>
79      </varlistentry>
80
81          <varlistentry>
82           <term>FOR EACH ROW</term>
83           <term>FOR EACH STATEMENT</term>
84
85           <listitem>
86            <para>
87                 This specifies whether the trigger procedure should be fired
88                 once for every row affected by the trigger event, or just once
89                 per SQL statement. If neither is specified, <literal>FOR EACH
90                 STATEMENT</literal> is the default.
91            </para>
92           </listitem>
93          </varlistentry>
94
95      <varlistentry>
96       <term><replaceable class="parameter">func</replaceable></term>
97       <listitem>
98        <para>
99         A user-supplied function that is declared as taking no arguments
100         and returning type <literal>trigger</>.
101        </para>
102       </listitem>
103      </varlistentry>
104      <varlistentry>
105       <term><replaceable class="parameter">arguments</replaceable></term>
106       <listitem>
107        <para>
108     An optional comma-separated list of arguments to be provided to
109         the function when the trigger is executed, along with the standard
110         trigger data such as old and new tuple contents.  The arguments
111         are literal string constants.  Simple names and numeric constants
112         may be written here too, but they will all be converted to
113         strings. Note that these arguments are not provided as normal
114         function parameters (since a trigger procedure must be declared to
115         take zero parameters), but are instead accessed through the
116         <literal>TG_ARGV</literal> array.
117        </para>
118       </listitem>
119      </varlistentry>
120     </variablelist>
121    </para>
122   </refsect2>
123
124   <refsect2 id="R2-SQL-CREATETRIGGER-2">
125    <refsect2info>
126     <date>1998-09-21</date>
127    </refsect2info>
128    <title>
129     Outputs
130    </title>
131    <para>
132
133     <variablelist>
134      <varlistentry>
135       <term><computeroutput>
136 CREATE TRIGGER
137        </computeroutput></term>
138       <listitem>
139        <para>
140         This message is returned if the trigger is successfully created.
141        </para>
142       </listitem>
143      </varlistentry>
144     </variablelist>
145    </para>
146   </refsect2>
147  </refsynopsisdiv>
148  
149  <refsect1 id="R1-SQL-CREATETRIGGER-1">
150   <refsect1info>
151    <date>1998-09-21</date>
152   </refsect1info>
153   <title>
154    Description
155   </title>
156
157   <para>
158    <command>CREATE TRIGGER</command> will enter a new trigger into the current
159    database.  The trigger will be associated with the relation
160    <replaceable class="parameter">table</replaceable> and will execute
161    the specified function <replaceable class="parameter">func</replaceable>.
162   </para>
163
164   <para>
165    The trigger can be specified to fire either before BEFORE the
166    operation is attempted on a tuple (before constraints are checked and
167    the <command>INSERT</command>, <command>UPDATE</command> or
168    <command>DELETE</command> is attempted) or AFTER the operation has
169    been attempted (e.g., after constraints are checked and the
170    <command>INSERT</command>, <command>UPDATE</command> or
171    <command>DELETE</command> has completed). If the trigger fires before
172    the event, the trigger may skip the operation for the current tuple,
173    or change the tuple being inserted (for <command>INSERT</command> and
174    <command>UPDATE</command> operations only). If the trigger fires
175    after the event, all changes, including the last insertion, update,
176    or deletion, are <quote>visible</quote> to the trigger.
177   </para>
178
179   <para>
180    A trigger that executes <literal>FOR EACH ROW</literal> of the
181    specified operation is called once for every row that the operation
182    modifies. For example, a <command>DELETE</command> that affects 10
183    rows will cause any <literal>ON DELETE</literal> triggers on the
184    target relation to be called 10 separate times, once for each
185    deleted tuple. In contrast, a trigger that executes <literal>FOR
186    EACH STATEMENT</literal> of the specified operation only executes
187    once for any given operation, regardless of how many rows it
188    modifies (in particular, an operation that modifies zero rows will
189    still result in the execution of any applicable <literal>FOR EACH
190    STATEMENT</literal> triggers).
191   </para>
192
193   <para>
194    If multiple triggers of the same kind are defined for the same event,
195    they will be fired in alphabetical order by name.
196   </para>
197
198   <para>
199    <command>SELECT</command> does not modify any rows so you can not
200    create <command>SELECT</command> triggers. Rules and views are more
201    appropriate in such cases.
202   </para>
203
204   <para>
205    Refer to <xref linkend="server-programming"> for more information.
206   </para>
207  </refsect1>
208
209  <refsect1 id="SQL-CREATETRIGGER-notes">
210   <title>Notes</title>
211
212   <para>
213    To create a trigger on a table, the user must have the
214    <literal>TRIGGER</literal> privilege on the table.
215   </para>
216
217   <para>
218    In <productname>PostgreSQL</productname> versions before 7.3, it was
219    necessary to declare trigger functions as returning the placeholder
220    type <type>opaque</>, rather than <type>trigger</>.  To support loading
221    of old dump files, <command>CREATE TRIGGER</> will accept a function
222    declared as returning <type>opaque</>, but it will issue a NOTICE and
223    change the function's declared return type to <type>trigger</>.
224   </para>
225
226   <para>
227    Refer to the <xref linkend="sql-droptrigger" endterm="sql-droptrigger-title"> command for
228    information on how to remove triggers.
229   </para>
230  </refsect1>
231
232  <refsect1 id="R1-SQL-CREATETRIGGER-2">
233   <title>Examples</title>
234
235   <para>
236    Check if the specified distributor code exists in the distributors
237    table before appending or updating a row in the table films:
238
239 <programlisting>
240 CREATE TRIGGER if_dist_exists
241     BEFORE INSERT OR UPDATE ON films FOR EACH ROW
242     EXECUTE PROCEDURE check_primary_key ('did', 'distributors', 'did');
243 </programlisting>
244   </para>
245
246   <para>
247    Before cancelling a distributor or updating its code, remove every
248    reference to the table films:
249 <programlisting>
250 CREATE TRIGGER if_film_exists 
251     BEFORE DELETE OR UPDATE ON distributors FOR EACH ROW
252     EXECUTE PROCEDURE check_foreign_key (1, 'CASCADE', 'did', 'films', 'did');
253 </programlisting>
254   </para>
255
256   <para>
257    The second example can also be done by using a foreign key,
258    constraint as in:
259
260 <programlisting>
261 CREATE TABLE distributors (
262     did      DECIMAL(3),
263     name     VARCHAR(40),
264     CONSTRAINT if_film_exists
265     FOREIGN KEY(did) REFERENCES films
266     ON UPDATE CASCADE ON DELETE CASCADE  
267 );
268 </programlisting>
269   </para>
270  </refsect1>
271
272  <refsect1 id="SQL-CREATETRIGGER-compatibility">
273   <title>Compatibility</title>
274   
275   <variablelist>
276    <varlistentry>
277     <term>SQL92</term>
278     <listitem>
279      <para>
280       There is no <command>CREATE TRIGGER</command> statement in <acronym>SQL92</acronym>.
281      </para>
282     </listitem>
283    </varlistentry>
284
285    <varlistentry>
286     <term>SQL99</term>
287     <listitem>
288      <para>
289       The <command>CREATE TRIGGER</command> statement in
290       <productname>PostgreSQL</productname> implements a subset of the
291       SQL99 standard.  The following functionality is missing:
292       <itemizedlist>
293        <listitem>
294         <para>
295          SQL99 allows triggers to fire on updates to specific columns
296          (e.g., <literal>AFTER UPDATE OF col1, col2</literal>).
297         </para>
298        </listitem>
299
300        <listitem>
301         <para>
302          SQL99 allows you to define aliases for the <quote>old</quote>
303          and <quote>new</quote> rows or tables for use in the definition
304          of the triggered action (e.g., <literal>CREATE TRIGGER ... ON
305          tablename REFERENCING OLD ROW AS somename NEW ROW AS
306          othername ...</literal>).  Since
307          <productname>PostgreSQL</productname> allows trigger
308          procedures to be written in any number of user-defined
309          languages, access to the data is handled in a
310          language-specific way.
311         </para>
312        </listitem>
313
314        <listitem>
315         <para>
316          <productname>PostgreSQL</productname> only allows the
317          execution of a stored procedure for the triggered action.
318          SQL99 allows the execution of a number of other SQL commands,
319          such as <command>CREATE TABLE</command> as triggered action.
320          This limitation is not hard to work around by creating a
321          stored procedure that executes these commands.
322         </para>
323        </listitem>
324       </itemizedlist>
325      </para>
326
327      <para>
328       SQL99 specifies that multiple triggers should be fired in
329       time-of-creation order.  <productname>PostgreSQL</productname>
330       uses name order, which was judged more convenient to work with.
331      </para>
332
333      <para>
334       The ability to specify multiple actions for a single trigger
335       using <literal>OR</literal> is a <productname>PostgreSQL</>
336       extension of the SQL standard.
337      </para>
338     </listitem>
339    </varlistentry>
340   </variablelist>
341  </refsect1>
342
343  <refsect1>
344   <title>See Also</title>
345
346   <simplelist type="inline">
347    <member><xref linkend="sql-createfunction" endterm="sql-createfunction-title"></member>
348    <member><xref linkend="sql-altertrigger" endterm="sql-altertrigger-title"></member>
349    <member><xref linkend="sql-droptrigger" endterm="sql-droptrigger-title"></member>
350   </simplelist>
351  </refsect1>
352 </refentry>
353
354 <!-- Keep this comment at the end of the file
355 Local variables:
356 mode: sgml
357 sgml-omittag:nil
358 sgml-shorttag:t
359 sgml-minimize-attributes:nil
360 sgml-always-quote-attributes:t
361 sgml-indent-step:1
362 sgml-indent-data:t
363 sgml-parent-document:nil
364 sgml-default-dtd-file:"../reference.ced"
365 sgml-exposed-tags:nil
366 sgml-local-catalogs:"/usr/lib/sgml/catalog"
367 sgml-local-ecat-files:nil
368 End:
369 -->