]> granicus.if.org Git - postgresql/blob - doc/src/sgml/plpgsql.sgml
Change plan caching to honor, not resist, changes in search_path.
[postgresql] / doc / src / sgml / plpgsql.sgml
1 <!-- doc/src/sgml/plpgsql.sgml -->
2
3 <chapter id="plpgsql">
4   <title><application>PL/pgSQL</application> - <acronym>SQL</acronym> Procedural Language</title>
5
6  <indexterm zone="plpgsql">
7   <primary>PL/pgSQL</primary>
8  </indexterm>
9
10  <sect1 id="plpgsql-overview">
11   <title>Overview</title>
12
13  <para>
14   <application>PL/pgSQL</application> is a loadable procedural
15   language for the <productname>PostgreSQL</productname> database
16   system.  The design goals of <application>PL/pgSQL</> were to create
17   a loadable procedural language that
18
19     <itemizedlist>
20      <listitem>
21       <para>
22        can be used to create functions and trigger procedures,
23       </para>
24      </listitem>
25      <listitem>
26       <para>
27        adds control structures to the <acronym>SQL</acronym> language,
28       </para>
29      </listitem>
30      <listitem>
31       <para>
32        can perform complex computations,
33       </para>
34      </listitem>
35      <listitem>
36       <para>
37        inherits all user-defined types, functions, and operators,
38       </para>
39      </listitem>
40      <listitem>
41       <para>
42        can be defined to be trusted by the server,
43       </para>
44      </listitem>
45      <listitem>
46       <para>
47        is easy to use.
48       </para>
49      </listitem>
50     </itemizedlist>
51    </para>
52
53    <para>
54     Functions created with <application>PL/pgSQL</application> can be
55     used anywhere that built-in functions could be used.
56     For example, it is possible to
57     create complex conditional computation functions and later use
58     them to define operators or use them in index expressions.
59    </para>
60
61    <para>
62     In <productname>PostgreSQL</> 9.0 and later,
63     <application>PL/pgSQL</application> is installed by default.
64     However it is still a loadable module, so especially security-conscious
65     administrators could choose to remove it.
66    </para>
67
68   <sect2 id="plpgsql-advantages">
69    <title>Advantages of Using <application>PL/pgSQL</application></title>
70
71     <para>
72      <acronym>SQL</acronym> is the language <productname>PostgreSQL</>
73      and most other relational databases use as query language. It's
74      portable and easy to learn. But every <acronym>SQL</acronym>
75      statement must be executed individually by the database server.
76     </para>
77
78     <para>
79      That means that your client application must send each query to
80      the database server, wait for it to be processed, receive and
81      process the results, do some computation, then send further
82      queries to the server.  All this incurs interprocess
83      communication and will also incur network overhead if your client
84      is on a different machine than the database server.
85     </para>
86
87     <para>
88      With <application>PL/pgSQL</application> you can group a block of
89      computation and a series of queries <emphasis>inside</emphasis>
90      the database server, thus having the power of a procedural
91      language and the ease of use of SQL, but with considerable
92      savings of client/server communication overhead.
93     </para>
94     <itemizedlist>
95
96      <listitem><para> Extra round trips between
97      client and server are eliminated </para></listitem>
98
99      <listitem><para> Intermediate results that the client does not
100      need do not have to be marshaled or transferred between server
101      and client </para></listitem>
102
103      <listitem><para> Multiple rounds of query
104      parsing can be avoided </para></listitem>
105
106     </itemizedlist>
107     <para> This can result in a considerable performance increase as
108     compared to an application that does not use stored functions.
109     </para>
110
111     <para>
112      Also, with <application>PL/pgSQL</application> you can use all
113      the data types, operators and functions of SQL.
114     </para>
115   </sect2>
116
117   <sect2 id="plpgsql-args-results">
118    <title>Supported Argument and Result Data Types</title>
119
120     <para>
121      Functions written in <application>PL/pgSQL</application> can accept
122      as arguments any scalar or array data type supported by the server,
123      and they can return a result of any of these types.  They can also
124      accept or return any composite type (row type) specified by name.
125      It is also possible to declare a <application>PL/pgSQL</application>
126      function as returning <type>record</>, which means that the result
127      is a row type whose columns are determined by specification in the
128      calling query, as discussed in <xref linkend="queries-tablefunctions">.
129     </para>
130
131     <para>
132      <application>PL/pgSQL</> functions can be declared to accept a variable
133      number of arguments by using the <literal>VARIADIC</> marker.  This
134      works exactly the same way as for SQL functions, as discussed in
135      <xref linkend="xfunc-sql-variadic-functions">.
136     </para>
137
138     <para>
139      <application>PL/pgSQL</> functions can also be declared to accept
140      and return the polymorphic types
141      <type>anyelement</type>, <type>anyarray</type>, <type>anynonarray</type>,
142      <type>anyenum</>, and <type>anyrange</type>.  The actual
143      data types handled by a polymorphic function can vary from call to
144      call, as discussed in <xref linkend="extend-types-polymorphic">.
145      An example is shown in <xref linkend="plpgsql-declaration-parameters">.
146     </para>
147
148     <para>
149      <application>PL/pgSQL</> functions can also be declared to return
150      a <quote>set</> (or table) of any data type that can be returned as
151      a single instance.  Such a function generates its output by executing
152      <command>RETURN NEXT</> for each desired element of the result
153      set, or by using <command>RETURN QUERY</> to output the result of
154      evaluating a query.
155     </para>
156
157     <para>
158      Finally, a <application>PL/pgSQL</> function can be declared to return
159      <type>void</> if it has no useful return value.
160     </para>
161
162     <para>
163      <application>PL/pgSQL</> functions can also be declared with output
164      parameters in place of an explicit specification of the return type.
165      This does not add any fundamental capability to the language, but
166      it is often convenient, especially for returning multiple values.
167      The <literal>RETURNS TABLE</> notation can also be used in place
168      of <literal>RETURNS SETOF</>.
169     </para>
170
171     <para>
172      Specific examples appear in
173      <xref linkend="plpgsql-declaration-parameters"> and
174      <xref linkend="plpgsql-statements-returning">.
175     </para>
176   </sect2>
177  </sect1>
178
179  <sect1 id="plpgsql-structure">
180   <title>Structure of <application>PL/pgSQL</application></title>
181
182   <para>
183    <application>PL/pgSQL</application> is a block-structured language.
184    The complete text of a function definition must be a
185    <firstterm>block</>. A block is defined as:
186
187 <synopsis>
188 <optional> &lt;&lt;<replaceable>label</replaceable>&gt;&gt; </optional>
189 <optional> DECLARE
190     <replaceable>declarations</replaceable> </optional>
191 BEGIN
192     <replaceable>statements</replaceable>
193 END <optional> <replaceable>label</replaceable> </optional>;
194 </synopsis>
195     </para>
196
197     <para>
198      Each declaration and each statement within a block is terminated
199      by a semicolon.  A block that appears within another block must
200      have a semicolon after <literal>END</literal>, as shown above;
201      however the final <literal>END</literal> that
202      concludes a function body does not require a semicolon.
203     </para>
204
205     <tip>
206      <para>
207       A common mistake is to write a semicolon immediately after
208       <literal>BEGIN</>.  This is incorrect and will result in a syntax error.
209      </para>
210     </tip>
211
212     <para>
213      A <replaceable>label</replaceable> is only needed if you want to
214      identify the block for use
215      in an <literal>EXIT</> statement, or to qualify the names of the
216      variables declared in the block.  If a label is given after
217      <literal>END</>, it must match the label at the block's beginning.
218     </para>
219
220     <para>
221      All key words are case-insensitive.
222      Identifiers are implicitly converted to lower case
223      unless double-quoted, just as they are in ordinary SQL commands.
224     </para>
225
226     <para>
227      Comments work the same way in <application>PL/pgSQL</> code as in
228      ordinary SQL.  A double dash (<literal>--</literal>) starts a comment
229      that extends to the end of the line. A <literal>/*</literal> starts a
230      block comment that extends to the matching occurrence of
231      <literal>*/</literal>.  Block comments nest.
232     </para>
233
234     <para>
235      Any statement in the statement section of a block
236      can be a <firstterm>subblock</>.  Subblocks can be used for
237      logical grouping or to localize variables to a small group
238      of statements.  Variables declared in a subblock mask any
239      similarly-named variables of outer blocks for the duration
240      of the subblock; but you can access the outer variables anyway
241      if you qualify their names with their block's label. For example:
242 <programlisting>
243 CREATE FUNCTION somefunc() RETURNS integer AS $$
244 &lt;&lt; outerblock &gt;&gt;
245 DECLARE
246     quantity integer := 30;
247 BEGIN
248     RAISE NOTICE 'Quantity here is %', quantity;  -- Prints 30
249     quantity := 50;
250     --
251     -- Create a subblock
252     --
253     DECLARE
254         quantity integer := 80;
255     BEGIN
256         RAISE NOTICE 'Quantity here is %', quantity;  -- Prints 80
257         RAISE NOTICE 'Outer quantity here is %', outerblock.quantity;  -- Prints 50
258     END;
259
260     RAISE NOTICE 'Quantity here is %', quantity;  -- Prints 50
261
262     RETURN quantity;
263 END;
264 $$ LANGUAGE plpgsql;
265 </programlisting>
266     </para>
267
268     <note>
269      <para>
270       There is actually a hidden <quote>outer block</> surrounding the body
271       of any <application>PL/pgSQL</> function.  This block provides the
272       declarations of the function's parameters (if any), as well as some
273       special variables such as <literal>FOUND</literal> (see
274       <xref linkend="plpgsql-statements-diagnostics">).  The outer block is
275       labeled with the function's name, meaning that parameters and special
276       variables can be qualified with the function's name.
277      </para>
278     </note>
279
280     <para>
281      It is important not to confuse the use of
282      <command>BEGIN</>/<command>END</> for grouping statements in
283      <application>PL/pgSQL</> with the similarly-named SQL commands
284      for transaction
285      control.  <application>PL/pgSQL</>'s <command>BEGIN</>/<command>END</>
286      are only for grouping; they do not start or end a transaction.
287      Functions and trigger procedures are always executed within a transaction
288      established by an outer query &mdash; they cannot start or commit that
289      transaction, since there would be no context for them to execute in.
290      However, a block containing an <literal>EXCEPTION</> clause effectively
291      forms a subtransaction that can be rolled back without affecting the
292      outer transaction.  For more about that see <xref
293      linkend="plpgsql-error-trapping">.
294     </para>
295   </sect1>
296
297   <sect1 id="plpgsql-declarations">
298     <title>Declarations</title>
299
300     <para>
301      All variables used in a block must be declared in the
302      declarations section of the block.
303      (The only exceptions are that the loop variable of a <literal>FOR</> loop
304      iterating over a range of integer values is automatically declared as an
305      integer variable, and likewise the loop variable of a <literal>FOR</> loop
306      iterating over a cursor's result is automatically declared as a
307      record variable.)
308     </para>
309
310     <para>
311      <application>PL/pgSQL</> variables can have any SQL data type, such as
312      <type>integer</type>, <type>varchar</type>, and
313      <type>char</type>.
314     </para>
315
316     <para>
317      Here are some examples of variable declarations:
318 <programlisting>
319 user_id integer;
320 quantity numeric(5);
321 url varchar;
322 myrow tablename%ROWTYPE;
323 myfield tablename.columnname%TYPE;
324 arow RECORD;
325 </programlisting>
326     </para>
327
328     <para>
329      The general syntax of a variable declaration is:
330 <synopsis>
331 <replaceable>name</replaceable> <optional> CONSTANT </optional> <replaceable>type</replaceable> <optional> COLLATE <replaceable>collation_name</replaceable> </optional> <optional> NOT NULL </optional> <optional> { DEFAULT | := } <replaceable>expression</replaceable> </optional>;
332 </synopsis>
333       The <literal>DEFAULT</> clause, if given, specifies the initial value assigned
334       to the variable when the block is entered.  If the <literal>DEFAULT</> clause
335       is not given then the variable is initialized to the
336       <acronym>SQL</acronym> null value.
337       The <literal>CONSTANT</> option prevents the variable from being
338       assigned to after initialization, so that its value will remain constant
339       for the duration of the block.
340       The <literal>COLLATE</> option specifies a collation to use for the
341       variable (see <xref linkend="plpgsql-declaration-collation">).
342       If <literal>NOT NULL</>
343       is specified, an assignment of a null value results in a run-time
344       error. All variables declared as <literal>NOT NULL</>
345       must have a nonnull default value specified.
346      </para>
347
348      <para>
349       A variable's default value is evaluated and assigned to the variable
350       each time the block is entered (not just once per function call).
351       So, for example, assigning <literal>now()</literal> to a variable of type
352       <type>timestamp</type> causes the variable to have the
353       time of the current function call, not the time when the function was
354       precompiled.
355      </para>
356
357      <para>
358       Examples:
359 <programlisting>
360 quantity integer DEFAULT 32;
361 url varchar := 'http://mysite.com';
362 user_id CONSTANT integer := 10;
363 </programlisting>
364      </para>
365
366     <sect2 id="plpgsql-declaration-parameters">
367      <title>Declaring Function Parameters</title>
368
369      <para>
370       Parameters passed to functions are named with the identifiers
371       <literal>$1</literal>, <literal>$2</literal>,
372       etc.  Optionally, aliases can be declared for
373       <literal>$<replaceable>n</replaceable></literal>
374       parameter names for increased readability.  Either the alias or the
375       numeric identifier can then be used to refer to the parameter value.
376      </para>
377
378      <para>
379       There are two ways to create an alias.  The preferred way is to give a
380       name to the parameter in the <command>CREATE FUNCTION</command> command,
381       for example:
382 <programlisting>
383 CREATE FUNCTION sales_tax(subtotal real) RETURNS real AS $$
384 BEGIN
385     RETURN subtotal * 0.06;
386 END;
387 $$ LANGUAGE plpgsql;
388 </programlisting>
389       The other way, which was the only way available before
390       <productname>PostgreSQL</productname> 8.0, is to explicitly
391       declare an alias, using the declaration syntax
392
393 <synopsis>
394 <replaceable>name</replaceable> ALIAS FOR $<replaceable>n</replaceable>;
395 </synopsis>
396
397       The same example in this style looks like:
398 <programlisting>
399 CREATE FUNCTION sales_tax(real) RETURNS real AS $$
400 DECLARE
401     subtotal ALIAS FOR $1;
402 BEGIN
403     RETURN subtotal * 0.06;
404 END;
405 $$ LANGUAGE plpgsql;
406 </programlisting>
407      </para>
408
409     <note>
410      <para>
411       These two examples are not perfectly equivalent.  In the first case,
412       <literal>subtotal</> could be referenced as
413       <literal>sales_tax.subtotal</>, but in the second case it could not.
414       (Had we attached a label to the inner block, <literal>subtotal</> could
415       be qualified with that label, instead.)
416      </para>
417     </note>
418
419      <para>
420       Some more examples:
421 <programlisting>
422 CREATE FUNCTION instr(varchar, integer) RETURNS integer AS $$
423 DECLARE
424     v_string ALIAS FOR $1;
425     index ALIAS FOR $2;
426 BEGIN
427     -- some computations using v_string and index here
428 END;
429 $$ LANGUAGE plpgsql;
430
431
432 CREATE FUNCTION concat_selected_fields(in_t sometablename) RETURNS text AS $$
433 BEGIN
434     RETURN in_t.f1 || in_t.f3 || in_t.f5 || in_t.f7;
435 END;
436 $$ LANGUAGE plpgsql;
437 </programlisting>
438      </para>
439
440      <para>
441       When a <application>PL/pgSQL</application> function is declared
442       with output parameters, the output parameters are given
443       <literal>$<replaceable>n</replaceable></literal> names and optional
444       aliases in just the same way as the normal input parameters.  An
445       output parameter is effectively a variable that starts out NULL;
446       it should be assigned to during the execution of the function.
447       The final value of the parameter is what is returned.  For instance,
448       the sales-tax example could also be done this way:
449
450 <programlisting>
451 CREATE FUNCTION sales_tax(subtotal real, OUT tax real) AS $$
452 BEGIN
453     tax := subtotal * 0.06;
454 END;
455 $$ LANGUAGE plpgsql;
456 </programlisting>
457
458       Notice that we omitted <literal>RETURNS real</> &mdash; we could have
459       included it, but it would be redundant.
460      </para>
461
462      <para>
463       Output parameters are most useful when returning multiple values.
464       A trivial example is:
465
466 <programlisting>
467 CREATE FUNCTION sum_n_product(x int, y int, OUT sum int, OUT prod int) AS $$
468 BEGIN
469     sum := x + y;
470     prod := x * y;
471 END;
472 $$ LANGUAGE plpgsql;
473 </programlisting>
474
475       As discussed in <xref linkend="xfunc-output-parameters">, this
476       effectively creates an anonymous record type for the function's
477       results.  If a <literal>RETURNS</> clause is given, it must say
478       <literal>RETURNS record</>.
479      </para>
480
481      <para>
482       Another way to declare a <application>PL/pgSQL</application> function
483       is with <literal>RETURNS TABLE</>, for example:
484
485 <programlisting>
486 CREATE FUNCTION extended_sales(p_itemno int)
487 RETURNS TABLE(quantity int, total numeric) AS $$
488 BEGIN
489     RETURN QUERY SELECT quantity, quantity * price FROM sales
490                  WHERE itemno = p_itemno;
491 END;
492 $$ LANGUAGE plpgsql;
493 </programlisting>
494
495       This is exactly equivalent to declaring one or more <literal>OUT</>
496       parameters and specifying <literal>RETURNS SETOF
497       <replaceable>sometype</></literal>.
498      </para>
499
500      <para>
501       When the return type of a <application>PL/pgSQL</application>
502       function is declared as a polymorphic type (<type>anyelement</type>,
503       <type>anyarray</type>, <type>anynonarray</type>, <type>anyenum</type>,
504       or <type>anyrange</type>), a special parameter <literal>$0</literal>
505       is created.  Its data type is the actual return type of the function,
506       as deduced from the actual input types (see <xref
507       linkend="extend-types-polymorphic">).
508       This allows the function to access its actual return type
509       as shown in <xref linkend="plpgsql-declaration-type">.
510       <literal>$0</literal> is initialized to null and can be modified by
511       the function, so it can be used to hold the return value if desired,
512       though that is not required.  <literal>$0</literal> can also be
513       given an alias.  For example, this function works on any data type
514       that has a <literal>+</> operator:
515
516 <programlisting>
517 CREATE FUNCTION add_three_values(v1 anyelement, v2 anyelement, v3 anyelement)
518 RETURNS anyelement AS $$
519 DECLARE
520     result ALIAS FOR $0;
521 BEGIN
522     result := v1 + v2 + v3;
523     RETURN result;
524 END;
525 $$ LANGUAGE plpgsql;
526 </programlisting>
527      </para>
528
529      <para>
530       The same effect can be had by declaring one or more output parameters as
531       polymorphic types.  In this case the
532       special <literal>$0</literal> parameter is not used; the output
533       parameters themselves serve the same purpose.  For example:
534
535 <programlisting>
536 CREATE FUNCTION add_three_values(v1 anyelement, v2 anyelement, v3 anyelement,
537                                  OUT sum anyelement)
538 AS $$
539 BEGIN
540     sum := v1 + v2 + v3;
541 END;
542 $$ LANGUAGE plpgsql;
543 </programlisting>
544      </para>
545     </sect2>
546
547   <sect2 id="plpgsql-declaration-alias">
548    <title><literal>ALIAS</></title>
549
550 <synopsis>
551 <replaceable>newname</> ALIAS FOR <replaceable>oldname</>;
552 </synopsis>
553
554    <para>
555     The <literal>ALIAS</> syntax is more general than is suggested in the
556     previous section: you can declare an alias for any variable, not just
557     function parameters.  The main practical use for this is to assign
558     a different name for variables with predetermined names, such as
559     <varname>NEW</varname> or <varname>OLD</varname> within
560     a trigger procedure.
561    </para>
562
563    <para>
564     Examples:
565 <programlisting>
566 DECLARE
567   prior ALIAS FOR old;
568   updated ALIAS FOR new;
569 </programlisting>
570    </para>
571
572    <para>
573     Since <literal>ALIAS</> creates two different ways to name the same
574     object, unrestricted use can be confusing.  It's best to use it only
575     for the purpose of overriding predetermined names.
576    </para>
577    </sect2>
578
579   <sect2 id="plpgsql-declaration-type">
580    <title>Copying Types</title>
581
582 <synopsis>
583 <replaceable>variable</replaceable>%TYPE
584 </synopsis>
585
586    <para>
587     <literal>%TYPE</literal> provides the data type of a variable or
588     table column. You can use this to declare variables that will hold
589     database values. For example, let's say you have a column named
590     <literal>user_id</literal> in your <literal>users</literal>
591     table. To declare a variable with the same data type as
592     <literal>users.user_id</> you write:
593 <programlisting>
594 user_id users.user_id%TYPE;
595 </programlisting>
596    </para>
597
598    <para>
599     By using <literal>%TYPE</literal> you don't need to know the data
600     type of the structure you are referencing, and most importantly,
601     if the data type of the referenced item changes in the future (for
602     instance: you change the type of <literal>user_id</>
603     from <type>integer</type> to <type>real</type>), you might not need
604     to change your function definition.
605    </para>
606
607    <para>
608     <literal>%TYPE</literal> is particularly valuable in polymorphic
609     functions, since the data types needed for internal variables can
610     change from one call to the next.  Appropriate variables can be
611     created by applying <literal>%TYPE</literal> to the function's
612     arguments or result placeholders.
613    </para>
614
615   </sect2>
616
617     <sect2 id="plpgsql-declaration-rowtypes">
618      <title>Row Types</title>
619
620 <synopsis>
621 <replaceable>name</replaceable> <replaceable>table_name</replaceable><literal>%ROWTYPE</literal>;
622 <replaceable>name</replaceable> <replaceable>composite_type_name</replaceable>;
623 </synopsis>
624
625    <para>
626     A variable of a composite type is called a <firstterm>row</>
627     variable (or <firstterm>row-type</> variable).  Such a variable
628     can hold a whole row of a <command>SELECT</> or <command>FOR</>
629     query result, so long as that query's column set matches the
630     declared type of the variable.
631     The individual fields of the row value
632     are accessed using the usual dot notation, for example
633     <literal>rowvar.field</literal>.
634    </para>
635
636    <para>
637     A row variable can be declared to have the same type as the rows of
638     an existing table or view, by using the
639     <replaceable>table_name</replaceable><literal>%ROWTYPE</literal>
640     notation; or it can be declared by giving a composite type's name.
641     (Since every table has an associated composite type of the same name,
642     it actually does not matter in <productname>PostgreSQL</> whether you
643     write <literal>%ROWTYPE</literal> or not.  But the form with
644     <literal>%ROWTYPE</literal> is more portable.)
645    </para>
646
647    <para>
648     Parameters to a function can be
649     composite types (complete table rows). In that case, the
650     corresponding identifier <literal>$<replaceable>n</replaceable></> will be a row variable, and fields can
651     be selected from it, for example <literal>$1.user_id</literal>.
652    </para>
653
654    <para>
655     Only the user-defined columns of a table row are accessible in a
656     row-type variable, not the OID or other system columns (because the
657     row could be from a view).  The fields of the row type inherit the
658     table's field size or precision for data types such as
659     <type>char(<replaceable>n</>)</type>.
660    </para>
661
662    <para>
663     Here is an example of using composite types.  <structname>table1</>
664     and <structname>table2</> are existing tables having at least the
665     mentioned fields:
666
667 <programlisting>
668 CREATE FUNCTION merge_fields(t_row table1) RETURNS text AS $$
669 DECLARE
670     t2_row table2%ROWTYPE;
671 BEGIN
672     SELECT * INTO t2_row FROM table2 WHERE ... ;
673     RETURN t_row.f1 || t2_row.f3 || t_row.f5 || t2_row.f7;
674 END;
675 $$ LANGUAGE plpgsql;
676
677 SELECT merge_fields(t.*) FROM table1 t WHERE ... ;
678 </programlisting>
679    </para>
680   </sect2>
681
682   <sect2 id="plpgsql-declaration-records">
683    <title>Record Types</title>
684
685 <synopsis>
686 <replaceable>name</replaceable> RECORD;
687 </synopsis>
688
689    <para>
690     Record variables are similar to row-type variables, but they have no
691     predefined structure.  They take on the actual row structure of the
692     row they are assigned during a <command>SELECT</> or <command>FOR</> command.  The substructure
693     of a record variable can change each time it is assigned to.
694     A consequence of this is that until a record variable is first assigned
695     to, it has no substructure, and any attempt to access a
696     field in it will draw a run-time error.
697    </para>
698
699    <para>
700     Note that <literal>RECORD</> is not a true data type, only a placeholder.
701     One should also realize that when a <application>PL/pgSQL</application>
702     function is declared to return type <type>record</>, this is not quite the
703     same concept as a record variable, even though such a function might
704     use a record variable to hold its result.  In both cases the actual row
705     structure is unknown when the function is written, but for a function
706     returning <type>record</> the actual structure is determined when the
707     calling query is parsed, whereas a record variable can change its row
708     structure on-the-fly.
709    </para>
710   </sect2>
711
712   <sect2 id="plpgsql-declaration-collation">
713    <title>Collation of <application>PL/pgSQL</application> Variables</title>
714
715    <indexterm>
716     <primary>collation</>
717     <secondary>in PL/pgSQL</>
718    </indexterm>
719
720    <para>
721     When a <application>PL/pgSQL</application> function has one or more
722     parameters of collatable data types, a collation is identified for each
723     function call depending on the collations assigned to the actual
724     arguments, as described in <xref linkend="collation">.  If a collation is
725     successfully identified (i.e., there are no conflicts of implicit
726     collations among the arguments) then all the collatable parameters are
727     treated as having that collation implicitly.  This will affect the
728     behavior of collation-sensitive operations within the function.
729     For example, consider
730
731 <programlisting>
732 CREATE FUNCTION less_than(a text, b text) RETURNS boolean AS $$
733 BEGIN
734     RETURN a &lt; b;
735 END;
736 $$ LANGUAGE plpgsql;
737
738 SELECT less_than(text_field_1, text_field_2) FROM table1;
739 SELECT less_than(text_field_1, text_field_2 COLLATE "C") FROM table1;
740 </programlisting>
741
742     The first use of <function>less_than</> will use the common collation
743     of <structfield>text_field_1</> and <structfield>text_field_2</> for
744     the comparison, while the second use will use <literal>C</> collation.
745    </para>
746
747    <para>
748     Furthermore, the identified collation is also assumed as the collation of
749     any local variables that are of collatable types.  Thus this function
750     would not work any differently if it were written as
751
752 <programlisting>
753 CREATE FUNCTION less_than(a text, b text) RETURNS boolean AS $$
754 DECLARE
755     local_a text := a;
756     local_b text := b;
757 BEGIN
758     RETURN local_a &lt; local_b;
759 END;
760 $$ LANGUAGE plpgsql;
761 </programlisting>
762    </para>
763
764    <para>
765     If there are no parameters of collatable data types, or no common
766     collation can be identified for them, then parameters and local variables
767     use the default collation of their data type (which is usually the
768     database's default collation, but could be different for variables of
769     domain types).
770    </para>
771
772    <para>
773     A local variable of a collatable data type can have a different collation
774     associated with it by including the <literal>COLLATE</> option in its
775     declaration, for example
776
777 <programlisting>
778 DECLARE
779     local_a text COLLATE "en_US";
780 </programlisting>
781
782     This option overrides the collation that would otherwise be
783     given to the variable according to the rules above.
784    </para>
785
786    <para>
787     Also, of course explicit <literal>COLLATE</> clauses can be written inside
788     a function if it is desired to force a particular collation to be used in
789     a particular operation.  For example,
790
791 <programlisting>
792 CREATE FUNCTION less_than_c(a text, b text) RETURNS boolean AS $$
793 BEGIN
794     RETURN a &lt; b COLLATE "C";
795 END;
796 $$ LANGUAGE plpgsql;
797 </programlisting>
798
799     This overrides the collations associated with the table columns,
800     parameters, or local variables used in the expression, just as would
801     happen in a plain SQL command.
802    </para>
803   </sect2>
804   </sect1>
805
806   <sect1 id="plpgsql-expressions">
807   <title>Expressions</title>
808
809     <para>
810      All expressions used in <application>PL/pgSQL</application>
811      statements are processed using the server's main
812      <acronym>SQL</acronym> executor.  For example, when you write
813      a <application>PL/pgSQL</application> statement like
814 <synopsis>
815 IF <replaceable>expression</replaceable> THEN ...
816 </synopsis>
817      <application>PL/pgSQL</application> will evaluate the expression by
818      feeding a query like
819 <synopsis>
820 SELECT <replaceable>expression</replaceable>
821 </synopsis>
822      to the main SQL engine.  While forming the <command>SELECT</> command,
823      any occurrences of <application>PL/pgSQL</application> variable names
824      are replaced by parameters, as discussed in detail in
825      <xref linkend="plpgsql-var-subst">.
826      This allows the query plan for the <command>SELECT</command> to
827      be prepared just once and then reused for subsequent
828      evaluations with different values of the variables.  Thus, what
829      really happens on first use of an expression is essentially a
830      <command>PREPARE</> command.  For example, if we have declared
831      two integer variables <literal>x</> and <literal>y</>, and we write
832 <programlisting>
833 IF x &lt; y THEN ...
834 </programlisting>
835      what happens behind the scenes is equivalent to
836 <programlisting>
837 PREPARE <replaceable>statement_name</>(integer, integer) AS SELECT $1 &lt; $2;
838 </programlisting>
839      and then this prepared statement is <command>EXECUTE</>d for each
840      execution of the <command>IF</> statement, with the current values
841      of the <application>PL/pgSQL</application> variables supplied as
842      parameter values.  Normally these details are
843      not important to a <application>PL/pgSQL</application> user, but
844      they are useful to know when trying to diagnose a problem.
845      More information appears in <xref linkend="plpgsql-plan-caching">.
846     </para>
847   </sect1>
848
849   <sect1 id="plpgsql-statements">
850   <title>Basic Statements</title>
851
852    <para>
853     In this section and the following ones, we describe all the statement
854     types that are explicitly understood by
855     <application>PL/pgSQL</application>.
856     Anything not recognized as one of these statement types is presumed
857     to be an SQL command and is sent to the main database engine to execute,
858     as described in <xref linkend="plpgsql-statements-sql-noresult">
859     and <xref linkend="plpgsql-statements-sql-onerow">.
860    </para>
861
862    <sect2 id="plpgsql-statements-assignment">
863     <title>Assignment</title>
864
865     <para>
866      An assignment of a value to a <application>PL/pgSQL</application>
867      variable is written as:
868 <synopsis>
869 <replaceable>variable</replaceable> := <replaceable>expression</replaceable>;
870 </synopsis>
871      As explained previously, the expression in such a statement is evaluated
872      by means of an SQL <command>SELECT</> command sent to the main
873      database engine.  The expression must yield a single value (possibly
874      a row value, if the variable is a row or record variable).  The target
875      variable can be a simple variable (optionally qualified with a block
876      name), a field of a row or record variable, or an element of an array
877      that is a simple variable or field.
878     </para>
879
880     <para>
881      If the expression's result data type doesn't match the variable's
882      data type, or the variable has a specific size/precision
883      (like <type>char(20)</type>), the result value will be implicitly
884      converted by the <application>PL/pgSQL</application> interpreter using
885      the result type's output-function and
886      the variable type's input-function. Note that this could potentially
887      result in run-time errors generated by the input function, if the
888      string form of the result value is not acceptable to the input function.
889     </para>
890
891     <para>
892      Examples:
893 <programlisting>
894 tax := subtotal * 0.06;
895 my_record.user_id := 20;
896 </programlisting>
897     </para>
898    </sect2>
899
900    <sect2 id="plpgsql-statements-sql-noresult">
901     <title>Executing a Command With No Result</title>
902
903     <para>
904      For any SQL command that does not return rows, for example
905      <command>INSERT</> without a <literal>RETURNING</> clause, you can
906      execute the command within a <application>PL/pgSQL</application> function
907      just by writing the command.
908     </para>
909
910     <para>
911      Any <application>PL/pgSQL</application> variable name appearing
912      in the command text is treated as a parameter, and then the
913      current value of the variable is provided as the parameter value
914      at run time.  This is exactly like the processing described earlier
915      for expressions; for details see <xref linkend="plpgsql-var-subst">.
916     </para>
917
918     <para>
919      When executing a SQL command in this way,
920      <application>PL/pgSQL</application> may cache and re-use the execution
921      plan for the command, as discussed in
922      <xref linkend="plpgsql-plan-caching">.
923     </para>
924
925     <para>
926      Sometimes it is useful to evaluate an expression or <command>SELECT</>
927      query but discard the result, for example when calling a function
928      that has side-effects but no useful result value.  To do
929      this in <application>PL/pgSQL</application>, use the
930      <command>PERFORM</command> statement:
931
932 <synopsis>
933 PERFORM <replaceable>query</replaceable>;
934 </synopsis>
935
936      This executes <replaceable>query</replaceable> and discards the
937      result.  Write the <replaceable>query</replaceable> the same
938      way you would write an SQL <command>SELECT</> command, but replace the
939      initial keyword <command>SELECT</> with <command>PERFORM</command>.
940      For <command>WITH</> queries, use <command>PERFORM</> and then
941      place the query in parentheses.  (In this case, the query can only
942      return one row.)
943      <application>PL/pgSQL</application> variables will be
944      substituted into the query just as for commands that return no result,
945      and the plan is cached in the same way.  Also, the special variable
946      <literal>FOUND</literal> is set to true if the query produced at
947      least one row, or false if it produced no rows (see
948      <xref linkend="plpgsql-statements-diagnostics">).
949     </para>
950
951     <note>
952      <para>
953       One might expect that writing <command>SELECT</command> directly
954       would accomplish this result, but at
955       present the only accepted way to do it is
956       <command>PERFORM</command>.  A SQL command that can return rows,
957       such as <command>SELECT</command>, will be rejected as an error
958       unless it has an <literal>INTO</> clause as discussed in the
959       next section.
960      </para>
961     </note>
962
963     <para>
964      An example:
965 <programlisting>
966 PERFORM create_mv('cs_session_page_requests_mv', my_query);
967 </programlisting>
968     </para>
969    </sect2>
970
971    <sect2 id="plpgsql-statements-sql-onerow">
972     <title>Executing a Query with a Single-row Result</title>
973
974     <indexterm zone="plpgsql-statements-sql-onerow">
975      <primary>SELECT INTO</primary>
976      <secondary>in PL/pgSQL</secondary>
977     </indexterm>
978
979     <indexterm zone="plpgsql-statements-sql-onerow">
980      <primary>RETURNING INTO</primary>
981      <secondary>in PL/pgSQL</secondary>
982     </indexterm>
983
984     <para>
985      The result of a SQL command yielding a single row (possibly of multiple
986      columns) can be assigned to a record variable, row-type variable, or list
987      of scalar variables.  This is done by writing the base SQL command and
988      adding an <literal>INTO</> clause.  For example,
989
990 <synopsis>
991 SELECT <replaceable>select_expressions</replaceable> INTO <optional>STRICT</optional> <replaceable>target</replaceable> FROM ...;
992 INSERT ... RETURNING <replaceable>expressions</replaceable> INTO <optional>STRICT</optional> <replaceable>target</replaceable>;
993 UPDATE ... RETURNING <replaceable>expressions</replaceable> INTO <optional>STRICT</optional> <replaceable>target</replaceable>;
994 DELETE ... RETURNING <replaceable>expressions</replaceable> INTO <optional>STRICT</optional> <replaceable>target</replaceable>;
995 </synopsis>
996
997      where <replaceable>target</replaceable> can be a record variable, a row
998      variable, or a comma-separated list of simple variables and
999      record/row fields.
1000      <application>PL/pgSQL</application> variables will be
1001      substituted into the rest of the query, and the plan is cached,
1002      just as described above for commands that do not return rows.
1003      This works for <command>SELECT</>,
1004      <command>INSERT</>/<command>UPDATE</>/<command>DELETE</> with
1005      <literal>RETURNING</>, and utility commands that return row-set
1006      results (such as <command>EXPLAIN</>).
1007      Except for the <literal>INTO</> clause, the SQL command is the same
1008      as it would be written outside <application>PL/pgSQL</application>.
1009     </para>
1010
1011    <tip>
1012     <para>
1013      Note that this interpretation of <command>SELECT</> with <literal>INTO</>
1014      is quite different from <productname>PostgreSQL</>'s regular
1015      <command>SELECT INTO</command> command, wherein the <literal>INTO</>
1016      target is a newly created table.  If you want to create a table from a
1017      <command>SELECT</> result inside a
1018      <application>PL/pgSQL</application> function, use the syntax
1019      <command>CREATE TABLE ... AS SELECT</command>.
1020     </para>
1021    </tip>
1022
1023     <para>
1024      If a row or a variable list is used as target, the query's result columns
1025      must exactly match the structure of the target as to number and data
1026      types, or else a run-time error
1027      occurs.  When a record variable is the target, it automatically
1028      configures itself to the row type of the query result columns.
1029     </para>
1030
1031     <para>
1032      The <literal>INTO</> clause can appear almost anywhere in the SQL
1033      command.  Customarily it is written either just before or just after
1034      the list of <replaceable>select_expressions</replaceable> in a
1035      <command>SELECT</> command, or at the end of the command for other
1036      command types.  It is recommended that you follow this convention
1037      in case the <application>PL/pgSQL</application> parser becomes
1038      stricter in future versions.
1039     </para>
1040
1041     <para>
1042      If <literal>STRICT</literal> is not specified in the <literal>INTO</>
1043      clause, then <replaceable>target</replaceable> will be set to the first
1044      row returned by the query, or to nulls if the query returned no rows.
1045      (Note that <quote>the first row</> is not
1046      well-defined unless you've used <literal>ORDER BY</>.)  Any result rows
1047      after the first row are discarded.
1048      You can check the special <literal>FOUND</literal> variable (see
1049      <xref linkend="plpgsql-statements-diagnostics">) to
1050      determine whether a row was returned:
1051
1052 <programlisting>
1053 SELECT * INTO myrec FROM emp WHERE empname = myname;
1054 IF NOT FOUND THEN
1055     RAISE EXCEPTION 'employee % not found', myname;
1056 END IF;
1057 </programlisting>
1058
1059      If the <literal>STRICT</literal> option is specified, the query must
1060      return exactly one row or a run-time error will be reported, either
1061      <literal>NO_DATA_FOUND</> (no rows) or <literal>TOO_MANY_ROWS</>
1062      (more than one row). You can use an exception block if you wish
1063      to catch the error, for example:
1064
1065 <programlisting>
1066 BEGIN
1067     SELECT * INTO STRICT myrec FROM emp WHERE empname = myname;
1068     EXCEPTION
1069         WHEN NO_DATA_FOUND THEN
1070             RAISE EXCEPTION 'employee % not found', myname;
1071         WHEN TOO_MANY_ROWS THEN
1072             RAISE EXCEPTION 'employee % not unique', myname;
1073 END;
1074 </programlisting>
1075      Successful execution of a command with <literal>STRICT</>
1076      always sets <literal>FOUND</literal> to true.
1077     </para>
1078
1079     <para>
1080      For <command>INSERT</>/<command>UPDATE</>/<command>DELETE</> with
1081      <literal>RETURNING</>, <application>PL/pgSQL</application> reports
1082      an error for more than one returned row, even when
1083      <literal>STRICT</literal> is not specified.  This is because there
1084      is no option such as <literal>ORDER BY</> with which to determine
1085      which affected row should be returned.
1086     </para>
1087
1088     <note>
1089      <para>
1090       The <literal>STRICT</> option matches the behavior of
1091       Oracle PL/SQL's <command>SELECT INTO</command> and related statements.
1092      </para>
1093     </note>
1094
1095     <para>
1096      To handle cases where you need to process multiple result rows
1097      from a SQL query, see <xref linkend="plpgsql-records-iterating">.
1098     </para>
1099
1100    </sect2>
1101
1102    <sect2 id="plpgsql-statements-executing-dyn">
1103     <title>Executing Dynamic Commands</title>
1104
1105     <para>
1106      Oftentimes you will want to generate dynamic commands inside your
1107      <application>PL/pgSQL</application> functions, that is, commands
1108      that will involve different tables or different data types each
1109      time they are executed.  <application>PL/pgSQL</application>'s
1110      normal attempts to cache plans for commands (as discussed in
1111      <xref linkend="plpgsql-plan-caching">) will not work in such
1112      scenarios.  To handle this sort of problem, the
1113      <command>EXECUTE</command> statement is provided:
1114
1115 <synopsis>
1116 EXECUTE <replaceable class="command">command-string</replaceable> <optional> INTO <optional>STRICT</optional> <replaceable>target</replaceable> </optional> <optional> USING <replaceable>expression</replaceable> <optional>, ... </optional> </optional>;
1117 </synopsis>
1118
1119      where <replaceable>command-string</replaceable> is an expression
1120      yielding a string (of type <type>text</type>) containing the
1121      command to be executed.  The optional <replaceable>target</replaceable>
1122      is a record variable, a row variable, or a comma-separated list of
1123      simple variables and record/row fields, into which the results of
1124      the command will be stored.  The optional <literal>USING</> expressions
1125      supply values to be inserted into the command.
1126     </para>
1127
1128     <para>
1129      No substitution of <application>PL/pgSQL</> variables is done on the
1130      computed command string.  Any required variable values must be inserted
1131      in the command string as it is constructed; or you can use parameters
1132      as described below.
1133     </para>
1134
1135     <para>
1136      Also, there is no plan caching for commands executed via
1137      <command>EXECUTE</command>.  Instead, the command is always planned
1138      each time the statement is run. Thus the command
1139      string can be dynamically created within the function to perform
1140      actions on different tables and columns.
1141     </para>
1142
1143     <para>
1144      The <literal>INTO</literal> clause specifies where the results of
1145      a SQL command returning rows should be assigned. If a row
1146      or variable list is provided, it must exactly match the structure
1147      of the query's results (when a
1148      record variable is used, it will configure itself to match the
1149      result structure automatically). If multiple rows are returned,
1150      only the first will be assigned to the <literal>INTO</literal>
1151      variable. If no rows are returned, NULL is assigned to the
1152      <literal>INTO</literal> variable(s). If no <literal>INTO</literal>
1153      clause is specified, the query results are discarded.
1154     </para>
1155
1156     <para>
1157      If the <literal>STRICT</> option is given, an error is reported
1158      unless the query produces exactly one row.
1159     </para>
1160
1161     <para>
1162      The command string can use parameter values, which are referenced
1163      in the command as <literal>$1</>, <literal>$2</>, etc.
1164      These symbols refer to values supplied in the <literal>USING</>
1165      clause.  This method is often preferable to inserting data values
1166      into the command string as text: it avoids run-time overhead of
1167      converting the values to text and back, and it is much less prone
1168      to SQL-injection attacks since there is no need for quoting or escaping.
1169      An example is:
1170 <programlisting>
1171 EXECUTE 'SELECT count(*) FROM mytable WHERE inserted_by = $1 AND inserted &lt;= $2'
1172    INTO c
1173    USING checked_user, checked_date;
1174 </programlisting>
1175     </para>
1176
1177     <para>
1178      Note that parameter symbols can only be used for data values
1179      &mdash; if you want to use dynamically determined table or column
1180      names, you must insert them into the command string textually.
1181      For example, if the preceding query needed to be done against a
1182      dynamically selected table, you could do this:
1183 <programlisting>
1184 EXECUTE 'SELECT count(*) FROM '
1185     || tabname::regclass
1186     || ' WHERE inserted_by = $1 AND inserted &lt;= $2'
1187    INTO c
1188    USING checked_user, checked_date;
1189 </programlisting>
1190      Another restriction on parameter symbols is that they only work in
1191      <command>SELECT</>, <command>INSERT</>, <command>UPDATE</>, and
1192      <command>DELETE</> commands.  In other statement
1193      types (generically called utility statements), you must insert
1194      values textually even if they are just data values.
1195     </para>
1196
1197     <para>
1198      An <command>EXECUTE</> with a simple constant command string and some
1199      <literal>USING</> parameters, as in the first example above, is
1200      functionally equivalent to just writing the command directly in
1201      <application>PL/pgSQL</application> and allowing replacement of
1202      <application>PL/pgSQL</application> variables to happen automatically.
1203      The important difference is that <command>EXECUTE</> will re-plan
1204      the command on each execution, generating a plan that is specific
1205      to the current parameter values; whereas
1206      <application>PL/pgSQL</application> may otherwise create a generic plan
1207      and cache it for re-use.  In situations where the best plan depends
1208      strongly on the parameter values, it can be helpful to use
1209      <command>EXECUTE</> to positively ensure that a generic plan is not
1210      selected.
1211     </para>
1212
1213     <para>
1214      <command>SELECT INTO</command> is not currently supported within
1215      <command>EXECUTE</command>; instead, execute a plain <command>SELECT</>
1216      command and specify <literal>INTO</> as part of the <command>EXECUTE</>
1217      itself.
1218     </para>
1219
1220    <note>
1221     <para>
1222      The <application>PL/pgSQL</application>
1223      <command>EXECUTE</command> statement is not related to the
1224      <xref linkend="sql-execute"> SQL
1225      statement supported by the
1226      <productname>PostgreSQL</productname> server. The server's
1227      <command>EXECUTE</command> statement cannot be used directly within
1228      <application>PL/pgSQL</> functions (and is not needed).
1229     </para>
1230    </note>
1231
1232    <example id="plpgsql-quote-literal-example">
1233    <title>Quoting Values In Dynamic Queries</title>
1234
1235     <indexterm>
1236      <primary>quote_ident</primary>
1237      <secondary>use in PL/pgSQL</secondary>
1238     </indexterm>
1239
1240     <indexterm>
1241      <primary>quote_literal</primary>
1242      <secondary>use in PL/pgSQL</secondary>
1243     </indexterm>
1244
1245     <indexterm>
1246      <primary>quote_nullable</primary>
1247      <secondary>use in PL/pgSQL</secondary>
1248     </indexterm>
1249
1250     <indexterm>
1251      <primary>format</primary>
1252      <secondary>use in PL/pgSQL</secondary>
1253     </indexterm>
1254
1255     <para>
1256      When working with dynamic commands you will often have to handle escaping
1257      of single quotes.  The recommended method for quoting fixed text in your
1258      function body is dollar quoting.  (If you have legacy code that does
1259      not use dollar quoting, please refer to the
1260      overview in <xref linkend="plpgsql-quote-tips">, which can save you
1261      some effort when translating said code to a more reasonable scheme.)
1262     </para>
1263
1264     <para>
1265      Dynamic values that are to be inserted into the constructed
1266      query require careful handling since they might themselves contain
1267      quote characters.
1268      An example (this assumes that you are using dollar quoting for the
1269      function as a whole, so the quote marks need not be doubled):
1270 <programlisting>
1271 EXECUTE 'UPDATE tbl SET '
1272         || quote_ident(colname)
1273         || ' = '
1274         || quote_literal(newvalue)
1275         || ' WHERE key = '
1276         || quote_literal(keyvalue);
1277 </programlisting>
1278     </para>
1279
1280     <para>
1281      This example demonstrates the use of the
1282      <function>quote_ident</function> and
1283      <function>quote_literal</function> functions (see <xref
1284      linkend="functions-string">).  For safety, expressions containing column
1285      or table identifiers should be passed through
1286      <function>quote_ident</function> before insertion in a dynamic query.
1287      Expressions containing values that should be literal strings in the
1288      constructed command should be passed through <function>quote_literal</>.
1289      These functions take the appropriate steps to return the input text
1290      enclosed in double or single quotes respectively, with any embedded
1291      special characters properly escaped.
1292     </para>
1293
1294     <para>
1295      Because <function>quote_literal</function> is labelled
1296      <literal>STRICT</literal>, it will always return null when called with a
1297      null argument.  In the above example, if <literal>newvalue</> or
1298      <literal>keyvalue</> were null, the entire dynamic query string would
1299      become null, leading to an error from <command>EXECUTE</command>.
1300      You can avoid this problem by using the <function>quote_nullable</>
1301      function, which works the same as <function>quote_literal</> except that
1302      when called with a null argument it returns the string <literal>NULL</>.
1303      For example,
1304 <programlisting>
1305 EXECUTE 'UPDATE tbl SET '
1306         || quote_ident(colname)
1307         || ' = '
1308         || quote_nullable(newvalue)
1309         || ' WHERE key = '
1310         || quote_nullable(keyvalue);
1311 </programlisting>
1312      If you are dealing with values that might be null, you should usually
1313      use <function>quote_nullable</> in place of <function>quote_literal</>.
1314     </para>
1315
1316     <para>
1317      As always, care must be taken to ensure that null values in a query do
1318      not deliver unintended results.  For example the <literal>WHERE</> clause
1319 <programlisting>
1320 'WHERE key = ' || quote_nullable(keyvalue)
1321 </programlisting>
1322      will never succeed if <literal>keyvalue</> is null, because the
1323      result of using the equality operator <literal>=</> with a null operand
1324      is always null.  If you wish null to work like an ordinary key value,
1325      you would need to rewrite the above as
1326 <programlisting>
1327 'WHERE key IS NOT DISTINCT FROM ' || quote_nullable(keyvalue)
1328 </programlisting>
1329      (At present, <literal>IS NOT DISTINCT FROM</> is handled much less
1330      efficiently than <literal>=</>, so don't do this unless you must.
1331      See <xref linkend="functions-comparison"> for
1332      more information on nulls and <literal>IS DISTINCT</>.)
1333     </para>
1334
1335     <para>
1336      Note that dollar quoting is only useful for quoting fixed text.
1337      It would be a very bad idea to try to write this example as:
1338 <programlisting>
1339 EXECUTE 'UPDATE tbl SET '
1340         || quote_ident(colname)
1341         || ' = $$'
1342         || newvalue
1343         || '$$ WHERE key = '
1344         || quote_literal(keyvalue);
1345 </programlisting>
1346      because it would break if the contents of <literal>newvalue</>
1347      happened to contain <literal>$$</>.  The same objection would
1348      apply to any other dollar-quoting delimiter you might pick.
1349      So, to safely quote text that is not known in advance, you
1350      <emphasis>must</> use <function>quote_literal</>,
1351      <function>quote_nullable</>, or <function>quote_ident</>, as appropriate.
1352     </para>
1353
1354     <para>
1355      Dynamic SQL statements can also be safely constructed using the
1356      <function>format</function> function (see <xref
1357      linkend="functions-string">). For example:
1358 <programlisting>
1359 EXECUTE format('UPDATE tbl SET %I = %L WHERE key = %L', colname, newvalue, keyvalue);
1360 </programlisting>
1361      The <function>format</function> function can be used in conjunction with
1362      the <literal>USING</literal> clause:
1363 <programlisting>
1364 EXECUTE format('UPDATE tbl SET %I = $1 WHERE key = $2', colname)
1365    USING newvalue, keyvalue;
1366 </programlisting>
1367      This form is more efficient, because the parameters
1368      <literal>newvalue</literal> and <literal>keyvalue</literal> are not
1369      converted to text.
1370     </para>
1371    </example>
1372
1373     <para>
1374      A much larger example of a dynamic command and
1375      <command>EXECUTE</command> can be seen in <xref
1376      linkend="plpgsql-porting-ex2">, which builds and executes a
1377      <command>CREATE FUNCTION</> command to define a new function.
1378     </para>
1379    </sect2>
1380
1381    <sect2 id="plpgsql-statements-diagnostics">
1382     <title>Obtaining the Result Status</title>
1383
1384     <para>
1385      There are several ways to determine the effect of a command. The
1386      first method is to use the <command>GET DIAGNOSTICS</command>
1387      command, which has the form:
1388
1389 <synopsis>
1390 GET <optional> CURRENT </optional> DIAGNOSTICS <replaceable>variable</replaceable> = <replaceable>item</replaceable> <optional> , ... </optional>;
1391 </synopsis>
1392
1393      This command allows retrieval of system status indicators.  Each
1394      <replaceable>item</replaceable> is a key word identifying a status
1395      value to be assigned to the specified variable (which should be
1396      of the right data type to receive it).  The currently available
1397      status items are <varname>ROW_COUNT</>, the number of rows
1398      processed by the last <acronym>SQL</acronym> command sent to
1399      the <acronym>SQL</acronym> engine, and <varname>RESULT_OID</>,
1400      the OID of the last row inserted by the most recent
1401      <acronym>SQL</acronym> command.  Note that <varname>RESULT_OID</>
1402      is only useful after an <command>INSERT</command> command into a
1403      table containing OIDs.
1404     </para>
1405
1406     <para>
1407      An example:
1408 <programlisting>
1409 GET DIAGNOSTICS integer_var = ROW_COUNT;
1410 </programlisting>
1411     </para>
1412
1413     <para>
1414      The second method to determine the effects of a command is to check the
1415      special variable named <literal>FOUND</literal>, which is of
1416      type <type>boolean</type>.  <literal>FOUND</literal> starts out
1417      false within each <application>PL/pgSQL</application> function call.
1418      It is set by each of the following types of statements:
1419
1420          <itemizedlist>
1421           <listitem>
1422            <para>
1423             A <command>SELECT INTO</command> statement sets
1424             <literal>FOUND</literal> true if a row is assigned, false if no
1425             row is returned.
1426            </para>
1427           </listitem>
1428           <listitem>
1429            <para>
1430             A <command>PERFORM</> statement sets <literal>FOUND</literal>
1431             true if it produces (and discards) one or more rows, false if
1432             no row is produced.
1433            </para>
1434           </listitem>
1435           <listitem>
1436            <para>
1437             <command>UPDATE</>, <command>INSERT</>, and <command>DELETE</>
1438             statements set <literal>FOUND</literal> true if at least one
1439             row is affected, false if no row is affected.
1440            </para>
1441           </listitem>
1442           <listitem>
1443            <para>
1444             A <command>FETCH</> statement sets <literal>FOUND</literal>
1445             true if it returns a row, false if no row is returned.
1446            </para>
1447           </listitem>
1448           <listitem>
1449            <para>
1450             A <command>MOVE</> statement sets <literal>FOUND</literal>
1451             true if it successfully repositions the cursor, false otherwise.
1452            </para>
1453           </listitem>
1454           <listitem>
1455            <para>
1456             A <command>FOR</> or <command>FOREACH</> statement sets
1457             <literal>FOUND</literal> true
1458             if it iterates one or more times, else false.
1459             <literal>FOUND</literal> is set this way when the
1460             loop exits; inside the execution of the loop,
1461             <literal>FOUND</literal> is not modified by the
1462             loop statement, although it might be changed by the
1463             execution of other statements within the loop body.
1464            </para>
1465           </listitem>
1466           <listitem>
1467            <para>
1468             <command>RETURN QUERY</command> and <command>RETURN QUERY
1469             EXECUTE</command> statements set <literal>FOUND</literal>
1470             true if the query returns at least one row, false if no row
1471             is returned.
1472            </para>
1473           </listitem>
1474          </itemizedlist>
1475
1476      Other <application>PL/pgSQL</application> statements do not change
1477      the state of <literal>FOUND</literal>.
1478      Note in particular that <command>EXECUTE</command>
1479      changes the output of <command>GET DIAGNOSTICS</command>, but
1480      does not change <literal>FOUND</literal>.
1481     </para>
1482
1483     <para>
1484      <literal>FOUND</literal> is a local variable within each
1485      <application>PL/pgSQL</application> function; any changes to it
1486      affect only the current function.
1487     </para>
1488
1489    </sect2>
1490
1491    <sect2 id="plpgsql-statements-null">
1492     <title>Doing Nothing At All</title>
1493
1494     <para>
1495      Sometimes a placeholder statement that does nothing is useful.
1496      For example, it can indicate that one arm of an if/then/else
1497      chain is deliberately empty.  For this purpose, use the
1498      <command>NULL</command> statement:
1499
1500 <synopsis>
1501 NULL;
1502 </synopsis>
1503     </para>
1504
1505     <para>
1506      For example, the following two fragments of code are equivalent:
1507 <programlisting>
1508 BEGIN
1509     y := x / 0;
1510 EXCEPTION
1511     WHEN division_by_zero THEN
1512         NULL;  -- ignore the error
1513 END;
1514 </programlisting>
1515
1516 <programlisting>
1517 BEGIN
1518     y := x / 0;
1519 EXCEPTION
1520     WHEN division_by_zero THEN  -- ignore the error
1521 END;
1522 </programlisting>
1523      Which is preferable is a matter of taste.
1524     </para>
1525
1526     <note>
1527      <para>
1528       In Oracle's PL/SQL, empty statement lists are not allowed, and so
1529       <command>NULL</> statements are <emphasis>required</> for situations
1530       such as this.  <application>PL/pgSQL</application> allows you to
1531       just write nothing, instead.
1532      </para>
1533     </note>
1534
1535    </sect2>
1536   </sect1>
1537
1538   <sect1 id="plpgsql-control-structures">
1539    <title>Control Structures</title>
1540
1541    <para>
1542     Control structures are probably the most useful (and
1543     important) part of <application>PL/pgSQL</>. With
1544     <application>PL/pgSQL</>'s control structures,
1545     you can manipulate <productname>PostgreSQL</> data in a very
1546     flexible and powerful way.
1547    </para>
1548
1549    <sect2 id="plpgsql-statements-returning">
1550     <title>Returning From a Function</title>
1551
1552     <para>
1553      There are two commands available that allow you to return data
1554      from a function: <command>RETURN</command> and <command>RETURN
1555      NEXT</command>.
1556     </para>
1557
1558     <sect3>
1559      <title><command>RETURN</></title>
1560
1561 <synopsis>
1562 RETURN <replaceable>expression</replaceable>;
1563 </synopsis>
1564
1565      <para>
1566       <command>RETURN</command> with an expression terminates the
1567       function and returns the value of
1568       <replaceable>expression</replaceable> to the caller.  This form
1569       is used for <application>PL/pgSQL</> functions that do
1570       not return a set.
1571      </para>
1572
1573      <para>
1574       In a function that returns a scalar type, the expression's result will
1575       automatically be cast into the function's return type as described for
1576       assignments.  But to return a composite (row) value, you must write an
1577       expression delivering exactly the requested column set.  This may
1578       require use of explicit casting.
1579      </para>
1580
1581      <para>
1582       If you declared the function with output parameters, write just
1583       <command>RETURN</command> with no expression.  The current values
1584       of the output parameter variables will be returned.
1585      </para>
1586
1587      <para>
1588       If you declared the function to return <type>void</type>, a
1589       <command>RETURN</command> statement can be used to exit the function
1590       early; but do not write an expression following
1591       <command>RETURN</command>.
1592      </para>
1593
1594      <para>
1595       The return value of a function cannot be left undefined. If
1596       control reaches the end of the top-level block of the function
1597       without hitting a <command>RETURN</command> statement, a run-time
1598       error will occur.  This restriction does not apply to functions
1599       with output parameters and functions returning <type>void</type>,
1600       however.  In those cases a <command>RETURN</command> statement is
1601       automatically executed if the top-level block finishes.
1602      </para>
1603
1604      <para>
1605       Some examples:
1606
1607 <programlisting>
1608 -- functions returning a scalar type
1609 RETURN 1 + 2;
1610 RETURN scalar_var;
1611
1612 -- functions returning a composite type
1613 RETURN composite_type_var;
1614 RETURN (1, 2, 'three'::text);  -- must cast columns to correct types
1615 </programlisting>
1616      </para>
1617     </sect3>
1618
1619     <sect3>
1620      <title><command>RETURN NEXT</> and <command>RETURN QUERY</command></title>
1621     <indexterm>
1622      <primary>RETURN NEXT</primary>
1623      <secondary>in PL/pgSQL</secondary>
1624     </indexterm>
1625     <indexterm>
1626      <primary>RETURN QUERY</primary>
1627      <secondary>in PL/pgSQL</secondary>
1628     </indexterm>
1629
1630 <synopsis>
1631 RETURN NEXT <replaceable>expression</replaceable>;
1632 RETURN QUERY <replaceable>query</replaceable>;
1633 RETURN QUERY EXECUTE <replaceable class="command">command-string</replaceable> <optional> USING <replaceable>expression</replaceable> <optional>, ... </optional> </optional>;
1634 </synopsis>
1635
1636      <para>
1637       When a <application>PL/pgSQL</> function is declared to return
1638       <literal>SETOF <replaceable>sometype</></literal>, the procedure
1639       to follow is slightly different.  In that case, the individual
1640       items to return are specified by a sequence of <command>RETURN
1641       NEXT</command> or <command>RETURN QUERY</command> commands, and
1642       then a final <command>RETURN</command> command with no argument
1643       is used to indicate that the function has finished executing.
1644       <command>RETURN NEXT</command> can be used with both scalar and
1645       composite data types; with a composite result type, an entire
1646       <quote>table</quote> of results will be returned.
1647       <command>RETURN QUERY</command> appends the results of executing
1648       a query to the function's result set. <command>RETURN
1649       NEXT</command> and <command>RETURN QUERY</command> can be freely
1650       intermixed in a single set-returning function, in which case
1651       their results will be concatenated.
1652      </para>
1653
1654      <para>
1655       <command>RETURN NEXT</command> and <command>RETURN
1656       QUERY</command> do not actually return from the function &mdash;
1657       they simply append zero or more rows to the function's result
1658       set.  Execution then continues with the next statement in the
1659       <application>PL/pgSQL</> function.  As successive
1660       <command>RETURN NEXT</command> or <command>RETURN
1661       QUERY</command> commands are executed, the result set is built
1662       up.  A final <command>RETURN</command>, which should have no
1663       argument, causes control to exit the function (or you can just
1664       let control reach the end of the function).
1665      </para>
1666
1667      <para>
1668       <command>RETURN QUERY</command> has a variant
1669       <command>RETURN QUERY EXECUTE</command>, which specifies the
1670       query to be executed dynamically.  Parameter expressions can
1671       be inserted into the computed query string via <literal>USING</>,
1672       in just the same way as in the <command>EXECUTE</> command.
1673      </para>
1674
1675      <para>
1676       If you declared the function with output parameters, write just
1677       <command>RETURN NEXT</command> with no expression.  On each
1678       execution, the current values of the output parameter
1679       variable(s) will be saved for eventual return as a row of the
1680       result.  Note that you must declare the function as returning
1681       <literal>SETOF record</literal> when there are multiple output
1682       parameters, or <literal>SETOF <replaceable>sometype</></literal>
1683       when there is just one output parameter of type
1684       <replaceable>sometype</>, in order to create a set-returning
1685       function with output parameters.
1686      </para>
1687
1688      <para>
1689       Here is an example of a function using <command>RETURN
1690       NEXT</command>:
1691
1692 <programlisting>
1693 CREATE TABLE foo (fooid INT, foosubid INT, fooname TEXT);
1694 INSERT INTO foo VALUES (1, 2, 'three');
1695 INSERT INTO foo VALUES (4, 5, 'six');
1696
1697 CREATE OR REPLACE FUNCTION getAllFoo() RETURNS SETOF foo AS
1698 $BODY$
1699 DECLARE
1700     r foo%rowtype;
1701 BEGIN
1702     FOR r IN SELECT * FROM foo
1703     WHERE fooid &gt; 0
1704     LOOP
1705         -- can do some processing here
1706         RETURN NEXT r; -- return current row of SELECT
1707     END LOOP;
1708     RETURN;
1709 END
1710 $BODY$
1711 LANGUAGE 'plpgsql' ;
1712
1713 SELECT * FROM getallfoo();
1714 </programlisting>
1715      </para>
1716
1717      <note>
1718       <para>
1719        The current implementation of <command>RETURN NEXT</command>
1720        and <command>RETURN QUERY</command> stores the entire result set
1721        before returning from the function, as discussed above.  That
1722        means that if a <application>PL/pgSQL</> function produces a
1723        very large result set, performance might be poor: data will be
1724        written to disk to avoid memory exhaustion, but the function
1725        itself will not return until the entire result set has been
1726        generated.  A future version of <application>PL/pgSQL</> might
1727        allow users to define set-returning functions
1728        that do not have this limitation.  Currently, the point at
1729        which data begins being written to disk is controlled by the
1730        <xref linkend="guc-work-mem">
1731        configuration variable.  Administrators who have sufficient
1732        memory to store larger result sets in memory should consider
1733        increasing this parameter.
1734       </para>
1735      </note>
1736     </sect3>
1737    </sect2>
1738
1739    <sect2 id="plpgsql-conditionals">
1740     <title>Conditionals</title>
1741
1742     <para>
1743      <command>IF</> and <command>CASE</> statements let you execute
1744      alternative commands based on certain conditions.
1745      <application>PL/pgSQL</> has three forms of <command>IF</>:
1746     <itemizedlist>
1747      <listitem>
1748       <para><literal>IF ... THEN</></>
1749      </listitem>
1750      <listitem>
1751       <para><literal>IF ... THEN ... ELSE</></>
1752      </listitem>
1753      <listitem>
1754       <para><literal>IF ... THEN ... ELSIF ... THEN ... ELSE</></>
1755      </listitem>
1756     </itemizedlist>
1757
1758     and two forms of <command>CASE</>:
1759     <itemizedlist>
1760      <listitem>
1761       <para><literal>CASE ... WHEN ... THEN ... ELSE ... END CASE</></>
1762      </listitem>
1763      <listitem>
1764       <para><literal>CASE WHEN ... THEN ... ELSE ... END CASE</></>
1765      </listitem>
1766     </itemizedlist>
1767     </para>
1768
1769     <sect3>
1770      <title><literal>IF-THEN</></title>
1771
1772 <synopsis>
1773 IF <replaceable>boolean-expression</replaceable> THEN
1774     <replaceable>statements</replaceable>
1775 END IF;
1776 </synopsis>
1777
1778        <para>
1779         <literal>IF-THEN</literal> statements are the simplest form of
1780         <literal>IF</literal>. The statements between
1781         <literal>THEN</literal> and <literal>END IF</literal> will be
1782         executed if the condition is true. Otherwise, they are
1783         skipped.
1784        </para>
1785
1786        <para>
1787         Example:
1788 <programlisting>
1789 IF v_user_id &lt;&gt; 0 THEN
1790     UPDATE users SET email = v_email WHERE user_id = v_user_id;
1791 END IF;
1792 </programlisting>
1793        </para>
1794      </sect3>
1795
1796      <sect3>
1797       <title><literal>IF-THEN-ELSE</></title>
1798
1799 <synopsis>
1800 IF <replaceable>boolean-expression</replaceable> THEN
1801     <replaceable>statements</replaceable>
1802 ELSE
1803     <replaceable>statements</replaceable>
1804 END IF;
1805 </synopsis>
1806
1807        <para>
1808         <literal>IF-THEN-ELSE</literal> statements add to
1809         <literal>IF-THEN</literal> by letting you specify an
1810         alternative set of statements that should be executed if the
1811         condition is not true.  (Note this includes the case where the
1812         condition evaluates to NULL.)
1813        </para>
1814
1815        <para>
1816         Examples:
1817 <programlisting>
1818 IF parentid IS NULL OR parentid = ''
1819 THEN
1820     RETURN fullname;
1821 ELSE
1822     RETURN hp_true_filename(parentid) || '/' || fullname;
1823 END IF;
1824 </programlisting>
1825
1826 <programlisting>
1827 IF v_count &gt; 0 THEN
1828     INSERT INTO users_count (count) VALUES (v_count);
1829     RETURN 't';
1830 ELSE
1831     RETURN 'f';
1832 END IF;
1833 </programlisting>
1834      </para>
1835     </sect3>
1836
1837      <sect3>
1838       <title><literal>IF-THEN-ELSIF</></title>
1839
1840 <synopsis>
1841 IF <replaceable>boolean-expression</replaceable> THEN
1842     <replaceable>statements</replaceable>
1843 <optional> ELSIF <replaceable>boolean-expression</replaceable> THEN
1844     <replaceable>statements</replaceable>
1845 <optional> ELSIF <replaceable>boolean-expression</replaceable> THEN
1846     <replaceable>statements</replaceable>
1847     ...
1848 </optional>
1849 </optional>
1850 <optional> ELSE
1851     <replaceable>statements</replaceable> </optional>
1852 END IF;
1853 </synopsis>
1854
1855        <para>
1856         Sometimes there are more than just two alternatives.
1857         <literal>IF-THEN-ELSIF</> provides a convenient
1858         method of checking several alternatives in turn.
1859         The <literal>IF</> conditions are tested successively
1860         until the first one that is true is found.  Then the
1861         associated statement(s) are executed, after which control
1862         passes to the next statement after <literal>END IF</>.
1863         (Any subsequent <literal>IF</> conditions are <emphasis>not</>
1864         tested.)  If none of the <literal>IF</> conditions is true,
1865         then the <literal>ELSE</> block (if any) is executed.
1866        </para>
1867
1868        <para>
1869         Here is an example:
1870
1871 <programlisting>
1872 IF number = 0 THEN
1873     result := 'zero';
1874 ELSIF number &gt; 0 THEN
1875     result := 'positive';
1876 ELSIF number &lt; 0 THEN
1877     result := 'negative';
1878 ELSE
1879     -- hmm, the only other possibility is that number is null
1880     result := 'NULL';
1881 END IF;
1882 </programlisting>
1883        </para>
1884
1885        <para>
1886         The key word <literal>ELSIF</> can also be spelled
1887         <literal>ELSEIF</>.
1888        </para>
1889
1890        <para>
1891         An alternative way of accomplishing the same task is to nest
1892         <literal>IF-THEN-ELSE</literal> statements, as in the
1893         following example:
1894
1895 <programlisting>
1896 IF demo_row.sex = 'm' THEN
1897     pretty_sex := 'man';
1898 ELSE
1899     IF demo_row.sex = 'f' THEN
1900         pretty_sex := 'woman';
1901     END IF;
1902 END IF;
1903 </programlisting>
1904        </para>
1905
1906        <para>
1907         However, this method requires writing a matching <literal>END IF</>
1908         for each <literal>IF</>, so it is much more cumbersome than
1909         using <literal>ELSIF</> when there are many alternatives.
1910        </para>
1911      </sect3>
1912
1913      <sect3>
1914       <title>Simple <literal>CASE</></title>
1915
1916 <synopsis>
1917 CASE <replaceable>search-expression</replaceable>
1918     WHEN <replaceable>expression</replaceable> <optional>, <replaceable>expression</replaceable> <optional> ... </optional></optional> THEN
1919       <replaceable>statements</replaceable>
1920   <optional> WHEN <replaceable>expression</replaceable> <optional>, <replaceable>expression</replaceable> <optional> ... </optional></optional> THEN
1921       <replaceable>statements</replaceable>
1922     ... </optional>
1923   <optional> ELSE
1924       <replaceable>statements</replaceable> </optional>
1925 END CASE;
1926 </synopsis>
1927
1928       <para>
1929        The simple form of <command>CASE</> provides conditional execution
1930        based on equality of operands.  The <replaceable>search-expression</>
1931        is evaluated (once) and successively compared to each
1932        <replaceable>expression</> in the <literal>WHEN</> clauses.
1933        If a match is found, then the corresponding
1934        <replaceable>statements</replaceable> are executed, and then control
1935        passes to the next statement after <literal>END CASE</>.  (Subsequent
1936        <literal>WHEN</> expressions are not evaluated.)  If no match is
1937        found, the <literal>ELSE</> <replaceable>statements</replaceable> are
1938        executed; but if <literal>ELSE</> is not present, then a
1939        <literal>CASE_NOT_FOUND</literal> exception is raised.
1940       </para>
1941
1942       <para>
1943        Here is a simple example:
1944
1945 <programlisting>
1946 CASE x
1947     WHEN 1, 2 THEN
1948         msg := 'one or two';
1949     ELSE
1950         msg := 'other value than one or two';
1951 END CASE;
1952 </programlisting>
1953       </para>
1954      </sect3>
1955
1956      <sect3>
1957       <title>Searched <literal>CASE</></title>
1958
1959 <synopsis>
1960 CASE
1961     WHEN <replaceable>boolean-expression</replaceable> THEN
1962       <replaceable>statements</replaceable>
1963   <optional> WHEN <replaceable>boolean-expression</replaceable> THEN
1964       <replaceable>statements</replaceable>
1965     ... </optional>
1966   <optional> ELSE
1967       <replaceable>statements</replaceable> </optional>
1968 END CASE;
1969 </synopsis>
1970
1971       <para>
1972        The searched form of <command>CASE</> provides conditional execution
1973        based on truth of Boolean expressions.  Each <literal>WHEN</> clause's
1974        <replaceable>boolean-expression</replaceable> is evaluated in turn,
1975        until one is found that yields <literal>true</>.  Then the
1976        corresponding <replaceable>statements</replaceable> are executed, and
1977        then control passes to the next statement after <literal>END CASE</>.
1978        (Subsequent <literal>WHEN</> expressions are not evaluated.)
1979        If no true result is found, the <literal>ELSE</>
1980        <replaceable>statements</replaceable> are executed;
1981        but if <literal>ELSE</> is not present, then a
1982        <literal>CASE_NOT_FOUND</literal> exception is raised.
1983       </para>
1984
1985       <para>
1986        Here is an example:
1987
1988 <programlisting>
1989 CASE
1990     WHEN x BETWEEN 0 AND 10 THEN
1991         msg := 'value is between zero and ten';
1992     WHEN x BETWEEN 11 AND 20 THEN
1993         msg := 'value is between eleven and twenty';
1994 END CASE;
1995 </programlisting>
1996       </para>
1997
1998       <para>
1999        This form of <command>CASE</> is entirely equivalent to
2000        <literal>IF-THEN-ELSIF</>, except for the rule that reaching
2001        an omitted <literal>ELSE</> clause results in an error rather
2002        than doing nothing.
2003       </para>
2004
2005      </sect3>
2006    </sect2>
2007
2008    <sect2 id="plpgsql-control-structures-loops">
2009     <title>Simple Loops</title>
2010
2011     <indexterm zone="plpgsql-control-structures-loops">
2012      <primary>loop</primary>
2013      <secondary>in PL/pgSQL</secondary>
2014     </indexterm>
2015
2016     <para>
2017      With the <literal>LOOP</>, <literal>EXIT</>,
2018      <literal>CONTINUE</>, <literal>WHILE</>, <literal>FOR</>,
2019      and <literal>FOREACH</> statements, you can arrange for your
2020      <application>PL/pgSQL</> function to repeat a series of commands.
2021     </para>
2022
2023     <sect3>
2024      <title><literal>LOOP</></title>
2025
2026 <synopsis>
2027 <optional> &lt;&lt;<replaceable>label</replaceable>&gt;&gt; </optional>
2028 LOOP
2029     <replaceable>statements</replaceable>
2030 END LOOP <optional> <replaceable>label</replaceable> </optional>;
2031 </synopsis>
2032
2033      <para>
2034       <literal>LOOP</> defines an unconditional loop that is repeated
2035       indefinitely until terminated by an <literal>EXIT</> or
2036       <command>RETURN</command> statement.  The optional
2037       <replaceable>label</replaceable> can be used by <literal>EXIT</>
2038       and <literal>CONTINUE</literal> statements within nested loops to
2039       specify which loop those statements refer to.
2040      </para>
2041     </sect3>
2042
2043      <sect3>
2044       <title><literal>EXIT</></title>
2045
2046      <indexterm>
2047       <primary>EXIT</primary>
2048       <secondary>in PL/pgSQL</secondary>
2049      </indexterm>
2050
2051 <synopsis>
2052 EXIT <optional> <replaceable>label</replaceable> </optional> <optional> WHEN <replaceable>boolean-expression</replaceable> </optional>;
2053 </synopsis>
2054
2055        <para>
2056         If no <replaceable>label</replaceable> is given, the innermost
2057         loop is terminated and the statement following <literal>END
2058         LOOP</> is executed next.  If <replaceable>label</replaceable>
2059         is given, it must be the label of the current or some outer
2060         level of nested loop or block. Then the named loop or block is
2061         terminated and control continues with the statement after the
2062         loop's/block's corresponding <literal>END</>.
2063        </para>
2064
2065        <para>
2066         If <literal>WHEN</> is specified, the loop exit occurs only if
2067         <replaceable>boolean-expression</> is true. Otherwise, control passes
2068         to the statement after <literal>EXIT</>.
2069        </para>
2070
2071        <para>
2072         <literal>EXIT</> can be used with all types of loops; it is
2073         not limited to use with unconditional loops.
2074        </para>
2075
2076        <para>
2077         When used with a
2078         <literal>BEGIN</literal> block, <literal>EXIT</literal> passes
2079         control to the next statement after the end of the block.
2080         Note that a label must be used for this purpose; an unlabelled
2081         <literal>EXIT</literal> is never considered to match a
2082         <literal>BEGIN</literal> block.  (This is a change from
2083         pre-8.4 releases of <productname>PostgreSQL</productname>, which
2084         would allow an unlabelled <literal>EXIT</literal> to match
2085         a <literal>BEGIN</literal> block.)
2086        </para>
2087
2088        <para>
2089         Examples:
2090 <programlisting>
2091 LOOP
2092     -- some computations
2093     IF count &gt; 0 THEN
2094         EXIT;  -- exit loop
2095     END IF;
2096 END LOOP;
2097
2098 LOOP
2099     -- some computations
2100     EXIT WHEN count &gt; 0;  -- same result as previous example
2101 END LOOP;
2102
2103 &lt;&lt;ablock&gt;&gt;
2104 BEGIN
2105     -- some computations
2106     IF stocks &gt; 100000 THEN
2107         EXIT ablock;  -- causes exit from the BEGIN block
2108     END IF;
2109     -- computations here will be skipped when stocks &gt; 100000
2110 END;
2111 </programlisting>
2112        </para>
2113      </sect3>
2114
2115      <sect3>
2116       <title><literal>CONTINUE</></title>
2117
2118      <indexterm>
2119       <primary>CONTINUE</primary>
2120       <secondary>in PL/pgSQL</secondary>
2121      </indexterm>
2122
2123 <synopsis>
2124 CONTINUE <optional> <replaceable>label</replaceable> </optional> <optional> WHEN <replaceable>boolean-expression</replaceable> </optional>;
2125 </synopsis>
2126
2127        <para>
2128         If no <replaceable>label</> is given, the next iteration of
2129         the innermost loop is begun. That is, all statements remaining
2130         in the loop body are skipped, and control returns
2131         to the loop control expression (if any) to determine whether
2132         another loop iteration is needed.
2133         If <replaceable>label</> is present, it
2134         specifies the label of the loop whose execution will be
2135         continued.
2136        </para>
2137
2138        <para>
2139         If <literal>WHEN</> is specified, the next iteration of the
2140         loop is begun only if <replaceable>boolean-expression</> is
2141         true. Otherwise, control passes to the statement after
2142         <literal>CONTINUE</>.
2143        </para>
2144
2145        <para>
2146         <literal>CONTINUE</> can be used with all types of loops; it
2147         is not limited to use with unconditional loops.
2148        </para>
2149
2150        <para>
2151         Examples:
2152 <programlisting>
2153 LOOP
2154     -- some computations
2155     EXIT WHEN count &gt; 100;
2156     CONTINUE WHEN count &lt; 50;
2157     -- some computations for count IN [50 .. 100]
2158 END LOOP;
2159 </programlisting>
2160        </para>
2161      </sect3>
2162
2163
2164      <sect3>
2165       <title><literal>WHILE</></title>
2166
2167      <indexterm>
2168       <primary>WHILE</primary>
2169       <secondary>in PL/pgSQL</secondary>
2170      </indexterm>
2171
2172 <synopsis>
2173 <optional> &lt;&lt;<replaceable>label</replaceable>&gt;&gt; </optional>
2174 WHILE <replaceable>boolean-expression</replaceable> LOOP
2175     <replaceable>statements</replaceable>
2176 END LOOP <optional> <replaceable>label</replaceable> </optional>;
2177 </synopsis>
2178
2179        <para>
2180         The <literal>WHILE</> statement repeats a
2181         sequence of statements so long as the
2182         <replaceable>boolean-expression</replaceable>
2183         evaluates to true.  The expression is checked just before
2184         each entry to the loop body.
2185        </para>
2186
2187        <para>
2188         For example:
2189 <programlisting>
2190 WHILE amount_owed &gt; 0 AND gift_certificate_balance &gt; 0 LOOP
2191     -- some computations here
2192 END LOOP;
2193
2194 WHILE NOT done LOOP
2195     -- some computations here
2196 END LOOP;
2197 </programlisting>
2198        </para>
2199      </sect3>
2200
2201      <sect3 id="plpgsql-integer-for">
2202       <title><literal>FOR</> (Integer Variant)</title>
2203
2204 <synopsis>
2205 <optional> &lt;&lt;<replaceable>label</replaceable>&gt;&gt; </optional>
2206 FOR <replaceable>name</replaceable> IN <optional> REVERSE </optional> <replaceable>expression</replaceable> .. <replaceable>expression</replaceable> <optional> BY <replaceable>expression</replaceable> </optional> LOOP
2207     <replaceable>statements</replaceable>
2208 END LOOP <optional> <replaceable>label</replaceable> </optional>;
2209 </synopsis>
2210
2211        <para>
2212         This form of <literal>FOR</> creates a loop that iterates over a range
2213         of integer values. The variable
2214         <replaceable>name</replaceable> is automatically defined as type
2215         <type>integer</> and exists only inside the loop (any existing
2216         definition of the variable name is ignored within the loop).
2217         The two expressions giving
2218         the lower and upper bound of the range are evaluated once when entering
2219         the loop. If the <literal>BY</> clause isn't specified the iteration
2220         step is 1, otherwise it's the value specified in the <literal>BY</>
2221         clause, which again is evaluated once on loop entry.
2222         If <literal>REVERSE</> is specified then the step value is
2223         subtracted, rather than added, after each iteration.
2224        </para>
2225
2226        <para>
2227         Some examples of integer <literal>FOR</> loops:
2228 <programlisting>
2229 FOR i IN 1..10 LOOP
2230     -- i will take on the values 1,2,3,4,5,6,7,8,9,10 within the loop
2231 END LOOP;
2232
2233 FOR i IN REVERSE 10..1 LOOP
2234     -- i will take on the values 10,9,8,7,6,5,4,3,2,1 within the loop
2235 END LOOP;
2236
2237 FOR i IN REVERSE 10..1 BY 2 LOOP
2238     -- i will take on the values 10,8,6,4,2 within the loop
2239 END LOOP;
2240 </programlisting>
2241        </para>
2242
2243        <para>
2244         If the lower bound is greater than the upper bound (or less than,
2245         in the <literal>REVERSE</> case), the loop body is not
2246         executed at all.  No error is raised.
2247        </para>
2248
2249        <para>
2250         If a <replaceable>label</replaceable> is attached to the
2251         <literal>FOR</> loop then the integer loop variable can be
2252         referenced with a qualified name, using that
2253         <replaceable>label</replaceable>.
2254        </para>
2255      </sect3>
2256    </sect2>
2257
2258    <sect2 id="plpgsql-records-iterating">
2259     <title>Looping Through Query Results</title>
2260
2261     <para>
2262      Using a different type of <literal>FOR</> loop, you can iterate through
2263      the results of a query and manipulate that data
2264      accordingly. The syntax is:
2265 <synopsis>
2266 <optional> &lt;&lt;<replaceable>label</replaceable>&gt;&gt; </optional>
2267 FOR <replaceable>target</replaceable> IN <replaceable>query</replaceable> LOOP
2268     <replaceable>statements</replaceable>
2269 END LOOP <optional> <replaceable>label</replaceable> </optional>;
2270 </synopsis>
2271      The <replaceable>target</replaceable> is a record variable, row variable,
2272      or comma-separated list of scalar variables.
2273      The <replaceable>target</replaceable> is successively assigned each row
2274      resulting from the <replaceable>query</replaceable> and the loop body is
2275      executed for each row. Here is an example:
2276 <programlisting>
2277 CREATE FUNCTION cs_refresh_mviews() RETURNS integer AS $$
2278 DECLARE
2279     mviews RECORD;
2280 BEGIN
2281     RAISE NOTICE 'Refreshing materialized views...';
2282
2283     FOR mviews IN SELECT * FROM cs_materialized_views ORDER BY sort_key LOOP
2284
2285         -- Now "mviews" has one record from cs_materialized_views
2286
2287         RAISE NOTICE 'Refreshing materialized view %s ...', quote_ident(mviews.mv_name);
2288         EXECUTE 'TRUNCATE TABLE ' || quote_ident(mviews.mv_name);
2289         EXECUTE 'INSERT INTO '
2290                    || quote_ident(mviews.mv_name) || ' '
2291                    || mviews.mv_query;
2292     END LOOP;
2293
2294     RAISE NOTICE 'Done refreshing materialized views.';
2295     RETURN 1;
2296 END;
2297 $$ LANGUAGE plpgsql;
2298 </programlisting>
2299
2300      If the loop is terminated by an <literal>EXIT</> statement, the last
2301      assigned row value is still accessible after the loop.
2302     </para>
2303
2304     <para>
2305      The <replaceable>query</replaceable> used in this type of <literal>FOR</>
2306      statement can be any SQL command that returns rows to the caller:
2307      <command>SELECT</> is the most common case,
2308      but you can also use <command>INSERT</>, <command>UPDATE</>, or
2309      <command>DELETE</> with a <literal>RETURNING</> clause.  Some utility
2310      commands such as <command>EXPLAIN</> will work too.
2311     </para>
2312
2313     <para>
2314      <application>PL/pgSQL</> variables are substituted into the query text,
2315      and the query plan is cached for possible re-use, as discussed in
2316      detail in <xref linkend="plpgsql-var-subst"> and
2317      <xref linkend="plpgsql-plan-caching">.
2318     </para>
2319
2320     <para>
2321      The <literal>FOR-IN-EXECUTE</> statement is another way to iterate over
2322      rows:
2323 <synopsis>
2324 <optional> &lt;&lt;<replaceable>label</replaceable>&gt;&gt; </optional>
2325 FOR <replaceable>target</replaceable> IN EXECUTE <replaceable>text_expression</replaceable> <optional> USING <replaceable>expression</replaceable> <optional>, ... </optional> </optional> LOOP
2326     <replaceable>statements</replaceable>
2327 END LOOP <optional> <replaceable>label</replaceable> </optional>;
2328 </synopsis>
2329      This is like the previous form, except that the source query
2330      is specified as a string expression, which is evaluated and replanned
2331      on each entry to the <literal>FOR</> loop.  This allows the programmer to
2332      choose the speed of a preplanned query or the flexibility of a dynamic
2333      query, just as with a plain <command>EXECUTE</command> statement.
2334      As with <command>EXECUTE</command>, parameter values can be inserted
2335      into the dynamic command via <literal>USING</>.
2336     </para>
2337
2338     <para>
2339      Another way to specify the query whose results should be iterated
2340      through is to declare it as a cursor.  This is described in
2341      <xref linkend="plpgsql-cursor-for-loop">.
2342     </para>
2343    </sect2>
2344
2345    <sect2 id="plpgsql-foreach-array">
2346     <title>Looping Through Arrays</title>
2347
2348     <para>
2349      The <literal>FOREACH</> loop is much like a <literal>FOR</> loop,
2350      but instead of iterating through the rows returned by a SQL query,
2351      it iterates through the elements of an array value.
2352      (In general, <literal>FOREACH</> is meant for looping through
2353      components of a composite-valued expression; variants for looping
2354      through composites besides arrays may be added in future.)
2355      The <literal>FOREACH</> statement to loop over an array is:
2356
2357 <synopsis>
2358 <optional> &lt;&lt;<replaceable>label</replaceable>&gt;&gt; </optional>
2359 FOREACH <replaceable>target</replaceable> <optional> SLICE <replaceable>number</replaceable> </optional> IN ARRAY <replaceable>expression</replaceable> LOOP
2360     <replaceable>statements</replaceable>
2361 END LOOP <optional> <replaceable>label</replaceable> </optional>;
2362 </synopsis>
2363     </para>
2364
2365     <para>
2366      Without <literal>SLICE</>, or if <literal>SLICE 0</> is specified,
2367      the loop iterates through individual elements of the array produced
2368      by evaluating the <replaceable>expression</replaceable>.
2369      The <replaceable>target</replaceable> variable is assigned each
2370      element value in sequence, and the loop body is executed for each element.
2371      Here is an example of looping through the elements of an integer
2372      array:
2373
2374 <programlisting>
2375 CREATE FUNCTION sum(int[]) RETURNS int8 AS $$
2376 DECLARE
2377   s int8 := 0;
2378   x int;
2379 BEGIN
2380   FOREACH x IN ARRAY $1
2381   LOOP
2382     s := s + x;
2383   END LOOP;
2384   RETURN s;
2385 END;
2386 $$ LANGUAGE plpgsql;
2387 </programlisting>
2388
2389      The elements are visited in storage order, regardless of the number of
2390      array dimensions.  Although the <replaceable>target</replaceable> is
2391      usually just a single variable, it can be a list of variables when
2392      looping through an array of composite values (records).  In that case,
2393      for each array element, the variables are assigned from successive
2394      columns of the composite value.
2395     </para>
2396
2397     <para>
2398      With a positive <literal>SLICE</> value, <literal>FOREACH</>
2399      iterates through slices of the array rather than single elements.
2400      The <literal>SLICE</> value must be an integer constant not larger
2401      than the number of dimensions of the array.  The
2402      <replaceable>target</replaceable> variable must be an array,
2403      and it receives successive slices of the array value, where each slice
2404      is of the number of dimensions specified by <literal>SLICE</>.
2405      Here is an example of iterating through one-dimensional slices:
2406
2407 <programlisting>
2408 CREATE FUNCTION scan_rows(int[]) RETURNS void AS $$
2409 DECLARE
2410   x int[];
2411 BEGIN
2412   FOREACH x SLICE 1 IN ARRAY $1
2413   LOOP
2414     RAISE NOTICE 'row = %', x;
2415   END LOOP;
2416 END;
2417 $$ LANGUAGE plpgsql;
2418
2419 SELECT scan_rows(ARRAY[[1,2,3],[4,5,6],[7,8,9],[10,11,12]]);
2420
2421 NOTICE:  row = {1,2,3}
2422 NOTICE:  row = {4,5,6}
2423 NOTICE:  row = {7,8,9}
2424 NOTICE:  row = {10,11,12}
2425 </programlisting>
2426     </para>
2427    </sect2>
2428
2429    <sect2 id="plpgsql-error-trapping">
2430     <title>Trapping Errors</title>
2431
2432     <indexterm>
2433      <primary>exceptions</primary>
2434      <secondary>in PL/pgSQL</secondary>
2435     </indexterm>
2436
2437     <para>
2438      By default, any error occurring in a <application>PL/pgSQL</>
2439      function aborts execution of the function, and indeed of the
2440      surrounding transaction as well.  You can trap errors and recover
2441      from them by using a <command>BEGIN</> block with an
2442      <literal>EXCEPTION</> clause.  The syntax is an extension of the
2443      normal syntax for a <command>BEGIN</> block:
2444
2445 <synopsis>
2446 <optional> &lt;&lt;<replaceable>label</replaceable>&gt;&gt; </optional>
2447 <optional> DECLARE
2448     <replaceable>declarations</replaceable> </optional>
2449 BEGIN
2450     <replaceable>statements</replaceable>
2451 EXCEPTION
2452     WHEN <replaceable>condition</replaceable> <optional> OR <replaceable>condition</replaceable> ... </optional> THEN
2453         <replaceable>handler_statements</replaceable>
2454     <optional> WHEN <replaceable>condition</replaceable> <optional> OR <replaceable>condition</replaceable> ... </optional> THEN
2455           <replaceable>handler_statements</replaceable>
2456       ... </optional>
2457 END;
2458 </synopsis>
2459     </para>
2460
2461     <para>
2462      If no error occurs, this form of block simply executes all the
2463      <replaceable>statements</replaceable>, and then control passes
2464      to the next statement after <literal>END</>.  But if an error
2465      occurs within the <replaceable>statements</replaceable>, further
2466      processing of the <replaceable>statements</replaceable> is
2467      abandoned, and control passes to the <literal>EXCEPTION</> list.
2468      The list is searched for the first <replaceable>condition</replaceable>
2469      matching the error that occurred.  If a match is found, the
2470      corresponding <replaceable>handler_statements</replaceable> are
2471      executed, and then control passes to the next statement after
2472      <literal>END</>.  If no match is found, the error propagates out
2473      as though the <literal>EXCEPTION</> clause were not there at all:
2474      the error can be caught by an enclosing block with
2475      <literal>EXCEPTION</>, or if there is none it aborts processing
2476      of the function.
2477     </para>
2478
2479     <para>
2480      The <replaceable>condition</replaceable> names can be any of
2481      those shown in <xref linkend="errcodes-appendix">.  A category
2482      name matches any error within its category.  The special
2483      condition name <literal>OTHERS</> matches every error type except
2484      <literal>QUERY_CANCELED</>.  (It is possible, but often unwise,
2485      to trap <literal>QUERY_CANCELED</> by name.)  Condition names are
2486      not case-sensitive.  Also, an error condition can be specified
2487      by <literal>SQLSTATE</> code; for example these are equivalent:
2488 <programlisting>
2489 WHEN division_by_zero THEN ...
2490 WHEN SQLSTATE '22012' THEN ...
2491 </programlisting>
2492     </para>
2493
2494     <para>
2495      If a new error occurs within the selected
2496      <replaceable>handler_statements</replaceable>, it cannot be caught
2497      by this <literal>EXCEPTION</> clause, but is propagated out.
2498      A surrounding <literal>EXCEPTION</> clause could catch it.
2499     </para>
2500
2501     <para>
2502      When an error is caught by an <literal>EXCEPTION</> clause,
2503      the local variables of the <application>PL/pgSQL</> function
2504      remain as they were when the error occurred, but all changes
2505      to persistent database state within the block are rolled back.
2506      As an example, consider this fragment:
2507
2508 <programlisting>
2509 INSERT INTO mytab(firstname, lastname) VALUES('Tom', 'Jones');
2510 BEGIN
2511     UPDATE mytab SET firstname = 'Joe' WHERE lastname = 'Jones';
2512     x := x + 1;
2513     y := x / 0;
2514 EXCEPTION
2515     WHEN division_by_zero THEN
2516         RAISE NOTICE 'caught division_by_zero';
2517         RETURN x;
2518 END;
2519 </programlisting>
2520
2521      When control reaches the assignment to <literal>y</>, it will
2522      fail with a <literal>division_by_zero</> error.  This will be caught by
2523      the <literal>EXCEPTION</> clause.  The value returned in the
2524      <command>RETURN</> statement will be the incremented value of
2525      <literal>x</>, but the effects of the <command>UPDATE</> command will
2526      have been rolled back.  The <command>INSERT</> command preceding the
2527      block is not rolled back, however, so the end result is that the database
2528      contains <literal>Tom Jones</> not <literal>Joe Jones</>.
2529     </para>
2530
2531     <tip>
2532      <para>
2533       A block containing an <literal>EXCEPTION</> clause is significantly
2534       more expensive to enter and exit than a block without one.  Therefore,
2535       don't use <literal>EXCEPTION</> without need.
2536      </para>
2537     </tip>
2538
2539     <example id="plpgsql-upsert-example">
2540     <title>Exceptions with <command>UPDATE</>/<command>INSERT</></title>
2541     <para>
2542
2543     This example uses exception handling to perform either
2544     <command>UPDATE</> or <command>INSERT</>, as appropriate:
2545
2546 <programlisting>
2547 CREATE TABLE db (a INT PRIMARY KEY, b TEXT);
2548
2549 CREATE FUNCTION merge_db(key INT, data TEXT) RETURNS VOID AS
2550 $$
2551 BEGIN
2552     LOOP
2553         -- first try to update the key
2554         UPDATE db SET b = data WHERE a = key;
2555         IF found THEN
2556             RETURN;
2557         END IF;
2558         -- not there, so try to insert the key
2559         -- if someone else inserts the same key concurrently,
2560         -- we could get a unique-key failure
2561         BEGIN
2562             INSERT INTO db(a,b) VALUES (key, data);
2563             RETURN;
2564         EXCEPTION WHEN unique_violation THEN
2565             -- Do nothing, and loop to try the UPDATE again.
2566         END;
2567     END LOOP;
2568 END;
2569 $$
2570 LANGUAGE plpgsql;
2571
2572 SELECT merge_db(1, 'david');
2573 SELECT merge_db(1, 'dennis');
2574 </programlisting>
2575
2576      This coding assumes the <literal>unique_violation</> error is caused by
2577      the <command>INSERT</>, and not by, say, an <command>INSERT</> in a
2578      trigger function on the table.  It might also misbehave if there is
2579      more than one unique index on the table, since it will retry the
2580      operation regardless of which index caused the error.
2581      More safety could be had by using the
2582      features discussed next to check that the trapped error was the one
2583      expected.
2584     </para>
2585     </example>
2586
2587    <sect3 id="plpgsql-exception-diagnostics">
2588     <title>Obtaining information about an error</title>
2589
2590     <para>
2591      Exception handlers frequently need to identify the specific error that
2592      occurred.  There are two ways to get information about the current
2593      exception in <application>PL/pgSQL</>: special variables and the
2594      <command>GET STACKED DIAGNOSTICS</command> command.
2595     </para>
2596
2597     <para>
2598      Within an exception handler, the special variable
2599      <varname>SQLSTATE</varname> contains the error code that corresponds to
2600      the exception that was raised (refer to <xref linkend="errcodes-table">
2601      for a list of possible error codes). The special variable
2602      <varname>SQLERRM</varname> contains the error message associated with the
2603      exception. These variables are undefined outside exception handlers.
2604     </para>
2605
2606     <para>
2607      Within an exception handler, one may also retrieve
2608      information about the current exception by using the
2609      <command>GET STACKED DIAGNOSTICS</command> command, which has the form:
2610
2611 <synopsis>
2612 GET STACKED DIAGNOSTICS <replaceable>variable</replaceable> = <replaceable>item</replaceable> <optional> , ... </optional>;
2613 </synopsis>
2614
2615      Each <replaceable>item</replaceable> is a key word identifying a status
2616      value to be assigned to the specified variable (which should be
2617      of the right data type to receive it).  The currently available
2618      status items are shown in <xref linkend="plpgsql-exception-diagnostics-values">.
2619     </para>
2620
2621      <table id="plpgsql-exception-diagnostics-values">
2622       <title>Error diagnostics values</title>
2623       <tgroup cols="3">
2624        <thead>
2625         <row>
2626          <entry>Name</entry>
2627          <entry>Type</entry>
2628          <entry>Description</entry>
2629         </row>
2630        </thead>
2631        <tbody>
2632         <row>
2633          <entry><literal>RETURNED_SQLSTATE</literal></entry>
2634          <entry>text</entry>
2635          <entry>the SQLSTATE error code of the exception</entry>
2636         </row>
2637         <row>
2638          <entry><literal>MESSAGE_TEXT</literal></entry>
2639          <entry>text</entry>
2640          <entry>the text of the exception's primary message</entry>
2641         </row>
2642         <row>
2643          <entry><literal>PG_EXCEPTION_DETAIL</literal></entry>
2644          <entry>text</entry>
2645          <entry>the text of the exception's detail message, if any</entry>
2646         </row>
2647         <row>
2648          <entry><literal>PG_EXCEPTION_HINT</literal></entry>
2649          <entry>text</entry>
2650          <entry>the text of the exception's hint message, if any</entry>
2651         </row>
2652         <row>
2653          <entry><literal>PG_EXCEPTION_CONTEXT</literal></entry>
2654          <entry>text</entry>
2655          <entry>line(s) of text describing the call stack</entry>
2656         </row>
2657        </tbody>
2658       </tgroup>
2659      </table>
2660
2661     <para>
2662      If the exception did not set a value for an item, an empty string
2663      will be returned.
2664     </para>
2665
2666     <para>
2667      Here is an example:
2668 <programlisting>
2669 DECLARE
2670   text_var1 text;
2671   text_var2 text;
2672   text_var3 text;
2673 BEGIN
2674   -- some processing which might cause an exception
2675   ...
2676 EXCEPTION WHEN OTHERS THEN
2677   GET STACKED DIAGNOSTICS text_var1 = MESSAGE_TEXT,
2678                           text_var2 = PG_EXCEPTION_DETAIL,
2679                           text_var3 = PG_EXCEPTION_HINT;
2680 END;
2681 </programlisting>
2682     </para>
2683    </sect3>
2684   </sect2>
2685   </sect1>
2686
2687   <sect1 id="plpgsql-cursors">
2688    <title>Cursors</title>
2689
2690    <indexterm zone="plpgsql-cursors">
2691     <primary>cursor</primary>
2692     <secondary>in PL/pgSQL</secondary>
2693    </indexterm>
2694
2695    <para>
2696     Rather than executing a whole query at once, it is possible to set
2697     up a <firstterm>cursor</> that encapsulates the query, and then read
2698     the query result a few rows at a time. One reason for doing this is
2699     to avoid memory overrun when the result contains a large number of
2700     rows. (However, <application>PL/pgSQL</> users do not normally need
2701     to worry about that, since <literal>FOR</> loops automatically use a cursor
2702     internally to avoid memory problems.) A more interesting usage is to
2703     return a reference to a cursor that a function has created, allowing the
2704     caller to read the rows. This provides an efficient way to return
2705     large row sets from functions.
2706    </para>
2707
2708    <sect2 id="plpgsql-cursor-declarations">
2709     <title>Declaring Cursor Variables</title>
2710
2711     <para>
2712      All access to cursors in <application>PL/pgSQL</> goes through
2713      cursor variables, which are always of the special data type
2714      <type>refcursor</>.  One way to create a cursor variable
2715      is just to declare it as a variable of type <type>refcursor</>.
2716      Another way is to use the cursor declaration syntax,
2717      which in general is:
2718 <synopsis>
2719 <replaceable>name</replaceable> <optional> <optional> NO </optional> SCROLL </optional> CURSOR <optional> ( <replaceable>arguments</replaceable> ) </optional> FOR <replaceable>query</replaceable>;
2720 </synopsis>
2721      (<literal>FOR</> can be replaced by <literal>IS</> for
2722      <productname>Oracle</productname> compatibility.)
2723      If <literal>SCROLL</> is specified, the cursor will be capable of
2724      scrolling backward; if <literal>NO SCROLL</> is specified, backward
2725      fetches will be rejected; if neither specification appears, it is
2726      query-dependent whether backward fetches will be allowed.
2727      <replaceable>arguments</replaceable>, if specified, is a
2728      comma-separated list of pairs <literal><replaceable>name</replaceable>
2729      <replaceable>datatype</replaceable></literal> that define names to be
2730      replaced by parameter values in the given query.  The actual
2731      values to substitute for these names will be specified later,
2732      when the cursor is opened.
2733     </para>
2734     <para>
2735      Some examples:
2736 <programlisting>
2737 DECLARE
2738     curs1 refcursor;
2739     curs2 CURSOR FOR SELECT * FROM tenk1;
2740     curs3 CURSOR (key integer) FOR SELECT * FROM tenk1 WHERE unique1 = key;
2741 </programlisting>
2742      All three of these variables have the data type <type>refcursor</>,
2743      but the first can be used with any query, while the second has
2744      a fully specified query already <firstterm>bound</> to it, and the last
2745      has a parameterized query bound to it.  (<literal>key</> will be
2746      replaced by an integer parameter value when the cursor is opened.)
2747      The variable <literal>curs1</>
2748      is said to be <firstterm>unbound</> since it is not bound to
2749      any particular query.
2750     </para>
2751    </sect2>
2752
2753    <sect2 id="plpgsql-cursor-opening">
2754     <title>Opening Cursors</title>
2755
2756     <para>
2757      Before a cursor can be used to retrieve rows, it must be
2758      <firstterm>opened</>. (This is the equivalent action to the SQL
2759      command <command>DECLARE CURSOR</>.) <application>PL/pgSQL</> has
2760      three forms of the <command>OPEN</> statement, two of which use unbound
2761      cursor variables while the third uses a bound cursor variable.
2762     </para>
2763
2764     <note>
2765      <para>
2766       Bound cursor variables can also be used without explicitly opening the cursor,
2767       via the <command>FOR</> statement described in
2768       <xref linkend="plpgsql-cursor-for-loop">.
2769      </para>
2770     </note>
2771
2772     <sect3>
2773      <title><command>OPEN FOR</command> <replaceable>query</replaceable></title>
2774
2775 <synopsis>
2776 OPEN <replaceable>unbound_cursorvar</replaceable> <optional> <optional> NO </optional> SCROLL </optional> FOR <replaceable>query</replaceable>;
2777 </synopsis>
2778
2779        <para>
2780         The cursor variable is opened and given the specified query to
2781         execute.  The cursor cannot be open already, and it must have been
2782         declared as an unbound cursor variable (that is, as a simple
2783         <type>refcursor</> variable).  The query must be a
2784         <command>SELECT</command>, or something else that returns rows
2785         (such as <command>EXPLAIN</>).  The query
2786         is treated in the same way as other SQL commands in
2787         <application>PL/pgSQL</>: <application>PL/pgSQL</>
2788         variable names are substituted, and the query plan is cached for
2789         possible reuse.  When a <application>PL/pgSQL</>
2790         variable is substituted into the cursor query, the value that is
2791         substituted is the one it has at the time of the <command>OPEN</>;
2792         subsequent changes to the variable will not affect the cursor's
2793         behavior.
2794         The <literal>SCROLL</> and <literal>NO SCROLL</>
2795         options have the same meanings as for a bound cursor.
2796        </para>
2797
2798        <para>
2799         An example:
2800 <programlisting>
2801 OPEN curs1 FOR SELECT * FROM foo WHERE key = mykey;
2802 </programlisting>
2803        </para>
2804      </sect3>
2805
2806     <sect3>
2807      <title><command>OPEN FOR EXECUTE</command></title>
2808
2809 <synopsis>
2810 OPEN <replaceable>unbound_cursorvar</replaceable> <optional> <optional> NO </optional> SCROLL </optional> FOR EXECUTE <replaceable class="command">query_string</replaceable>
2811                                      <optional> USING <replaceable>expression</replaceable> <optional>, ... </optional> </optional>;
2812 </synopsis>
2813
2814          <para>
2815           The cursor variable is opened and given the specified query to
2816           execute.  The cursor cannot be open already, and it must have been
2817           declared as an unbound cursor variable (that is, as a simple
2818           <type>refcursor</> variable).  The query is specified as a string
2819           expression, in the same way as in the <command>EXECUTE</command>
2820           command.  As usual, this gives flexibility so the query plan can vary
2821           from one run to the next (see <xref linkend="plpgsql-plan-caching">),
2822           and it also means that variable substitution is not done on the
2823           command string. As with <command>EXECUTE</command>, parameter values
2824           can be inserted into the dynamic command via <literal>USING</>.
2825           The <literal>SCROLL</> and
2826           <literal>NO SCROLL</> options have the same meanings as for a bound
2827           cursor.
2828          </para>
2829
2830        <para>
2831         An example:
2832 <programlisting>
2833 OPEN curs1 FOR EXECUTE 'SELECT * FROM ' || quote_ident(tabname)
2834                                         || ' WHERE col1 = $1' USING keyvalue;
2835 </programlisting>
2836         In this example, the table name is inserted into the query textually,
2837         so use of <function>quote_ident()</> is recommended to guard against
2838         SQL injection.  The comparison value for <literal>col1</> is inserted
2839         via a <literal>USING</> parameter, so it needs no quoting.
2840        </para>
2841      </sect3>
2842
2843     <sect3 id="plpgsql-open-bound-cursor">
2844      <title>Opening a Bound Cursor</title>
2845
2846 <synopsis>
2847 OPEN <replaceable>bound_cursorvar</replaceable> <optional> ( <optional> <replaceable>argument_name</replaceable> := </optional> <replaceable>argument_value</replaceable> <optional>, ...</optional> ) </optional>;
2848 </synopsis>
2849
2850          <para>
2851           This form of <command>OPEN</command> is used to open a cursor
2852           variable whose query was bound to it when it was declared.  The
2853           cursor cannot be open already.  A list of actual argument value
2854           expressions must appear if and only if the cursor was declared to
2855           take arguments.  These values will be substituted in the query.
2856          </para>
2857
2858          <para>
2859           The query plan for a bound cursor is always considered cacheable;
2860           there is no equivalent of <command>EXECUTE</command> in this case.
2861           Notice that <literal>SCROLL</> and <literal>NO SCROLL</> cannot be
2862           specified in <command>OPEN</>, as the cursor's scrolling
2863           behavior was already determined.
2864          </para>
2865
2866          <para>
2867           Argument values can be passed using either <firstterm>positional</firstterm>
2868           or <firstterm>named</firstterm> notation.  In positional
2869           notation, all arguments are specified in order.  In named notation,
2870           each argument's name is specified using <literal>:=</literal> to
2871           separate it from the argument expression. Similar to calling
2872           functions, described in <xref linkend="sql-syntax-calling-funcs">, it
2873           is also allowed to mix positional and named notation.
2874          </para>
2875
2876          <para>
2877           Examples (these use the cursor declaration examples above):
2878 <programlisting>
2879 OPEN curs2;
2880 OPEN curs3(42);
2881 OPEN curs3(key := 42);
2882 </programlisting>
2883          </para>
2884
2885          <para>
2886           Because variable substitution is done on a bound cursor's query,
2887           there are really two ways to pass values into the cursor: either
2888           with an explicit argument to <command>OPEN</>, or implicitly by
2889           referencing a <application>PL/pgSQL</> variable in the query.
2890           However, only variables declared before the bound cursor was
2891           declared will be substituted into it.  In either case the value to
2892           be passed is determined at the time of the <command>OPEN</>.
2893           For example, another way to get the same effect as the
2894           <literal>curs3</> example above is
2895 <programlisting>
2896 DECLARE
2897     key integer;
2898     curs4 CURSOR FOR SELECT * FROM tenk1 WHERE unique1 = key;
2899 BEGIN
2900     key := 42;
2901     OPEN curs4;
2902 </programlisting>
2903          </para>
2904      </sect3>
2905    </sect2>
2906
2907    <sect2 id="plpgsql-cursor-using">
2908     <title>Using Cursors</title>
2909
2910     <para>
2911      Once a cursor has been opened, it can be manipulated with the
2912      statements described here.
2913     </para>
2914
2915     <para>
2916      These manipulations need not occur in the same function that
2917      opened the cursor to begin with.  You can return a <type>refcursor</>
2918      value out of a function and let the caller operate on the cursor.
2919      (Internally, a <type>refcursor</> value is simply the string name
2920      of a so-called portal containing the active query for the cursor.  This name
2921      can be passed around, assigned to other <type>refcursor</> variables,
2922      and so on, without disturbing the portal.)
2923     </para>
2924
2925     <para>
2926      All portals are implicitly closed at transaction end.  Therefore
2927      a <type>refcursor</> value is usable to reference an open cursor
2928      only until the end of the transaction.
2929     </para>
2930
2931     <sect3>
2932      <title><literal>FETCH</></title>
2933
2934 <synopsis>
2935 FETCH <optional> <replaceable>direction</replaceable> { FROM | IN } </optional> <replaceable>cursor</replaceable> INTO <replaceable>target</replaceable>;
2936 </synopsis>
2937
2938     <para>
2939      <command>FETCH</command> retrieves the next row from the
2940      cursor into a target, which might be a row variable, a record
2941      variable, or a comma-separated list of simple variables, just like
2942      <command>SELECT INTO</command>.  If there is no next row, the
2943      target is set to NULL(s).  As with <command>SELECT
2944      INTO</command>, the special variable <literal>FOUND</literal> can
2945      be checked to see whether a row was obtained or not.
2946     </para>
2947
2948     <para>
2949      The <replaceable>direction</replaceable> clause can be any of the
2950      variants allowed in the SQL <xref linkend="sql-fetch">
2951      command except the ones that can fetch
2952      more than one row; namely, it can be
2953      <literal>NEXT</>,
2954      <literal>PRIOR</>,
2955      <literal>FIRST</>,
2956      <literal>LAST</>,
2957      <literal>ABSOLUTE</> <replaceable>count</replaceable>,
2958      <literal>RELATIVE</> <replaceable>count</replaceable>,
2959      <literal>FORWARD</>, or
2960      <literal>BACKWARD</>.
2961      Omitting <replaceable>direction</replaceable> is the same
2962      as specifying <literal>NEXT</>.
2963      <replaceable>direction</replaceable> values that require moving
2964      backward are likely to fail unless the cursor was declared or opened
2965      with the <literal>SCROLL</> option.
2966     </para>
2967
2968     <para>
2969      <replaceable>cursor</replaceable> must be the name of a <type>refcursor</>
2970      variable that references an open cursor portal.
2971     </para>
2972
2973     <para>
2974      Examples:
2975 <programlisting>
2976 FETCH curs1 INTO rowvar;
2977 FETCH curs2 INTO foo, bar, baz;
2978 FETCH LAST FROM curs3 INTO x, y;
2979 FETCH RELATIVE -2 FROM curs4 INTO x;
2980 </programlisting>
2981        </para>
2982      </sect3>
2983
2984     <sect3>
2985      <title><literal>MOVE</></title>
2986
2987 <synopsis>
2988 MOVE <optional> <replaceable>direction</replaceable> { FROM | IN } </optional> <replaceable>cursor</replaceable>;
2989 </synopsis>
2990
2991     <para>
2992      <command>MOVE</command> repositions a cursor without retrieving
2993      any data. <command>MOVE</command> works exactly like the
2994      <command>FETCH</command> command, except it only repositions the
2995      cursor and does not return the row moved to. As with <command>SELECT
2996      INTO</command>, the special variable <literal>FOUND</literal> can
2997      be checked to see whether there was a next row to move to.
2998     </para>
2999
3000     <para>
3001      The <replaceable>direction</replaceable> clause can be any of the
3002      variants allowed in the SQL <xref linkend="sql-fetch">
3003      command, namely
3004      <literal>NEXT</>,
3005      <literal>PRIOR</>,
3006      <literal>FIRST</>,
3007      <literal>LAST</>,
3008      <literal>ABSOLUTE</> <replaceable>count</replaceable>,
3009      <literal>RELATIVE</> <replaceable>count</replaceable>,
3010      <literal>ALL</>,
3011      <literal>FORWARD</> <optional> <replaceable>count</replaceable> | <literal>ALL</> </optional>, or
3012      <literal>BACKWARD</> <optional> <replaceable>count</replaceable> | <literal>ALL</> </optional>.
3013      Omitting <replaceable>direction</replaceable> is the same
3014      as specifying <literal>NEXT</>.
3015      <replaceable>direction</replaceable> values that require moving
3016      backward are likely to fail unless the cursor was declared or opened
3017      with the <literal>SCROLL</> option.
3018     </para>
3019
3020     <para>
3021      Examples:
3022 <programlisting>
3023 MOVE curs1;
3024 MOVE LAST FROM curs3;
3025 MOVE RELATIVE -2 FROM curs4;
3026 MOVE FORWARD 2 FROM curs4;
3027 </programlisting>
3028        </para>
3029      </sect3>
3030
3031     <sect3>
3032      <title><literal>UPDATE/DELETE WHERE CURRENT OF</></title>
3033
3034 <synopsis>
3035 UPDATE <replaceable>table</replaceable> SET ... WHERE CURRENT OF <replaceable>cursor</replaceable>;
3036 DELETE FROM <replaceable>table</replaceable> WHERE CURRENT OF <replaceable>cursor</replaceable>;
3037 </synopsis>
3038
3039        <para>
3040         When a cursor is positioned on a table row, that row can be updated
3041         or deleted using the cursor to identify the row.  There are
3042         restrictions on what the cursor's query can be (in particular,
3043         no grouping) and it's best to use <literal>FOR UPDATE</> in the
3044         cursor.  For more information see the
3045         <xref linkend="sql-declare">
3046         reference page.
3047        </para>
3048
3049        <para>
3050         An example:
3051 <programlisting>
3052 UPDATE foo SET dataval = myval WHERE CURRENT OF curs1;
3053 </programlisting>
3054        </para>
3055      </sect3>
3056
3057     <sect3>
3058      <title><literal>CLOSE</></title>
3059
3060 <synopsis>
3061 CLOSE <replaceable>cursor</replaceable>;
3062 </synopsis>
3063
3064        <para>
3065         <command>CLOSE</command> closes the portal underlying an open
3066         cursor.  This can be used to release resources earlier than end of
3067         transaction, or to free up the cursor variable to be opened again.
3068        </para>
3069
3070        <para>
3071         An example:
3072 <programlisting>
3073 CLOSE curs1;
3074 </programlisting>
3075        </para>
3076      </sect3>
3077
3078     <sect3>
3079      <title>Returning Cursors</title>
3080
3081        <para>
3082         <application>PL/pgSQL</> functions can return cursors to the
3083         caller. This is useful to return multiple rows or columns,
3084         especially with very large result sets.  To do this, the function
3085         opens the cursor and returns the cursor name to the caller (or simply
3086         opens the cursor using a portal name specified by or otherwise known
3087         to the caller).  The caller can then fetch rows from the cursor. The
3088         cursor can be closed by the caller, or it will be closed automatically
3089         when the transaction closes.
3090        </para>
3091
3092        <para>
3093         The portal name used for a cursor can be specified by the
3094         programmer or automatically generated.  To specify a portal name,
3095         simply assign a string to the <type>refcursor</> variable before
3096         opening it.  The string value of the <type>refcursor</> variable
3097         will be used by <command>OPEN</> as the name of the underlying portal.
3098         However, if the <type>refcursor</> variable is null,
3099         <command>OPEN</> automatically generates a name that does not
3100         conflict with any existing portal, and assigns it to the
3101         <type>refcursor</> variable.
3102        </para>
3103
3104        <note>
3105         <para>
3106          A bound cursor variable is initialized to the string value
3107          representing its name, so that the portal name is the same as
3108          the cursor variable name, unless the programmer overrides it
3109          by assignment before opening the cursor.  But an unbound cursor
3110          variable defaults to the null value initially, so it will receive
3111          an automatically-generated unique name, unless overridden.
3112         </para>
3113        </note>
3114
3115        <para>
3116         The following example shows one way a cursor name can be supplied by
3117         the caller:
3118
3119 <programlisting>
3120 CREATE TABLE test (col text);
3121 INSERT INTO test VALUES ('123');
3122
3123 CREATE FUNCTION reffunc(refcursor) RETURNS refcursor AS '
3124 BEGIN
3125     OPEN $1 FOR SELECT col FROM test;
3126     RETURN $1;
3127 END;
3128 ' LANGUAGE plpgsql;
3129
3130 BEGIN;
3131 SELECT reffunc('funccursor');
3132 FETCH ALL IN funccursor;
3133 COMMIT;
3134 </programlisting>
3135        </para>
3136
3137        <para>
3138         The following example uses automatic cursor name generation:
3139
3140 <programlisting>
3141 CREATE FUNCTION reffunc2() RETURNS refcursor AS '
3142 DECLARE
3143     ref refcursor;
3144 BEGIN
3145     OPEN ref FOR SELECT col FROM test;
3146     RETURN ref;
3147 END;
3148 ' LANGUAGE plpgsql;
3149
3150 -- need to be in a transaction to use cursors.
3151 BEGIN;
3152 SELECT reffunc2();
3153
3154       reffunc2
3155 --------------------
3156  &lt;unnamed cursor 1&gt;
3157 (1 row)
3158
3159 FETCH ALL IN "&lt;unnamed cursor 1&gt;";
3160 COMMIT;
3161 </programlisting>
3162        </para>
3163
3164        <para>
3165         The following example shows one way to return multiple cursors
3166         from a single function:
3167
3168 <programlisting>
3169 CREATE FUNCTION myfunc(refcursor, refcursor) RETURNS SETOF refcursor AS $$
3170 BEGIN
3171     OPEN $1 FOR SELECT * FROM table_1;
3172     RETURN NEXT $1;
3173     OPEN $2 FOR SELECT * FROM table_2;
3174     RETURN NEXT $2;
3175 END;
3176 $$ LANGUAGE plpgsql;
3177
3178 -- need to be in a transaction to use cursors.
3179 BEGIN;
3180
3181 SELECT * FROM myfunc('a', 'b');
3182
3183 FETCH ALL FROM a;
3184 FETCH ALL FROM b;
3185 COMMIT;
3186 </programlisting>
3187        </para>
3188      </sect3>
3189    </sect2>
3190
3191    <sect2 id="plpgsql-cursor-for-loop">
3192     <title>Looping Through a Cursor's Result</title>
3193
3194     <para>
3195      There is a variant of the <command>FOR</> statement that allows
3196      iterating through the rows returned by a cursor.  The syntax is:
3197
3198 <synopsis>
3199 <optional> &lt;&lt;<replaceable>label</replaceable>&gt;&gt; </optional>
3200 FOR <replaceable>recordvar</replaceable> IN <replaceable>bound_cursorvar</replaceable> <optional> ( <optional> <replaceable>argument_name</replaceable> := </optional> <replaceable>argument_value</replaceable> <optional>, ...</optional> ) </optional> LOOP
3201     <replaceable>statements</replaceable>
3202 END LOOP <optional> <replaceable>label</replaceable> </optional>;
3203 </synopsis>
3204
3205      The cursor variable must have been bound to some query when it was
3206      declared, and it <emphasis>cannot</> be open already.  The
3207      <command>FOR</> statement automatically opens the cursor, and it closes
3208      the cursor again when the loop exits.  A list of actual argument value
3209      expressions must appear if and only if the cursor was declared to take
3210      arguments.  These values will be substituted in the query, in just
3211      the same way as during an <command>OPEN</> (see <xref
3212      linkend="plpgsql-open-bound-cursor">).
3213    </para>
3214
3215    <para>
3216      The variable <replaceable>recordvar</replaceable> is automatically
3217      defined as type <type>record</> and exists only inside the loop (any
3218      existing definition of the variable name is ignored within the loop).
3219      Each row returned by the cursor is successively assigned to this
3220      record variable and the loop body is executed.
3221     </para>
3222    </sect2>
3223
3224   </sect1>
3225
3226   <sect1 id="plpgsql-errors-and-messages">
3227    <title>Errors and Messages</title>
3228
3229    <indexterm>
3230     <primary>RAISE</primary>
3231    </indexterm>
3232
3233    <indexterm>
3234     <primary>reporting errors</primary>
3235     <secondary>in PL/pgSQL</secondary>
3236    </indexterm>
3237
3238    <para>
3239     Use the <command>RAISE</command> statement to report messages and
3240     raise errors.
3241
3242 <synopsis>
3243 RAISE <optional> <replaceable class="parameter">level</replaceable> </optional> '<replaceable class="parameter">format</replaceable>' <optional>, <replaceable class="parameter">expression</replaceable> <optional>, ... </optional></optional> <optional> USING <replaceable class="parameter">option</replaceable> = <replaceable class="parameter">expression</replaceable> <optional>, ... </optional> </optional>;
3244 RAISE <optional> <replaceable class="parameter">level</replaceable> </optional> <replaceable class="parameter">condition_name</> <optional> USING <replaceable class="parameter">option</replaceable> = <replaceable class="parameter">expression</replaceable> <optional>, ... </optional> </optional>;
3245 RAISE <optional> <replaceable class="parameter">level</replaceable> </optional> SQLSTATE '<replaceable class="parameter">sqlstate</>' <optional> USING <replaceable class="parameter">option</replaceable> = <replaceable class="parameter">expression</replaceable> <optional>, ... </optional> </optional>;
3246 RAISE <optional> <replaceable class="parameter">level</replaceable> </optional> USING <replaceable class="parameter">option</replaceable> = <replaceable class="parameter">expression</replaceable> <optional>, ... </optional>;
3247 RAISE ;
3248 </synopsis>
3249
3250     The <replaceable class="parameter">level</replaceable> option specifies
3251     the error severity.  Allowed levels are <literal>DEBUG</literal>,
3252     <literal>LOG</literal>, <literal>INFO</literal>,
3253     <literal>NOTICE</literal>, <literal>WARNING</literal>,
3254     and <literal>EXCEPTION</literal>, with <literal>EXCEPTION</literal>
3255     being the default.
3256     <literal>EXCEPTION</literal> raises an error (which normally aborts the
3257     current transaction); the other levels only generate messages of different
3258     priority levels.
3259     Whether messages of a particular priority are reported to the client,
3260     written to the server log, or both is controlled by the
3261     <xref linkend="guc-log-min-messages"> and
3262     <xref linkend="guc-client-min-messages"> configuration
3263     variables. See <xref linkend="runtime-config"> for more
3264     information.
3265    </para>
3266
3267    <para>
3268     After <replaceable class="parameter">level</replaceable> if any,
3269     you can write a <replaceable class="parameter">format</replaceable>
3270     (which must be a simple string literal, not an expression).  The
3271     format string specifies the error message text to be reported.
3272     The format string can be followed
3273     by optional argument expressions to be inserted into the message.
3274     Inside the format string, <literal>%</literal> is replaced by the
3275     string representation of the next optional argument's value. Write
3276     <literal>%%</literal> to emit a literal <literal>%</literal>.
3277    </para>
3278
3279    <para>
3280     In this example, the value of <literal>v_job_id</> will replace the
3281     <literal>%</literal> in the string:
3282 <programlisting>
3283 RAISE NOTICE 'Calling cs_create_job(%)', v_job_id;
3284 </programlisting>
3285    </para>
3286
3287    <para>
3288     You can attach additional information to the error report by writing
3289     <literal>USING</> followed by <replaceable
3290     class="parameter">option</replaceable> = <replaceable
3291     class="parameter">expression</replaceable> items.  Each
3292     <replaceable class="parameter">expression</replaceable> can be any
3293     string-valued expression.  The allowed <replaceable
3294     class="parameter">option</replaceable> key words are:
3295
3296     <variablelist id="raise-using-options">
3297      <varlistentry>
3298       <term><literal>MESSAGE</literal></term>
3299       <listitem>
3300        <para>Sets the error message text.  This option can't be used in the
3301         form of <command>RAISE</> that includes a format string
3302         before <literal>USING</>.</para>
3303       </listitem>
3304      </varlistentry>
3305
3306      <varlistentry>
3307       <term><literal>DETAIL</literal></term>
3308       <listitem>
3309        <para>Supplies an error detail message.</para>
3310       </listitem>
3311      </varlistentry>
3312
3313      <varlistentry>
3314       <term><literal>HINT</literal></term>
3315       <listitem>
3316        <para>Supplies a hint message.</para>
3317       </listitem>
3318      </varlistentry>
3319
3320      <varlistentry>
3321       <term><literal>ERRCODE</literal></term>
3322       <listitem>
3323        <para>Specifies the error code (SQLSTATE) to report, either by condition
3324         name, as shown in <xref linkend="errcodes-appendix">, or directly as a
3325         five-character SQLSTATE code.</para>
3326       </listitem>
3327      </varlistentry>
3328     </variablelist>
3329    </para>
3330
3331    <para>
3332     This example will abort the transaction with the given error message
3333     and hint:
3334 <programlisting>
3335 RAISE EXCEPTION 'Nonexistent ID --> %', user_id
3336       USING HINT = 'Please check your user ID';
3337 </programlisting>
3338    </para>
3339
3340    <para>
3341     These two examples show equivalent ways of setting the SQLSTATE:
3342 <programlisting>
3343 RAISE 'Duplicate user ID: %', user_id USING ERRCODE = 'unique_violation';
3344 RAISE 'Duplicate user ID: %', user_id USING ERRCODE = '23505';
3345 </programlisting>
3346    </para>
3347
3348    <para>
3349     There is a second <command>RAISE</> syntax in which the main argument
3350     is the condition name or SQLSTATE to be reported, for example:
3351 <programlisting>
3352 RAISE division_by_zero;
3353 RAISE SQLSTATE '22012';
3354 </programlisting>
3355     In this syntax, <literal>USING</> can be used to supply a custom
3356     error message, detail, or hint.  Another way to do the earlier
3357     example is
3358 <programlisting>
3359 RAISE unique_violation USING MESSAGE = 'Duplicate user ID: ' || user_id;
3360 </programlisting>
3361    </para>
3362
3363    <para>
3364     Still another variant is to write <literal>RAISE USING</> or <literal>RAISE
3365     <replaceable class="parameter">level</replaceable> USING</> and put
3366     everything else into the <literal>USING</> list.
3367    </para>
3368
3369    <para>
3370     The last variant of <command>RAISE</> has no parameters at all.
3371     This form can only be used inside a <literal>BEGIN</> block's
3372     <literal>EXCEPTION</> clause;
3373     it causes the error currently being handled to be re-thrown.
3374    </para>
3375
3376    <note>
3377     <para>
3378      Before <productname>PostgreSQL</> 9.1, <command>RAISE</> without
3379      parameters was interpreted as re-throwing the error from the block
3380      containing the active exception handler.  Thus an <literal>EXCEPTION</>
3381      clause nested within that handler could not catch it, even if the
3382      <command>RAISE</> was within the nested <literal>EXCEPTION</> clause's
3383      block. This was deemed surprising as well as being incompatible with
3384      Oracle's PL/SQL.
3385     </para>
3386    </note>
3387
3388    <para>
3389     If no condition name nor SQLSTATE is specified in a
3390     <command>RAISE EXCEPTION</command> command, the default is to use
3391     <literal>RAISE_EXCEPTION</> (<literal>P0001</>).  If no message
3392     text is specified, the default is to use the condition name or
3393     SQLSTATE as message text.
3394    </para>
3395
3396    <note>
3397     <para>
3398      When specifying an error code by SQLSTATE code, you are not
3399      limited to the predefined error codes, but can select any
3400      error code consisting of five digits and/or upper-case ASCII
3401      letters, other than <literal>00000</>.  It is recommended that
3402      you avoid throwing error codes that end in three zeroes, because
3403      these are category codes and can only be trapped by trapping
3404      the whole category.
3405     </para>
3406    </note>
3407
3408  </sect1>
3409
3410  <sect1 id="plpgsql-trigger">
3411   <title>Trigger Procedures</title>
3412
3413   <indexterm zone="plpgsql-trigger">
3414    <primary>trigger</primary>
3415    <secondary>in PL/pgSQL</secondary>
3416   </indexterm>
3417
3418   <sect2 id="plpgsql-dml-trigger">
3419    <title>Triggers on data changes</title>
3420
3421    <para>
3422     <application>PL/pgSQL</application> can be used to define trigger
3423     procedures. A trigger procedure is created with the
3424     <command>CREATE FUNCTION</> command, declaring it as a function with
3425     no arguments and a return type of <type>trigger</type>.  Note that
3426     the function must be declared with no arguments even if it expects
3427     to receive arguments specified in <command>CREATE TRIGGER</> &mdash;
3428     trigger arguments are passed via <varname>TG_ARGV</>, as described
3429     below.
3430   </para>
3431
3432   <para>
3433    When a <application>PL/pgSQL</application> function is called as a
3434    trigger, several special variables are created automatically in the
3435    top-level block. They are:
3436
3437    <variablelist>
3438     <varlistentry>
3439      <term><varname>NEW</varname></term>
3440      <listitem>
3441       <para>
3442        Data type <type>RECORD</type>; variable holding the new
3443        database row for <command>INSERT</>/<command>UPDATE</> operations in row-level
3444        triggers. This variable is unassigned in statement-level triggers
3445        and for <command>DELETE</command> operations.
3446       </para>
3447      </listitem>
3448     </varlistentry>
3449
3450     <varlistentry>
3451      <term><varname>OLD</varname></term>
3452      <listitem>
3453       <para>
3454        Data type <type>RECORD</type>; variable holding the old
3455        database row for <command>UPDATE</>/<command>DELETE</> operations in row-level
3456        triggers. This variable is unassigned in statement-level triggers
3457        and for <command>INSERT</command> operations.
3458       </para>
3459      </listitem>
3460     </varlistentry>
3461
3462     <varlistentry>
3463      <term><varname>TG_NAME</varname></term>
3464      <listitem>
3465       <para>
3466        Data type <type>name</type>; variable that contains the name of the trigger actually
3467        fired.
3468       </para>
3469      </listitem>
3470     </varlistentry>
3471
3472     <varlistentry>
3473      <term><varname>TG_WHEN</varname></term>
3474      <listitem>
3475       <para>
3476        Data type <type>text</type>; a string of
3477        <literal>BEFORE</literal>, <literal>AFTER</literal>, or
3478        <literal>INSTEAD OF</literal>, depending on the trigger's definition.
3479       </para>
3480      </listitem>
3481     </varlistentry>
3482
3483     <varlistentry>
3484      <term><varname>TG_LEVEL</varname></term>
3485      <listitem>
3486       <para>
3487        Data type <type>text</type>; a string of either
3488        <literal>ROW</literal> or <literal>STATEMENT</literal>
3489        depending on the trigger's definition.
3490       </para>
3491      </listitem>
3492     </varlistentry>
3493
3494     <varlistentry>
3495      <term><varname>TG_OP</varname></term>
3496      <listitem>
3497       <para>
3498        Data type <type>text</type>; a string of
3499        <literal>INSERT</literal>, <literal>UPDATE</literal>,
3500        <literal>DELETE</literal>, or <literal>TRUNCATE</>
3501        telling for which operation the trigger was fired.
3502       </para>
3503      </listitem>
3504     </varlistentry>
3505
3506     <varlistentry>
3507      <term><varname>TG_RELID</varname></term>
3508      <listitem>
3509       <para>
3510        Data type <type>oid</type>; the object ID of the table that caused the
3511        trigger invocation.
3512       </para>
3513      </listitem>
3514     </varlistentry>
3515
3516     <varlistentry>
3517      <term><varname>TG_RELNAME</varname></term>
3518      <listitem>
3519       <para>
3520        Data type <type>name</type>; the name of the table that caused the trigger
3521        invocation. This is now deprecated, and could disappear in a future
3522        release. Use <literal>TG_TABLE_NAME</> instead.
3523       </para>
3524      </listitem>
3525     </varlistentry>
3526
3527     <varlistentry>
3528      <term><varname>TG_TABLE_NAME</varname></term>
3529      <listitem>
3530       <para>
3531        Data type <type>name</type>; the name of the table that
3532        caused the trigger invocation.
3533       </para>
3534      </listitem>
3535     </varlistentry>
3536
3537     <varlistentry>
3538      <term><varname>TG_TABLE_SCHEMA</varname></term>
3539      <listitem>
3540       <para>
3541        Data type <type>name</type>; the name of the schema of the
3542        table that caused the trigger invocation.
3543       </para>
3544      </listitem>
3545     </varlistentry>
3546
3547     <varlistentry>
3548      <term><varname>TG_NARGS</varname></term>
3549      <listitem>
3550       <para>
3551        Data type <type>integer</type>; the number of arguments given to the trigger
3552        procedure in the <command>CREATE TRIGGER</command> statement.
3553       </para>
3554      </listitem>
3555     </varlistentry>
3556
3557     <varlistentry>
3558      <term><varname>TG_ARGV[]</varname></term>
3559      <listitem>
3560       <para>
3561        Data type array of <type>text</type>; the arguments from
3562        the <command>CREATE TRIGGER</command> statement.
3563        The index counts from 0. Invalid
3564        indexes (less than 0 or greater than or equal to <varname>tg_nargs</>)
3565        result in a null value.
3566       </para>
3567      </listitem>
3568     </varlistentry>
3569    </variablelist>
3570   </para>
3571
3572    <para>
3573     A trigger function must return either <symbol>NULL</symbol> or a
3574     record/row value having exactly the structure of the table the
3575     trigger was fired for.
3576    </para>
3577
3578    <para>
3579     Row-level triggers fired <literal>BEFORE</> can return null to signal the
3580     trigger manager to skip the rest of the operation for this row
3581     (i.e., subsequent triggers are not fired, and the
3582     <command>INSERT</>/<command>UPDATE</>/<command>DELETE</> does not occur
3583     for this row).  If a nonnull
3584     value is returned then the operation proceeds with that row value.
3585     Returning a row value different from the original value
3586     of <varname>NEW</> alters the row that will be inserted or
3587     updated.  Thus, if the trigger function wants the triggering
3588     action to succeed normally without altering the row
3589     value, <varname>NEW</varname> (or a value equal thereto) has to be
3590     returned.  To alter the row to be stored, it is possible to
3591     replace single values directly in <varname>NEW</> and return the
3592     modified <varname>NEW</>, or to build a complete new record/row to
3593     return.  In the case of a before-trigger
3594     on <command>DELETE</command>, the returned value has no direct
3595     effect, but it has to be nonnull to allow the trigger action to
3596     proceed.  Note that <varname>NEW</varname> is null
3597     in <command>DELETE</command> triggers, so returning that is
3598     usually not sensible.  The usual idiom in <command>DELETE</command>
3599     triggers is to return <varname>OLD</varname>.
3600    </para>
3601
3602    <para>
3603     <literal>INSTEAD OF</> triggers (which are always row-level triggers,
3604     and may only be used on views) can return null to signal that they did
3605     not perform any updates, and that the rest of the operation for this
3606     row should be skipped (i.e., subsequent triggers are not fired, and the
3607     row is not counted in the rows-affected status for the surrounding
3608     <command>INSERT</>/<command>UPDATE</>/<command>DELETE</>).
3609     Otherwise a nonnull value should be returned, to signal
3610     that the trigger performed the requested operation. For
3611     <command>INSERT</> and <command>UPDATE</> operations, the return value
3612     should be <varname>NEW</>, which the trigger function may modify to
3613     support <command>INSERT RETURNING</> and <command>UPDATE RETURNING</>
3614     (this will also affect the row value passed to any subsequent triggers).
3615     For <command>DELETE</> operations, the return value should be
3616     <varname>OLD</>.
3617    </para>
3618
3619    <para>
3620     The return value of a row-level trigger
3621     fired <literal>AFTER</literal> or a statement-level trigger
3622     fired <literal>BEFORE</> or <literal>AFTER</> is
3623     always ignored; it might as well be null. However, any of these types of
3624     triggers might still abort the entire operation by raising an error.
3625    </para>
3626
3627    <para>
3628     <xref linkend="plpgsql-trigger-example"> shows an example of a
3629     trigger procedure in <application>PL/pgSQL</application>.
3630    </para>
3631
3632    <example id="plpgsql-trigger-example">
3633     <title>A <application>PL/pgSQL</application> Trigger Procedure</title>
3634
3635     <para>
3636      This example trigger ensures that any time a row is inserted or updated
3637      in the table, the current user name and time are stamped into the
3638      row. And it checks that an employee's name is given and that the
3639      salary is a positive value.
3640     </para>
3641
3642 <programlisting>
3643 CREATE TABLE emp (
3644     empname text,
3645     salary integer,
3646     last_date timestamp,
3647     last_user text
3648 );
3649
3650 CREATE FUNCTION emp_stamp() RETURNS trigger AS $emp_stamp$
3651     BEGIN
3652         -- Check that empname and salary are given
3653         IF NEW.empname IS NULL THEN
3654             RAISE EXCEPTION 'empname cannot be null';
3655         END IF;
3656         IF NEW.salary IS NULL THEN
3657             RAISE EXCEPTION '% cannot have null salary', NEW.empname;
3658         END IF;
3659
3660         -- Who works for us when she must pay for it?
3661         IF NEW.salary &lt; 0 THEN
3662             RAISE EXCEPTION '% cannot have a negative salary', NEW.empname;
3663         END IF;
3664
3665         -- Remember who changed the payroll when
3666         NEW.last_date := current_timestamp;
3667         NEW.last_user := current_user;
3668         RETURN NEW;
3669     END;
3670 $emp_stamp$ LANGUAGE plpgsql;
3671
3672 CREATE TRIGGER emp_stamp BEFORE INSERT OR UPDATE ON emp
3673     FOR EACH ROW EXECUTE PROCEDURE emp_stamp();
3674 </programlisting>
3675    </example>
3676
3677    <para>
3678     Another way to log changes to a table involves creating a new table that
3679     holds a row for each insert, update, or delete that occurs. This approach
3680     can be thought of as auditing changes to a table.
3681     <xref linkend="plpgsql-trigger-audit-example"> shows an example of an
3682     audit trigger procedure in <application>PL/pgSQL</application>.
3683    </para>
3684
3685    <example id="plpgsql-trigger-audit-example">
3686     <title>A <application>PL/pgSQL</application> Trigger Procedure For Auditing</title>
3687
3688     <para>
3689      This example trigger ensures that any insert, update or delete of a row
3690      in the <literal>emp</literal> table is recorded (i.e., audited) in the <literal>emp_audit</literal> table.
3691      The current time and user name are stamped into the row, together with
3692      the type of operation performed on it.
3693     </para>
3694
3695 <programlisting>
3696 CREATE TABLE emp (
3697     empname           text NOT NULL,
3698     salary            integer
3699 );
3700
3701 CREATE TABLE emp_audit(
3702     operation         char(1)   NOT NULL,
3703     stamp             timestamp NOT NULL,
3704     userid            text      NOT NULL,
3705     empname           text      NOT NULL,
3706     salary integer
3707 );
3708
3709 CREATE OR REPLACE FUNCTION process_emp_audit() RETURNS TRIGGER AS $emp_audit$
3710     BEGIN
3711         --
3712         -- Create a row in emp_audit to reflect the operation performed on emp,
3713         -- make use of the special variable TG_OP to work out the operation.
3714         --
3715         IF (TG_OP = 'DELETE') THEN
3716             INSERT INTO emp_audit SELECT 'D', now(), user, OLD.*;
3717             RETURN OLD;
3718         ELSIF (TG_OP = 'UPDATE') THEN
3719             INSERT INTO emp_audit SELECT 'U', now(), user, NEW.*;
3720             RETURN NEW;
3721         ELSIF (TG_OP = 'INSERT') THEN
3722             INSERT INTO emp_audit SELECT 'I', now(), user, NEW.*;
3723             RETURN NEW;
3724         END IF;
3725         RETURN NULL; -- result is ignored since this is an AFTER trigger
3726     END;
3727 $emp_audit$ LANGUAGE plpgsql;
3728
3729 CREATE TRIGGER emp_audit
3730 AFTER INSERT OR UPDATE OR DELETE ON emp
3731     FOR EACH ROW EXECUTE PROCEDURE process_emp_audit();
3732 </programlisting>
3733    </example>
3734
3735    <para>
3736     A variation of the previous example uses a view joining the main table
3737     to the audit table, to show when each entry was last modified. This
3738     approach still records the full audit trail of changes to the table,
3739     but also presents a simplified view of the audit trail, showing just
3740     the last modified timestamp derived from the audit trail for each entry.
3741     <xref linkend="plpgsql-view-trigger-audit-example"> shows an example
3742     of an audit trigger on a view in <application>PL/pgSQL</application>.
3743    </para>
3744
3745    <example id="plpgsql-view-trigger-audit-example">
3746     <title>A <application>PL/pgSQL</application> View Trigger Procedure For Auditing</title>
3747
3748     <para>
3749      This example uses a trigger on the view to make it updatable, and
3750      ensure that any insert, update or delete of a row in the view is
3751      recorded (i.e., audited) in the <literal>emp_audit</literal> table. The current time
3752      and user name are recorded, together with the type of operation
3753      performed, and the view displays the last modified time of each row.
3754     </para>
3755
3756 <programlisting>
3757 CREATE TABLE emp (
3758     empname           text PRIMARY KEY,
3759     salary            integer
3760 );
3761
3762 CREATE TABLE emp_audit(
3763     operation         char(1)   NOT NULL,
3764     userid            text      NOT NULL,
3765     empname           text      NOT NULL,
3766     salary            integer,
3767     stamp             timestamp NOT NULL
3768 );
3769
3770 CREATE VIEW emp_view AS
3771     SELECT e.empname,
3772            e.salary,
3773            max(ea.stamp) AS last_updated
3774       FROM emp e
3775       LEFT JOIN emp_audit ea ON ea.empname = e.empname
3776      GROUP BY 1, 2;
3777
3778 CREATE OR REPLACE FUNCTION update_emp_view() RETURNS TRIGGER AS $$
3779     BEGIN
3780         --
3781         -- Perform the required operation on emp, and create a row in emp_audit
3782         -- to reflect the change made to emp.
3783         --
3784         IF (TG_OP = 'DELETE') THEN
3785             DELETE FROM emp WHERE empname = OLD.empname;
3786             IF NOT FOUND THEN RETURN NULL; END IF;
3787
3788             OLD.last_updated = now();
3789             INSERT INTO emp_audit VALUES('D', user, OLD.*);
3790             RETURN OLD;
3791         ELSIF (TG_OP = 'UPDATE') THEN
3792             UPDATE emp SET salary = NEW.salary WHERE empname = OLD.empname;
3793             IF NOT FOUND THEN RETURN NULL; END IF;
3794
3795             NEW.last_updated = now();
3796             INSERT INTO emp_audit VALUES('U', user, NEW.*);
3797             RETURN NEW;
3798         ELSIF (TG_OP = 'INSERT') THEN
3799             INSERT INTO emp VALUES(NEW.empname, NEW.salary);
3800
3801             NEW.last_updated = now();
3802             INSERT INTO emp_audit VALUES('I', user, NEW.*);
3803             RETURN NEW;
3804         END IF;
3805     END;
3806 $$ LANGUAGE plpgsql;
3807
3808 CREATE TRIGGER emp_audit
3809 INSTEAD OF INSERT OR UPDATE OR DELETE ON emp_view
3810     FOR EACH ROW EXECUTE PROCEDURE update_emp_view();
3811 </programlisting>
3812    </example>
3813
3814    <para>
3815     One use of triggers is to maintain a summary table
3816     of another table. The resulting summary can be used in place of the
3817     original table for certain queries &mdash; often with vastly reduced run
3818     times.
3819     This technique is commonly used in Data Warehousing, where the tables
3820     of measured or observed data (called fact tables) might be extremely large.
3821     <xref linkend="plpgsql-trigger-summary-example"> shows an example of a
3822     trigger procedure in <application>PL/pgSQL</application> that maintains
3823     a summary table for a fact table in a data warehouse.
3824    </para>
3825
3826
3827    <example id="plpgsql-trigger-summary-example">
3828     <title>A <application>PL/pgSQL</application> Trigger Procedure For Maintaining A Summary Table</title>
3829
3830     <para>
3831      The schema detailed here is partly based on the <emphasis>Grocery Store
3832      </emphasis> example from <emphasis>The Data Warehouse Toolkit</emphasis>
3833      by Ralph Kimball.
3834     </para>
3835
3836 <programlisting>
3837 --
3838 -- Main tables - time dimension and sales fact.
3839 --
3840 CREATE TABLE time_dimension (
3841     time_key                    integer NOT NULL,
3842     day_of_week                 integer NOT NULL,
3843     day_of_month                integer NOT NULL,
3844     month                       integer NOT NULL,
3845     quarter                     integer NOT NULL,
3846     year                        integer NOT NULL
3847 );
3848 CREATE UNIQUE INDEX time_dimension_key ON time_dimension(time_key);
3849
3850 CREATE TABLE sales_fact (
3851     time_key                    integer NOT NULL,
3852     product_key                 integer NOT NULL,
3853     store_key                   integer NOT NULL,
3854     amount_sold                 numeric(12,2) NOT NULL,
3855     units_sold                  integer NOT NULL,
3856     amount_cost                 numeric(12,2) NOT NULL
3857 );
3858 CREATE INDEX sales_fact_time ON sales_fact(time_key);
3859
3860 --
3861 -- Summary table - sales by time.
3862 --
3863 CREATE TABLE sales_summary_bytime (
3864     time_key                    integer NOT NULL,
3865     amount_sold                 numeric(15,2) NOT NULL,
3866     units_sold                  numeric(12) NOT NULL,
3867     amount_cost                 numeric(15,2) NOT NULL
3868 );
3869 CREATE UNIQUE INDEX sales_summary_bytime_key ON sales_summary_bytime(time_key);
3870
3871 --
3872 -- Function and trigger to amend summarized column(s) on UPDATE, INSERT, DELETE.
3873 --
3874 CREATE OR REPLACE FUNCTION maint_sales_summary_bytime() RETURNS TRIGGER
3875 AS $maint_sales_summary_bytime$
3876     DECLARE
3877         delta_time_key          integer;
3878         delta_amount_sold       numeric(15,2);
3879         delta_units_sold        numeric(12);
3880         delta_amount_cost       numeric(15,2);
3881     BEGIN
3882
3883         -- Work out the increment/decrement amount(s).
3884         IF (TG_OP = 'DELETE') THEN
3885
3886             delta_time_key = OLD.time_key;
3887             delta_amount_sold = -1 * OLD.amount_sold;
3888             delta_units_sold = -1 * OLD.units_sold;
3889             delta_amount_cost = -1 * OLD.amount_cost;
3890
3891         ELSIF (TG_OP = 'UPDATE') THEN
3892
3893             -- forbid updates that change the time_key -
3894             -- (probably not too onerous, as DELETE + INSERT is how most
3895             -- changes will be made).
3896             IF ( OLD.time_key != NEW.time_key) THEN
3897                 RAISE EXCEPTION 'Update of time_key : % -&gt; % not allowed',
3898                                                       OLD.time_key, NEW.time_key;
3899             END IF;
3900
3901             delta_time_key = OLD.time_key;
3902             delta_amount_sold = NEW.amount_sold - OLD.amount_sold;
3903             delta_units_sold = NEW.units_sold - OLD.units_sold;
3904             delta_amount_cost = NEW.amount_cost - OLD.amount_cost;
3905
3906         ELSIF (TG_OP = 'INSERT') THEN
3907
3908             delta_time_key = NEW.time_key;
3909             delta_amount_sold = NEW.amount_sold;
3910             delta_units_sold = NEW.units_sold;
3911             delta_amount_cost = NEW.amount_cost;
3912
3913         END IF;
3914
3915
3916         -- Insert or update the summary row with the new values.
3917         &lt;&lt;insert_update&gt;&gt;
3918         LOOP
3919             UPDATE sales_summary_bytime
3920                 SET amount_sold = amount_sold + delta_amount_sold,
3921                     units_sold = units_sold + delta_units_sold,
3922                     amount_cost = amount_cost + delta_amount_cost
3923                 WHERE time_key = delta_time_key;
3924
3925             EXIT insert_update WHEN found;
3926
3927             BEGIN
3928                 INSERT INTO sales_summary_bytime (
3929                             time_key,
3930                             amount_sold,
3931                             units_sold,
3932                             amount_cost)
3933                     VALUES (
3934                             delta_time_key,
3935                             delta_amount_sold,
3936                             delta_units_sold,
3937                             delta_amount_cost
3938                            );
3939
3940                 EXIT insert_update;
3941
3942             EXCEPTION
3943                 WHEN UNIQUE_VIOLATION THEN
3944                     -- do nothing
3945             END;
3946         END LOOP insert_update;
3947
3948         RETURN NULL;
3949
3950     END;
3951 $maint_sales_summary_bytime$ LANGUAGE plpgsql;
3952
3953 CREATE TRIGGER maint_sales_summary_bytime
3954 AFTER INSERT OR UPDATE OR DELETE ON sales_fact
3955     FOR EACH ROW EXECUTE PROCEDURE maint_sales_summary_bytime();
3956
3957 INSERT INTO sales_fact VALUES(1,1,1,10,3,15);
3958 INSERT INTO sales_fact VALUES(1,2,1,20,5,35);
3959 INSERT INTO sales_fact VALUES(2,2,1,40,15,135);
3960 INSERT INTO sales_fact VALUES(2,3,1,10,1,13);
3961 SELECT * FROM sales_summary_bytime;
3962 DELETE FROM sales_fact WHERE product_key = 1;
3963 SELECT * FROM sales_summary_bytime;
3964 UPDATE sales_fact SET units_sold = units_sold * 2;
3965 SELECT * FROM sales_summary_bytime;
3966 </programlisting>
3967    </example>
3968 </sect2>
3969
3970   <sect2 id="plpgsql-event-trigger">
3971    <title>Triggers on events</title>
3972
3973    <para>
3974     <application>PL/pgSQL</application> can be used to define event
3975     triggers.  <productname>PostgreSQL</> requires that a procedure that
3976     is to be called as an event trigger must be declared as a function with
3977     no arguments and a return type of <literal>event_trigger</>.
3978    </para>
3979
3980    <para>
3981     When a <application>PL/pgSQL</application> function is called as a
3982     event trigger, several special variables are created automatically
3983     in the top-level block. They are:
3984
3985    <variablelist>
3986     <varlistentry>
3987      <term><varname>TG_EVENT</varname></term>
3988      <listitem>
3989       <para>
3990        Data type <type>text</type>; a string representing the event the
3991        trigger is fired for.
3992       </para>
3993      </listitem>
3994     </varlistentry>
3995
3996     <varlistentry>
3997      <term><varname>TG_TAG</varname></term>
3998      <listitem>
3999       <para>
4000        Data type <type>text</type>; variable that contains the command tag
4001        for which the trigger is fired.
4002       </para>
4003      </listitem>
4004     </varlistentry>
4005    </variablelist>
4006   </para>
4007
4008    <para>
4009     <xref linkend="plpgsql-event-trigger-example"> shows an example of a
4010     event trigger procedure in <application>PL/pgSQL</application>.
4011    </para>
4012
4013    <example id="plpgsql-event-trigger-example">
4014     <title>A <application>PL/pgSQL</application> Event Trigger Procedure</title>
4015
4016     <para>
4017      This example trigger simply raises a <literal>NOTICE</literal> message
4018      each time a supported command is executed.
4019     </para>
4020
4021 <programlisting>
4022 CREATE OR REPLACE FUNCTION snitch() RETURNS event_trigger AS $$
4023 BEGIN
4024     RAISE NOTICE 'snitch: % %', tg_event, tg_tag;
4025 END;
4026 $$ LANGUAGE plpgsql;
4027
4028 CREATE EVENT TRIGGER snitch ON ddl_command_start EXECUTE PROCEDURE snitch();
4029 </programlisting>
4030    </example>
4031   </sect2>
4032
4033   </sect1>
4034
4035   <sect1 id="plpgsql-implementation">
4036    <title><application>PL/pgSQL</> Under the Hood</title>
4037
4038    <para>
4039     This section discusses some implementation details that are
4040     frequently important for <application>PL/pgSQL</> users to know.
4041    </para>
4042
4043   <sect2 id="plpgsql-var-subst">
4044    <title>Variable Substitution</title>
4045
4046    <para>
4047     SQL statements and expressions within a <application>PL/pgSQL</> function
4048     can refer to variables and parameters of the function.  Behind the scenes,
4049     <application>PL/pgSQL</> substitutes query parameters for such references.
4050     Parameters will only be substituted in places where a parameter or
4051     column reference is syntactically allowed.  As an extreme case, consider
4052     this example of poor programming style:
4053 <programlisting>
4054 INSERT INTO foo (foo) VALUES (foo);
4055 </programlisting>
4056     The first occurrence of <literal>foo</> must syntactically be a table
4057     name, so it will not be substituted, even if the function has a variable
4058     named <literal>foo</>.  The second occurrence must be the name of a
4059     column of the table, so it will not be substituted either.  Only the
4060     third occurrence is a candidate to be a reference to the function's
4061     variable.
4062    </para>
4063
4064    <note>
4065     <para>
4066      <productname>PostgreSQL</productname> versions before 9.0 would try
4067      to substitute the variable in all three cases, leading to syntax errors.
4068     </para>
4069    </note>
4070
4071    <para>
4072     Since the names of variables are syntactically no different from the names
4073     of table columns, there can be ambiguity in statements that also refer to
4074     tables: is a given name meant to refer to a table column, or a variable?
4075     Let's change the previous example to
4076 <programlisting>
4077 INSERT INTO dest (col) SELECT foo + bar FROM src;
4078 </programlisting>
4079     Here, <literal>dest</> and <literal>src</> must be table names, and
4080     <literal>col</> must be a column of <literal>dest</>, but <literal>foo</>
4081     and <literal>bar</> might reasonably be either variables of the function
4082     or columns of <literal>src</>.
4083    </para>
4084
4085    <para>
4086     By default, <application>PL/pgSQL</> will report an error if a name
4087     in a SQL statement could refer to either a variable or a table column.
4088     You can fix such a problem by renaming the variable or column,
4089     or by qualifying the ambiguous reference, or by telling
4090     <application>PL/pgSQL</> which interpretation to prefer.
4091    </para>
4092
4093    <para>
4094     The simplest solution is to rename the variable or column.
4095     A common coding rule is to use a
4096     different naming convention for <application>PL/pgSQL</application>
4097     variables than you use for column names.  For example,
4098     if you consistently name function variables
4099     <literal>v_<replaceable>something</></literal> while none of your
4100     column names start with <literal>v_</>, no conflicts will occur.
4101    </para>
4102
4103    <para>
4104     Alternatively you can qualify ambiguous references to make them clear.
4105     In the above example, <literal>src.foo</> would be an unambiguous reference
4106     to the table column.  To create an unambiguous reference to a variable,
4107     declare it in a labeled block and use the block's label
4108     (see <xref linkend="plpgsql-structure">).  For example,
4109 <programlisting>
4110 &lt;&lt;block&gt;&gt;
4111 DECLARE
4112     foo int;
4113 BEGIN
4114     foo := ...;
4115     INSERT INTO dest (col) SELECT block.foo + bar FROM src;
4116 </programlisting>
4117     Here <literal>block.foo</> means the variable even if there is a column
4118     <literal>foo</> in <literal>src</>.  Function parameters, as well as
4119     special variables such as <literal>FOUND</>, can be qualified by the
4120     function's name, because they are implicitly declared in an outer block
4121     labeled with the function's name.
4122    </para>
4123
4124    <para>
4125     Sometimes it is impractical to fix all the ambiguous references in a
4126     large body of <application>PL/pgSQL</> code.  In such cases you can
4127     specify that <application>PL/pgSQL</> should resolve ambiguous references
4128     as the variable (which is compatible with <application>PL/pgSQL</>'s
4129     behavior before <productname>PostgreSQL</productname> 9.0), or as the
4130     table column (which is compatible with some other systems such as
4131     <productname>Oracle</productname>).
4132    </para>
4133
4134    <indexterm>
4135      <primary><varname>plpgsql.variable_conflict</> configuration parameter</primary>
4136    </indexterm>
4137
4138    <para>
4139     To change this behavior on a system-wide basis, set the configuration
4140     parameter <literal>plpgsql.variable_conflict</> to one of
4141     <literal>error</>, <literal>use_variable</>, or
4142     <literal>use_column</> (where <literal>error</> is the factory default).
4143     This parameter affects subsequent compilations
4144     of statements in <application>PL/pgSQL</> functions, but not statements
4145     already compiled in the current session.
4146     Because changing this setting
4147     can cause unexpected changes in the behavior of <application>PL/pgSQL</>
4148     functions, it can only be changed by a superuser.
4149    </para>
4150
4151    <para>
4152     You can also set the behavior on a function-by-function basis, by
4153     inserting one of these special commands at the start of the function
4154     text:
4155 <programlisting>
4156 #variable_conflict error
4157 #variable_conflict use_variable
4158 #variable_conflict use_column
4159 </programlisting>
4160     These commands affect only the function they are written in, and override
4161     the setting of <literal>plpgsql.variable_conflict</>.  An example is
4162 <programlisting>
4163 CREATE FUNCTION stamp_user(id int, comment text) RETURNS void AS $$
4164     #variable_conflict use_variable
4165     DECLARE
4166         curtime timestamp := now();
4167     BEGIN
4168         UPDATE users SET last_modified = curtime, comment = comment
4169           WHERE users.id = id;
4170     END;
4171 $$ LANGUAGE plpgsql;
4172 </programlisting>
4173     In the <literal>UPDATE</> command, <literal>curtime</>, <literal>comment</>,
4174     and <literal>id</> will refer to the function's variable and parameters
4175     whether or not <literal>users</> has columns of those names.  Notice
4176     that we had to qualify the reference to <literal>users.id</> in the
4177     <literal>WHERE</> clause to make it refer to the table column.
4178     But we did not have to qualify the reference to <literal>comment</>
4179     as a target in the <literal>UPDATE</> list, because syntactically
4180     that must be a column of <literal>users</>.  We could write the same
4181     function without depending on the <literal>variable_conflict</> setting
4182     in this way:
4183 <programlisting>
4184 CREATE FUNCTION stamp_user(id int, comment text) RETURNS void AS $$
4185     &lt;&lt;fn&gt;&gt;
4186     DECLARE
4187         curtime timestamp := now();
4188     BEGIN
4189         UPDATE users SET last_modified = fn.curtime, comment = stamp_user.comment
4190           WHERE users.id = stamp_user.id;
4191     END;
4192 $$ LANGUAGE plpgsql;
4193 </programlisting>
4194    </para>
4195
4196    <para>
4197     Variable substitution does not happen in the command string given
4198     to <command>EXECUTE</> or one of its variants.  If you need to
4199     insert a varying value into such a command, do so as part of
4200     constructing the string value, or use <literal>USING</>, as illustrated in
4201     <xref linkend="plpgsql-statements-executing-dyn">.
4202    </para>
4203
4204    <para>
4205     Variable substitution currently works only in <command>SELECT</>,
4206     <command>INSERT</>, <command>UPDATE</>, and <command>DELETE</> commands,
4207     because the main SQL engine allows query parameters only in these
4208     commands.  To use a non-constant name or value in other statement
4209     types (generically called utility statements), you must construct
4210     the utility statement as a string and <command>EXECUTE</> it.
4211    </para>
4212
4213   </sect2>
4214
4215   <sect2 id="plpgsql-plan-caching">
4216    <title>Plan Caching</title>
4217
4218    <para>
4219     The <application>PL/pgSQL</> interpreter parses the function's source
4220     text and produces an internal binary instruction tree the first time the
4221     function is called (within each session).  The instruction tree
4222     fully translates the
4223     <application>PL/pgSQL</> statement structure, but individual
4224     <acronym>SQL</acronym> expressions and <acronym>SQL</acronym> commands
4225     used in the function are not translated immediately.
4226    </para>
4227
4228    <para>
4229     <indexterm>
4230      <primary>preparing a query</>
4231      <secondary>in PL/pgSQL</>
4232     </indexterm>
4233     As each expression and <acronym>SQL</acronym> command is first
4234     executed in the function, the <application>PL/pgSQL</> interpreter
4235     parses and analyzes the command to create a prepared statement,
4236     using the <acronym>SPI</acronym> manager's
4237     <function>SPI_prepare</function> function.
4238     Subsequent visits to that expression or command
4239     reuse the prepared statement.  Thus, a function with conditional code
4240     paths that are seldom visited will never incur the overhead of
4241     analyzing those commands that are never executed within the current
4242     session.  A disadvantage is that errors
4243     in a specific expression or command cannot be detected until that
4244     part of the function is reached in execution.  (Trivial syntax
4245     errors will be detected during the initial parsing pass, but
4246     anything deeper will not be detected until execution.)
4247    </para>
4248
4249    <para>
4250     <application>PL/pgSQL</> (or more precisely, the SPI manager) can
4251     furthermore attempt to cache the execution plan associated with any
4252     particular prepared statement.  If a cached plan is not used, then
4253     a fresh execution plan is generated on each visit to the statement,
4254     and the current parameter values (that is, <application>PL/pgSQL</>
4255     variable values) can be used to optimize the selected plan.  If the
4256     statement has no parameters, or is executed many times, the SPI manager
4257     will consider creating a <firstterm>generic</> plan that is not dependent
4258     on specific parameter values, and caching that for re-use.  Typically
4259     this will happen only if the execution plan is not very sensitive to
4260     the values of the <application>PL/pgSQL</> variables referenced in it.
4261     If it is, generating a plan each time is a net win.  See <xref
4262     linkend="sql-prepare"> for more information about the behavior of
4263     prepared statements.
4264    </para>
4265
4266    <para>
4267     Because <application>PL/pgSQL</application> saves prepared statements
4268     and sometimes execution plans in this way,
4269     SQL commands that appear directly in a
4270     <application>PL/pgSQL</application> function must refer to the
4271     same tables and columns on every execution; that is, you cannot use
4272     a parameter as the name of a table or column in an SQL command.  To get
4273     around this restriction, you can construct dynamic commands using
4274     the <application>PL/pgSQL</application> <command>EXECUTE</command>
4275     statement &mdash; at the price of performing new parse analysis and
4276     constructing a new execution plan on every execution.
4277    </para>
4278
4279     <para>
4280      The mutable nature of record variables presents another problem in this
4281      connection.  When fields of a record variable are used in
4282      expressions or statements, the data types of the fields must not
4283      change from one call of the function to the next, since each
4284      expression will be analyzed using the data type that is present
4285      when the expression is first reached.  <command>EXECUTE</command> can be
4286      used to get around this problem when necessary.
4287     </para>
4288
4289     <para>
4290      If the same function is used as a trigger for more than one table,
4291      <application>PL/pgSQL</application> prepares and caches statements
4292      independently for each such table &mdash; that is, there is a cache
4293      for each trigger function and table combination, not just for each
4294      function.  This alleviates some of the problems with varying
4295      data types; for instance, a trigger function will be able to work
4296      successfully with a column named <literal>key</> even if it happens
4297      to have different types in different tables.
4298     </para>
4299
4300     <para>
4301      Likewise, functions having polymorphic argument types have a separate
4302      statement cache for each combination of actual argument types they have
4303      been invoked for, so that data type differences do not cause unexpected
4304      failures.
4305     </para>
4306
4307    <para>
4308     Statement caching can sometimes have surprising effects on the
4309     interpretation of time-sensitive values.  For example there
4310     is a difference between what these two functions do:
4311
4312 <programlisting>
4313 CREATE FUNCTION logfunc1(logtxt text) RETURNS void AS $$
4314     BEGIN
4315         INSERT INTO logtable VALUES (logtxt, 'now');
4316     END;
4317 $$ LANGUAGE plpgsql;
4318 </programlisting>
4319
4320      and:
4321
4322 <programlisting>
4323 CREATE FUNCTION logfunc2(logtxt text) RETURNS void AS $$
4324     DECLARE
4325         curtime timestamp;
4326     BEGIN
4327         curtime := 'now';
4328         INSERT INTO logtable VALUES (logtxt, curtime);
4329     END;
4330 $$ LANGUAGE plpgsql;
4331 </programlisting>
4332     </para>
4333
4334     <para>
4335      In the case of <function>logfunc1</function>, the
4336      <productname>PostgreSQL</productname> main parser knows when
4337      analyzing the <command>INSERT</command> that the
4338      string <literal>'now'</literal> should be interpreted as
4339      <type>timestamp</type>, because the target column of
4340      <classname>logtable</classname> is of that type. Thus,
4341      <literal>'now'</literal> will be converted to a <type>timestamp</type>
4342      constant when the
4343      <command>INSERT</command> is analyzed, and then used in all
4344      invocations of <function>logfunc1</function> during the lifetime
4345      of the session. Needless to say, this isn't what the programmer
4346      wanted.  A better idea is to use the <literal>now()</> or
4347      <literal>current_timestamp</> function.
4348     </para>
4349
4350     <para>
4351      In the case of <function>logfunc2</function>, the
4352      <productname>PostgreSQL</productname> main parser does not know
4353      what type <literal>'now'</literal> should become and therefore
4354      it returns a data value of type <type>text</type> containing the string
4355      <literal>now</literal>. During the ensuing assignment
4356      to the local variable <varname>curtime</varname>, the
4357      <application>PL/pgSQL</application> interpreter casts this
4358      string to the <type>timestamp</type> type by calling the
4359      <function>text_out</function> and <function>timestamp_in</function>
4360      functions for the conversion.  So, the computed time stamp is updated
4361      on each execution as the programmer expects.  Even though this
4362      happens to work as expected, it's not terribly efficient, so
4363      use of the <literal>now()</> function would still be a better idea.
4364     </para>
4365
4366   </sect2>
4367
4368   </sect1>
4369
4370  <sect1 id="plpgsql-development-tips">
4371   <title>Tips for Developing in <application>PL/pgSQL</application></title>
4372
4373    <para>
4374     One good way to develop in
4375     <application>PL/pgSQL</> is to use the text editor of your
4376     choice to create your functions, and in another window, use
4377     <application>psql</application> to load and test those functions.
4378     If you are doing it this way, it
4379     is a good idea to write the function using <command>CREATE OR
4380     REPLACE FUNCTION</>. That way you can just reload the file to update
4381     the function definition.  For example:
4382 <programlisting>
4383 CREATE OR REPLACE FUNCTION testfunc(integer) RETURNS integer AS $$
4384           ....
4385 $$ LANGUAGE plpgsql;
4386 </programlisting>
4387    </para>
4388
4389    <para>
4390     While running <application>psql</application>, you can load or reload such
4391     a function definition file with:
4392 <programlisting>
4393 \i filename.sql
4394 </programlisting>
4395     and then immediately issue SQL commands to test the function.
4396    </para>
4397
4398    <para>
4399     Another good way to develop in <application>PL/pgSQL</> is with a
4400     GUI database access tool that facilitates development in a
4401     procedural language. One example of such a tool is
4402     <application>pgAdmin</>, although others exist. These tools often
4403     provide convenient features such as escaping single quotes and
4404     making it easier to recreate and debug functions.
4405    </para>
4406
4407   <sect2 id="plpgsql-quote-tips">
4408    <title>Handling of Quotation Marks</title>
4409
4410    <para>
4411     The code of a <application>PL/pgSQL</> function is specified in
4412     <command>CREATE FUNCTION</command> as a string literal.  If you
4413     write the string literal in the ordinary way with surrounding
4414     single quotes, then any single quotes inside the function body
4415     must be doubled; likewise any backslashes must be doubled (assuming
4416     escape string syntax is used).
4417     Doubling quotes is at best tedious, and in more complicated cases
4418     the code can become downright incomprehensible, because you can
4419     easily find yourself needing half a dozen or more adjacent quote marks.
4420     It's recommended that you instead write the function body as a
4421     <quote>dollar-quoted</> string literal (see <xref
4422     linkend="sql-syntax-dollar-quoting">).  In the dollar-quoting
4423     approach, you never double any quote marks, but instead take care to
4424     choose a different dollar-quoting delimiter for each level of
4425     nesting you need.  For example, you might write the <command>CREATE
4426     FUNCTION</command> command as:
4427 <programlisting>
4428 CREATE OR REPLACE FUNCTION testfunc(integer) RETURNS integer AS $PROC$
4429           ....
4430 $PROC$ LANGUAGE plpgsql;
4431 </programlisting>
4432     Within this, you might use quote marks for simple literal strings in
4433     SQL commands and <literal>$$</> to delimit fragments of SQL commands
4434     that you are assembling as strings.  If you need to quote text that
4435     includes <literal>$$</>, you could use <literal>$Q$</>, and so on.
4436    </para>
4437
4438    <para>
4439     The following chart shows what you have to do when writing quote
4440     marks without dollar quoting.  It might be useful when translating
4441     pre-dollar quoting code into something more comprehensible.
4442   </para>
4443
4444   <variablelist>
4445    <varlistentry>
4446     <term>1 quotation mark</term>
4447     <listitem>
4448      <para>
4449       To begin and end the function body, for example:
4450 <programlisting>
4451 CREATE FUNCTION foo() RETURNS integer AS '
4452           ....
4453 ' LANGUAGE plpgsql;
4454 </programlisting>
4455       Anywhere within a single-quoted function body, quote marks
4456       <emphasis>must</> appear in pairs.
4457      </para>
4458     </listitem>
4459    </varlistentry>
4460
4461    <varlistentry>
4462     <term>2 quotation marks</term>
4463     <listitem>
4464      <para>
4465       For string literals inside the function body, for example:
4466 <programlisting>
4467 a_output := ''Blah'';
4468 SELECT * FROM users WHERE f_name=''foobar'';
4469 </programlisting>
4470       In the dollar-quoting approach, you'd just write:
4471 <programlisting>
4472 a_output := 'Blah';
4473 SELECT * FROM users WHERE f_name='foobar';
4474 </programlisting>
4475       which is exactly what the <application>PL/pgSQL</> parser would see
4476       in either case.
4477      </para>
4478     </listitem>
4479    </varlistentry>
4480
4481    <varlistentry>
4482     <term>4 quotation marks</term>
4483     <listitem>
4484      <para>
4485       When you need a single quotation mark in a string constant inside the
4486       function body, for example:
4487 <programlisting>
4488 a_output := a_output || '' AND name LIKE ''''foobar'''' AND xyz''
4489 </programlisting>
4490       The value actually appended to <literal>a_output</literal> would be:
4491       <literal> AND name LIKE 'foobar' AND xyz</literal>.
4492      </para>
4493      <para>
4494       In the dollar-quoting approach, you'd write:
4495 <programlisting>
4496 a_output := a_output || $$ AND name LIKE 'foobar' AND xyz$$
4497 </programlisting>
4498       being careful that any dollar-quote delimiters around this are not
4499       just <literal>$$</>.
4500      </para>
4501     </listitem>
4502    </varlistentry>
4503
4504    <varlistentry>
4505     <term>6 quotation marks</term>
4506     <listitem>
4507      <para>
4508       When a single quotation mark in a string inside the function body is
4509       adjacent to the end of that string constant, for example:
4510 <programlisting>
4511 a_output := a_output || '' AND name LIKE ''''foobar''''''
4512 </programlisting>
4513       The value appended to <literal>a_output</literal> would then be:
4514       <literal> AND name LIKE 'foobar'</literal>.
4515      </para>
4516      <para>
4517       In the dollar-quoting approach, this becomes:
4518 <programlisting>
4519 a_output := a_output || $$ AND name LIKE 'foobar'$$
4520 </programlisting>
4521      </para>
4522     </listitem>
4523    </varlistentry>
4524
4525    <varlistentry>
4526     <term>10 quotation marks</term>
4527     <listitem>
4528      <para>
4529       When you want two single quotation marks in a string constant (which
4530       accounts for 8 quotation marks) and this is adjacent to the end of that
4531       string constant (2 more).  You will probably only need that if
4532       you are writing a function that generates other functions, as in
4533       <xref linkend="plpgsql-porting-ex2">.
4534       For example:
4535 <programlisting>
4536 a_output := a_output || '' if v_'' ||
4537     referrer_keys.kind || '' like ''''''''''
4538     || referrer_keys.key_string || ''''''''''
4539     then return ''''''  || referrer_keys.referrer_type
4540     || ''''''; end if;'';
4541 </programlisting>
4542       The value of <literal>a_output</literal> would then be:
4543 <programlisting>
4544 if v_... like ''...'' then return ''...''; end if;
4545 </programlisting>
4546      </para>
4547      <para>
4548       In the dollar-quoting approach, this becomes:
4549 <programlisting>
4550 a_output := a_output || $$ if v_$$ || referrer_keys.kind || $$ like '$$
4551     || referrer_keys.key_string || $$'
4552     then return '$$  || referrer_keys.referrer_type
4553     || $$'; end if;$$;
4554 </programlisting>
4555       where we assume we only need to put single quote marks into
4556       <literal>a_output</literal>, because it will be re-quoted before use.
4557      </para>
4558     </listitem>
4559    </varlistentry>
4560   </variablelist>
4561
4562   </sect2>
4563  </sect1>
4564
4565   <!-- **** Porting from Oracle PL/SQL **** -->
4566
4567  <sect1 id="plpgsql-porting">
4568   <title>Porting from <productname>Oracle</productname> PL/SQL</title>
4569
4570   <indexterm zone="plpgsql-porting">
4571    <primary>Oracle</primary>
4572    <secondary>porting from PL/SQL to PL/pgSQL</secondary>
4573   </indexterm>
4574
4575   <indexterm zone="plpgsql-porting">
4576    <primary>PL/SQL (Oracle)</primary>
4577    <secondary>porting to PL/pgSQL</secondary>
4578   </indexterm>
4579
4580   <para>
4581    This section explains differences between
4582    <productname>PostgreSQL</>'s <application>PL/pgSQL</application>
4583    language and Oracle's <application>PL/SQL</application> language,
4584    to help developers who port applications from
4585    <trademark class="registered">Oracle</> to <productname>PostgreSQL</>.
4586   </para>
4587
4588   <para>
4589    <application>PL/pgSQL</application> is similar to PL/SQL in many
4590    aspects. It is a block-structured, imperative language, and all
4591    variables have to be declared.  Assignments, loops, conditionals
4592    are similar.  The main differences you should keep in mind when
4593    porting from <application>PL/SQL</> to
4594    <application>PL/pgSQL</application> are:
4595
4596     <itemizedlist>
4597      <listitem>
4598       <para>
4599        If a name used in a SQL command could be either a column name of a
4600        table or a reference to a variable of the function,
4601        <application>PL/SQL</> treats it as a column name.  This corresponds
4602        to <application>PL/pgSQL</>'s
4603        <literal>plpgsql.variable_conflict</> = <literal>use_column</>
4604        behavior, which is not the default,
4605        as explained in <xref linkend="plpgsql-var-subst">.
4606        It's often best to avoid such ambiguities in the first place,
4607        but if you have to port a large amount of code that depends on
4608        this behavior, setting <literal>variable_conflict</> may be the
4609        best solution.
4610       </para>
4611      </listitem>
4612
4613      <listitem>
4614       <para>
4615        In <productname>PostgreSQL</> the function body must be written as
4616        a string literal.  Therefore you need to use dollar quoting or escape
4617        single quotes in the function body. (See <xref
4618        linkend="plpgsql-quote-tips">.)
4619       </para>
4620      </listitem>
4621
4622      <listitem>
4623       <para>
4624        Instead of packages, use schemas to organize your functions
4625        into groups.
4626       </para>
4627      </listitem>
4628
4629      <listitem>
4630       <para>
4631        Since there are no packages, there are no package-level variables
4632        either. This is somewhat annoying.  You can keep per-session state
4633        in temporary tables instead.
4634       </para>
4635      </listitem>
4636
4637      <listitem>
4638       <para>
4639        Integer <command>FOR</> loops with <literal>REVERSE</> work
4640        differently: <application>PL/SQL</> counts down from the second
4641        number to the first, while <application>PL/pgSQL</> counts down
4642        from the first number to the second, requiring the loop bounds
4643        to be swapped when porting.  This incompatibility is unfortunate
4644        but is unlikely to be changed. (See <xref
4645        linkend="plpgsql-integer-for">.)
4646       </para>
4647      </listitem>
4648
4649      <listitem>
4650       <para>
4651        <command>FOR</> loops over queries (other than cursors) also work
4652        differently: the target variable(s) must have been declared,
4653        whereas <application>PL/SQL</> always declares them implicitly.
4654        An advantage of this is that the variable values are still accessible
4655        after the loop exits.
4656       </para>
4657      </listitem>
4658
4659      <listitem>
4660       <para>
4661        There are various notational differences for the use of cursor
4662        variables.
4663       </para>
4664      </listitem>
4665
4666     </itemizedlist>
4667    </para>
4668
4669   <sect2>
4670    <title>Porting Examples</title>
4671
4672    <para>
4673     <xref linkend="pgsql-porting-ex1"> shows how to port a simple
4674     function from <application>PL/SQL</> to <application>PL/pgSQL</>.
4675    </para>
4676
4677    <example id="pgsql-porting-ex1">
4678     <title>Porting a Simple Function from <application>PL/SQL</> to <application>PL/pgSQL</></title>
4679
4680     <para>
4681      Here is an <productname>Oracle</productname> <application>PL/SQL</> function:
4682 <programlisting>
4683 CREATE OR REPLACE FUNCTION cs_fmt_browser_version(v_name varchar,
4684                                                   v_version varchar)
4685 RETURN varchar IS
4686 BEGIN
4687     IF v_version IS NULL THEN
4688         RETURN v_name;
4689     END IF;
4690     RETURN v_name || '/' || v_version;
4691 END;
4692 /
4693 show errors;
4694 </programlisting>
4695     </para>
4696
4697     <para>
4698      Let's go through this function and see the differences compared to
4699      <application>PL/pgSQL</>:
4700
4701      <itemizedlist>
4702       <listitem>
4703        <para>
4704         The <literal>RETURN</literal> key word in the function
4705         prototype (not the function body) becomes
4706         <literal>RETURNS</literal> in
4707         <productname>PostgreSQL</productname>.
4708         Also, <literal>IS</> becomes <literal>AS</>, and you need to
4709         add a <literal>LANGUAGE</> clause because <application>PL/pgSQL</>
4710         is not the only possible function language.
4711        </para>
4712       </listitem>
4713
4714       <listitem>
4715        <para>
4716         In <productname>PostgreSQL</>, the function body is considered
4717         to be a string literal, so you need to use quote marks or dollar
4718         quotes around it.  This substitutes for the terminating <literal>/</>
4719         in the Oracle approach.
4720        </para>
4721       </listitem>
4722
4723       <listitem>
4724        <para>
4725         The <literal>show errors</literal> command does not exist in
4726         <productname>PostgreSQL</>, and is not needed since errors are
4727         reported automatically.
4728        </para>
4729       </listitem>
4730      </itemizedlist>
4731     </para>
4732
4733     <para>
4734      This is how this function would look when ported to
4735      <productname>PostgreSQL</>:
4736
4737 <programlisting>
4738 CREATE OR REPLACE FUNCTION cs_fmt_browser_version(v_name varchar,
4739                                                   v_version varchar)
4740 RETURNS varchar AS $$
4741 BEGIN
4742     IF v_version IS NULL THEN
4743         RETURN v_name;
4744     END IF;
4745     RETURN v_name || '/' || v_version;
4746 END;
4747 $$ LANGUAGE plpgsql;
4748 </programlisting>
4749     </para>
4750    </example>
4751
4752    <para>
4753     <xref linkend="plpgsql-porting-ex2"> shows how to port a
4754     function that creates another function and how to handle the
4755     ensuing quoting problems.
4756    </para>
4757
4758    <example id="plpgsql-porting-ex2">
4759     <title>Porting a Function that Creates Another Function from <application>PL/SQL</> to <application>PL/pgSQL</></title>
4760
4761     <para>
4762      The following procedure grabs rows from a
4763      <command>SELECT</command> statement and builds a large function
4764      with the results in <literal>IF</literal> statements, for the
4765      sake of efficiency.
4766     </para>
4767
4768     <para>
4769      This is the Oracle version:
4770 <programlisting>
4771 CREATE OR REPLACE PROCEDURE cs_update_referrer_type_proc IS
4772     CURSOR referrer_keys IS
4773         SELECT * FROM cs_referrer_keys
4774         ORDER BY try_order;
4775     func_cmd VARCHAR(4000);
4776 BEGIN
4777     func_cmd := 'CREATE OR REPLACE FUNCTION cs_find_referrer_type(v_host IN VARCHAR,
4778                  v_domain IN VARCHAR, v_url IN VARCHAR) RETURN VARCHAR IS BEGIN';
4779
4780     FOR referrer_key IN referrer_keys LOOP
4781         func_cmd := func_cmd ||
4782           ' IF v_' || referrer_key.kind
4783           || ' LIKE ''' || referrer_key.key_string
4784           || ''' THEN RETURN ''' || referrer_key.referrer_type
4785           || '''; END IF;';
4786     END LOOP;
4787
4788     func_cmd := func_cmd || ' RETURN NULL; END;';
4789
4790     EXECUTE IMMEDIATE func_cmd;
4791 END;
4792 /
4793 show errors;
4794 </programlisting>
4795     </para>
4796
4797     <para>
4798      Here is how this function would end up in <productname>PostgreSQL</>:
4799 <programlisting>
4800 CREATE OR REPLACE FUNCTION cs_update_referrer_type_proc() RETURNS void AS $func$
4801 DECLARE
4802     referrer_keys CURSOR IS
4803         SELECT * FROM cs_referrer_keys
4804         ORDER BY try_order;
4805     func_body text;
4806     func_cmd text;
4807 BEGIN
4808     func_body := 'BEGIN';
4809
4810     FOR referrer_key IN referrer_keys LOOP
4811         func_body := func_body ||
4812           ' IF v_' || referrer_key.kind
4813           || ' LIKE ' || quote_literal(referrer_key.key_string)
4814           || ' THEN RETURN ' || quote_literal(referrer_key.referrer_type)
4815           || '; END IF;' ;
4816     END LOOP;
4817
4818     func_body := func_body || ' RETURN NULL; END;';
4819
4820     func_cmd :=
4821       'CREATE OR REPLACE FUNCTION cs_find_referrer_type(v_host varchar,
4822                                                         v_domain varchar,
4823                                                         v_url varchar)
4824         RETURNS varchar AS '
4825       || quote_literal(func_body)
4826       || ' LANGUAGE plpgsql;' ;
4827
4828     EXECUTE func_cmd;
4829 END;
4830 $func$ LANGUAGE plpgsql;
4831 </programlisting>
4832      Notice how the body of the function is built separately and passed
4833      through <literal>quote_literal</> to double any quote marks in it.  This
4834      technique is needed because we cannot safely use dollar quoting for
4835      defining the new function: we do not know for sure what strings will
4836      be interpolated from the <structfield>referrer_key.key_string</> field.
4837      (We are assuming here that <structfield>referrer_key.kind</> can be
4838      trusted to always be <literal>host</>, <literal>domain</>, or
4839      <literal>url</>, but <structfield>referrer_key.key_string</> might be
4840      anything, in particular it might contain dollar signs.) This function
4841      is actually an improvement on the Oracle original, because it will
4842      not generate broken code when <structfield>referrer_key.key_string</> or
4843      <structfield>referrer_key.referrer_type</> contain quote marks.
4844     </para>
4845    </example>
4846
4847    <para>
4848     <xref linkend="plpgsql-porting-ex3"> shows how to port a function
4849     with <literal>OUT</> parameters and string manipulation.
4850     <productname>PostgreSQL</> does not have a built-in
4851     <function>instr</function> function, but you can create one
4852     using a combination of other
4853     functions.<indexterm><primary>instr</></indexterm> In <xref
4854     linkend="plpgsql-porting-appendix"> there is a
4855     <application>PL/pgSQL</application> implementation of
4856     <function>instr</function> that you can use to make your porting
4857     easier.
4858    </para>
4859
4860    <example id="plpgsql-porting-ex3">
4861     <title>Porting a Procedure With String Manipulation and
4862     <literal>OUT</> Parameters from <application>PL/SQL</> to
4863     <application>PL/pgSQL</></title>
4864
4865     <para>
4866      The following <productname>Oracle</productname> PL/SQL procedure is used
4867      to parse a URL and return several elements (host, path, and query).
4868     </para>
4869
4870     <para>
4871      This is the Oracle version:
4872 <programlisting>
4873 CREATE OR REPLACE PROCEDURE cs_parse_url(
4874     v_url IN VARCHAR,
4875     v_host OUT VARCHAR,  -- This will be passed back
4876     v_path OUT VARCHAR,  -- This one too
4877     v_query OUT VARCHAR) -- And this one
4878 IS
4879     a_pos1 INTEGER;
4880     a_pos2 INTEGER;
4881 BEGIN
4882     v_host := NULL;
4883     v_path := NULL;
4884     v_query := NULL;
4885     a_pos1 := instr(v_url, '//');
4886
4887     IF a_pos1 = 0 THEN
4888         RETURN;
4889     END IF;
4890     a_pos2 := instr(v_url, '/', a_pos1 + 2);
4891     IF a_pos2 = 0 THEN
4892         v_host := substr(v_url, a_pos1 + 2);
4893         v_path := '/';
4894         RETURN;
4895     END IF;
4896
4897     v_host := substr(v_url, a_pos1 + 2, a_pos2 - a_pos1 - 2);
4898     a_pos1 := instr(v_url, '?', a_pos2 + 1);
4899
4900     IF a_pos1 = 0 THEN
4901         v_path := substr(v_url, a_pos2);
4902         RETURN;
4903     END IF;
4904
4905     v_path := substr(v_url, a_pos2, a_pos1 - a_pos2);
4906     v_query := substr(v_url, a_pos1 + 1);
4907 END;
4908 /
4909 show errors;
4910 </programlisting>
4911     </para>
4912
4913     <para>
4914      Here is a possible translation into <application>PL/pgSQL</>:
4915 <programlisting>
4916 CREATE OR REPLACE FUNCTION cs_parse_url(
4917     v_url IN VARCHAR,
4918     v_host OUT VARCHAR,  -- This will be passed back
4919     v_path OUT VARCHAR,  -- This one too
4920     v_query OUT VARCHAR) -- And this one
4921 AS $$
4922 DECLARE
4923     a_pos1 INTEGER;
4924     a_pos2 INTEGER;
4925 BEGIN
4926     v_host := NULL;
4927     v_path := NULL;
4928     v_query := NULL;
4929     a_pos1 := instr(v_url, '//');
4930
4931     IF a_pos1 = 0 THEN
4932         RETURN;
4933     END IF;
4934     a_pos2 := instr(v_url, '/', a_pos1 + 2);
4935     IF a_pos2 = 0 THEN
4936         v_host := substr(v_url, a_pos1 + 2);
4937         v_path := '/';
4938         RETURN;
4939     END IF;
4940
4941     v_host := substr(v_url, a_pos1 + 2, a_pos2 - a_pos1 - 2);
4942     a_pos1 := instr(v_url, '?', a_pos2 + 1);
4943
4944     IF a_pos1 = 0 THEN
4945         v_path := substr(v_url, a_pos2);
4946         RETURN;
4947     END IF;
4948
4949     v_path := substr(v_url, a_pos2, a_pos1 - a_pos2);
4950     v_query := substr(v_url, a_pos1 + 1);
4951 END;
4952 $$ LANGUAGE plpgsql;
4953 </programlisting>
4954
4955      This function could be used like this:
4956 <programlisting>
4957 SELECT * FROM cs_parse_url('http://foobar.com/query.cgi?baz');
4958 </programlisting>
4959     </para>
4960    </example>
4961
4962    <para>
4963     <xref linkend="plpgsql-porting-ex4"> shows how to port a procedure
4964     that uses numerous features that are specific to Oracle.
4965    </para>
4966
4967    <example id="plpgsql-porting-ex4">
4968     <title>Porting a Procedure from <application>PL/SQL</> to <application>PL/pgSQL</></title>
4969
4970     <para>
4971      The Oracle version:
4972
4973 <programlisting>
4974 CREATE OR REPLACE PROCEDURE cs_create_job(v_job_id IN INTEGER) IS
4975     a_running_job_count INTEGER;
4976     PRAGMA AUTONOMOUS_TRANSACTION;<co id="co.plpgsql-porting-pragma">
4977 BEGIN
4978     LOCK TABLE cs_jobs IN EXCLUSIVE MODE;<co id="co.plpgsql-porting-locktable">
4979
4980     SELECT count(*) INTO a_running_job_count FROM cs_jobs WHERE end_stamp IS NULL;
4981
4982     IF a_running_job_count &gt; 0 THEN
4983         COMMIT; -- free lock<co id="co.plpgsql-porting-commit">
4984         raise_application_error(-20000,
4985                  'Unable to create a new job: a job is currently running.');
4986     END IF;
4987
4988     DELETE FROM cs_active_job;
4989     INSERT INTO cs_active_job(job_id) VALUES (v_job_id);
4990
4991     BEGIN
4992         INSERT INTO cs_jobs (job_id, start_stamp) VALUES (v_job_id, sysdate);
4993     EXCEPTION
4994         WHEN dup_val_on_index THEN NULL; -- don't worry if it already exists
4995     END;
4996     COMMIT;
4997 END;
4998 /
4999 show errors
5000 </programlisting>
5001    </para>
5002
5003    <para>
5004     Procedures like this can easily be converted into <productname>PostgreSQL</>
5005     functions returning <type>void</type>. This procedure in
5006     particular is interesting because it can teach us some things:
5007
5008     <calloutlist>
5009      <callout arearefs="co.plpgsql-porting-pragma">
5010       <para>
5011        There is no <literal>PRAGMA</literal> statement in <productname>PostgreSQL</>.
5012       </para>
5013      </callout>
5014
5015      <callout arearefs="co.plpgsql-porting-locktable">
5016       <para>
5017        If you do a <command>LOCK TABLE</command> in <application>PL/pgSQL</>,
5018        the lock will not be released until the calling transaction is
5019        finished.
5020       </para>
5021      </callout>
5022
5023      <callout arearefs="co.plpgsql-porting-commit">
5024       <para>
5025        You cannot issue <command>COMMIT</> in a
5026        <application>PL/pgSQL</application> function.  The function is
5027        running within some outer transaction and so <command>COMMIT</>
5028        would imply terminating the function's execution.  However, in
5029        this particular case it is not necessary anyway, because the lock
5030        obtained by the <command>LOCK TABLE</command> will be released when
5031        we raise an error.
5032       </para>
5033      </callout>
5034     </calloutlist>
5035    </para>
5036
5037    <para>
5038     This is how we could port this procedure to <application>PL/pgSQL</>:
5039
5040 <programlisting>
5041 CREATE OR REPLACE FUNCTION cs_create_job(v_job_id integer) RETURNS void AS $$
5042 DECLARE
5043     a_running_job_count integer;
5044 BEGIN
5045     LOCK TABLE cs_jobs IN EXCLUSIVE MODE;
5046
5047     SELECT count(*) INTO a_running_job_count FROM cs_jobs WHERE end_stamp IS NULL;
5048
5049     IF a_running_job_count &gt; 0 THEN
5050         RAISE EXCEPTION 'Unable to create a new job: a job is currently running';<co id="co.plpgsql-porting-raise">
5051     END IF;
5052
5053     DELETE FROM cs_active_job;
5054     INSERT INTO cs_active_job(job_id) VALUES (v_job_id);
5055
5056     BEGIN
5057         INSERT INTO cs_jobs (job_id, start_stamp) VALUES (v_job_id, now());
5058     EXCEPTION
5059         WHEN unique_violation THEN <co id="co.plpgsql-porting-exception">
5060             -- don't worry if it already exists
5061     END;
5062 END;
5063 $$ LANGUAGE plpgsql;
5064 </programlisting>
5065
5066     <calloutlist>
5067      <callout arearefs="co.plpgsql-porting-raise">
5068       <para>
5069        The syntax of <literal>RAISE</> is considerably different from
5070        Oracle's statement, although the basic case <literal>RAISE</>
5071        <replaceable class="parameter">exception_name</replaceable> works
5072        similarly.
5073       </para>
5074      </callout>
5075      <callout arearefs="co.plpgsql-porting-exception">
5076       <para>
5077        The exception names supported by <application>PL/pgSQL</> are
5078        different from Oracle's.  The set of built-in exception names
5079        is much larger (see <xref linkend="errcodes-appendix">).  There
5080        is not currently a way to declare user-defined exception names,
5081        although you can throw user-chosen SQLSTATE values instead.
5082       </para>
5083      </callout>
5084     </calloutlist>
5085
5086     The main functional difference between this procedure and the
5087     Oracle equivalent is that the exclusive lock on the <literal>cs_jobs</>
5088     table will be held until the calling transaction completes.  Also, if
5089     the caller later aborts (for example due to an error), the effects of
5090     this procedure will be rolled back.
5091    </para>
5092    </example>
5093   </sect2>
5094
5095   <sect2 id="plpgsql-porting-other">
5096    <title>Other Things to Watch For</title>
5097
5098    <para>
5099     This section explains a few other things to watch for when porting
5100     Oracle <application>PL/SQL</> functions to
5101     <productname>PostgreSQL</productname>.
5102    </para>
5103
5104    <sect3 id="plpgsql-porting-exceptions">
5105     <title>Implicit Rollback after Exceptions</title>
5106
5107     <para>
5108      In <application>PL/pgSQL</>, when an exception is caught by an
5109      <literal>EXCEPTION</> clause, all database changes since the block's
5110      <literal>BEGIN</> are automatically rolled back.  That is, the behavior
5111      is equivalent to what you'd get in Oracle with:
5112
5113 <programlisting>
5114 BEGIN
5115     SAVEPOINT s1;
5116     ... code here ...
5117 EXCEPTION
5118     WHEN ... THEN
5119         ROLLBACK TO s1;
5120         ... code here ...
5121     WHEN ... THEN
5122         ROLLBACK TO s1;
5123         ... code here ...
5124 END;
5125 </programlisting>
5126
5127      If you are translating an Oracle procedure that uses
5128      <command>SAVEPOINT</> and <command>ROLLBACK TO</> in this style,
5129      your task is easy: just omit the <command>SAVEPOINT</> and
5130      <command>ROLLBACK TO</>.  If you have a procedure that uses
5131      <command>SAVEPOINT</> and <command>ROLLBACK TO</> in a different way
5132      then some actual thought will be required.
5133     </para>
5134    </sect3>
5135
5136    <sect3>
5137     <title><command>EXECUTE</command></title>
5138
5139     <para>
5140      The <application>PL/pgSQL</> version of
5141      <command>EXECUTE</command> works similarly to the
5142      <application>PL/SQL</> version, but you have to remember to use
5143      <function>quote_literal</function> and
5144      <function>quote_ident</function> as described in <xref
5145      linkend="plpgsql-statements-executing-dyn">.  Constructs of the
5146      type <literal>EXECUTE 'SELECT * FROM $1';</literal> will not work
5147      reliably unless you use these functions.
5148     </para>
5149    </sect3>
5150
5151    <sect3 id="plpgsql-porting-optimization">
5152     <title>Optimizing <application>PL/pgSQL</application> Functions</title>
5153
5154     <para>
5155      <productname>PostgreSQL</> gives you two function creation
5156      modifiers to optimize execution: <quote>volatility</> (whether
5157      the function always returns the same result when given the same
5158      arguments) and <quote>strictness</quote> (whether the function
5159      returns null if any argument is null).  Consult the <xref
5160      linkend="sql-createfunction">
5161      reference page for details.
5162     </para>
5163
5164     <para>
5165      When making use of these optimization attributes, your
5166      <command>CREATE FUNCTION</command> statement might look something
5167      like this:
5168
5169 <programlisting>
5170 CREATE FUNCTION foo(...) RETURNS integer AS $$
5171 ...
5172 $$ LANGUAGE plpgsql STRICT IMMUTABLE;
5173 </programlisting>
5174     </para>
5175    </sect3>
5176   </sect2>
5177
5178   <sect2 id="plpgsql-porting-appendix">
5179    <title>Appendix</title>
5180
5181    <para>
5182     This section contains the code for a set of Oracle-compatible
5183     <function>instr</function> functions that you can use to simplify
5184     your porting efforts.
5185    </para>
5186
5187 <programlisting>
5188 --
5189 -- instr functions that mimic Oracle's counterpart
5190 -- Syntax: instr(string1, string2, [n], [m]) where [] denotes optional parameters.
5191 --
5192 -- Searches string1 beginning at the nth character for the mth occurrence
5193 -- of string2.  If n is negative, search backwards.  If m is not passed,
5194 -- assume 1 (search starts at first character).
5195 --
5196
5197 CREATE FUNCTION instr(varchar, varchar) RETURNS integer AS $$
5198 DECLARE
5199     pos integer;
5200 BEGIN
5201     pos:= instr($1, $2, 1);
5202     RETURN pos;
5203 END;
5204 $$ LANGUAGE plpgsql STRICT IMMUTABLE;
5205
5206
5207 CREATE FUNCTION instr(string varchar, string_to_search varchar, beg_index integer)
5208 RETURNS integer AS $$
5209 DECLARE
5210     pos integer NOT NULL DEFAULT 0;
5211     temp_str varchar;
5212     beg integer;
5213     length integer;
5214     ss_length integer;
5215 BEGIN
5216     IF beg_index &gt; 0 THEN
5217         temp_str := substring(string FROM beg_index);
5218         pos := position(string_to_search IN temp_str);
5219
5220         IF pos = 0 THEN
5221             RETURN 0;
5222         ELSE
5223             RETURN pos + beg_index - 1;
5224         END IF;
5225     ELSIF beg_index &lt; 0 THEN
5226         ss_length := char_length(string_to_search);
5227         length := char_length(string);
5228         beg := length + beg_index - ss_length + 2;
5229
5230         WHILE beg &gt; 0 LOOP
5231             temp_str := substring(string FROM beg FOR ss_length);
5232             pos := position(string_to_search IN temp_str);
5233
5234             IF pos &gt; 0 THEN
5235                 RETURN beg;
5236             END IF;
5237
5238             beg := beg - 1;
5239         END LOOP;
5240
5241         RETURN 0;
5242     ELSE
5243         RETURN 0;
5244     END IF;
5245 END;
5246 $$ LANGUAGE plpgsql STRICT IMMUTABLE;
5247
5248
5249 CREATE FUNCTION instr(string varchar, string_to_search varchar,
5250                       beg_index integer, occur_index integer)
5251 RETURNS integer AS $$
5252 DECLARE
5253     pos integer NOT NULL DEFAULT 0;
5254     occur_number integer NOT NULL DEFAULT 0;
5255     temp_str varchar;
5256     beg integer;
5257     i integer;
5258     length integer;
5259     ss_length integer;
5260 BEGIN
5261     IF beg_index &gt; 0 THEN
5262         beg := beg_index;
5263         temp_str := substring(string FROM beg_index);
5264
5265         FOR i IN 1..occur_index LOOP
5266             pos := position(string_to_search IN temp_str);
5267
5268             IF i = 1 THEN
5269                 beg := beg + pos - 1;
5270             ELSE
5271                 beg := beg + pos;
5272             END IF;
5273
5274             temp_str := substring(string FROM beg + 1);
5275         END LOOP;
5276
5277         IF pos = 0 THEN
5278             RETURN 0;
5279         ELSE
5280             RETURN beg;
5281         END IF;
5282     ELSIF beg_index &lt; 0 THEN
5283         ss_length := char_length(string_to_search);
5284         length := char_length(string);
5285         beg := length + beg_index - ss_length + 2;
5286
5287         WHILE beg &gt; 0 LOOP
5288             temp_str := substring(string FROM beg FOR ss_length);
5289             pos := position(string_to_search IN temp_str);
5290
5291             IF pos &gt; 0 THEN
5292                 occur_number := occur_number + 1;
5293
5294                 IF occur_number = occur_index THEN
5295                     RETURN beg;
5296                 END IF;
5297             END IF;
5298
5299             beg := beg - 1;
5300         END LOOP;
5301
5302         RETURN 0;
5303     ELSE
5304         RETURN 0;
5305     END IF;
5306 END;
5307 $$ LANGUAGE plpgsql STRICT IMMUTABLE;
5308 </programlisting>
5309   </sect2>
5310
5311  </sect1>
5312
5313 </chapter>