1 <!-- doc/src/sgml/plpgsql.sgml -->
4 <title><application>PL/pgSQL</application> - <acronym>SQL</acronym> Procedural Language</title>
6 <indexterm zone="plpgsql">
7 <primary>PL/pgSQL</primary>
10 <sect1 id="plpgsql-overview">
11 <title>Overview</title>
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
22 can be used to create functions and trigger procedures,
27 adds control structures to the <acronym>SQL</acronym> language,
32 can perform complex computations,
37 inherits all user-defined types, functions, and operators,
42 can be defined to be trusted by the server,
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.
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.
68 <sect2 id="plpgsql-advantages">
69 <title>Advantages of Using <application>PL/pgSQL</application></title>
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.
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.
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.
96 <listitem><para> Extra round trips between
97 client and server are eliminated </para></listitem>
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>
103 <listitem><para> Multiple rounds of query
104 parsing can be avoided </para></listitem>
107 <para> This can result in a considerable performance increase as
108 compared to an application that does not use stored functions.
112 Also, with <application>PL/pgSQL</application> you can use all
113 the data types, operators and functions of SQL.
117 <sect2 id="plpgsql-args-results">
118 <title>Supported Argument and Result Data Types</title>
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">.
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">.
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">.
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
158 Finally, a <application>PL/pgSQL</> function can be declared to return
159 <type>void</> if it has no useful return value.
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</>.
172 Specific examples appear in
173 <xref linkend="plpgsql-declaration-parameters"> and
174 <xref linkend="plpgsql-statements-returning">.
179 <sect1 id="plpgsql-structure">
180 <title>Structure of <application>PL/pgSQL</application></title>
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:
188 <optional> <<<replaceable>label</replaceable>>> </optional>
190 <replaceable>declarations</replaceable> </optional>
192 <replaceable>statements</replaceable>
193 END <optional> <replaceable>label</replaceable> </optional>;
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.
207 A common mistake is to write a semicolon immediately after
208 <literal>BEGIN</>. This is incorrect and will result in a syntax error.
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.
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.
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.
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:
243 CREATE FUNCTION somefunc() RETURNS integer AS $$
244 << outerblock >>
246 quantity integer := 30;
248 RAISE NOTICE 'Quantity here is %', quantity; -- Prints 30
254 quantity integer := 80;
256 RAISE NOTICE 'Quantity here is %', quantity; -- Prints 80
257 RAISE NOTICE 'Outer quantity here is %', outerblock.quantity; -- Prints 50
260 RAISE NOTICE 'Quantity here is %', quantity; -- Prints 50
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.
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
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 — 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">.
297 <sect1 id="plpgsql-declarations">
298 <title>Declarations</title>
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
311 <application>PL/pgSQL</> variables can have any SQL data type, such as
312 <type>integer</type>, <type>varchar</type>, and
317 Here are some examples of variable declarations:
322 myrow tablename%ROWTYPE;
323 myfield tablename.columnname%TYPE;
329 The general syntax of a variable declaration is:
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>;
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.
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
360 quantity integer DEFAULT 32;
361 url varchar := 'http://mysite.com';
362 user_id CONSTANT integer := 10;
366 <sect2 id="plpgsql-declaration-parameters">
367 <title>Declaring Function Parameters</title>
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.
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,
383 CREATE FUNCTION sales_tax(subtotal real) RETURNS real AS $$
385 RETURN subtotal * 0.06;
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
394 <replaceable>name</replaceable> ALIAS FOR $<replaceable>n</replaceable>;
397 The same example in this style looks like:
399 CREATE FUNCTION sales_tax(real) RETURNS real AS $$
401 subtotal ALIAS FOR $1;
403 RETURN subtotal * 0.06;
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.)
422 CREATE FUNCTION instr(varchar, integer) RETURNS integer AS $$
424 v_string ALIAS FOR $1;
427 -- some computations using v_string and index here
432 CREATE FUNCTION concat_selected_fields(in_t sometablename) RETURNS text AS $$
434 RETURN in_t.f1 || in_t.f3 || in_t.f5 || in_t.f7;
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:
451 CREATE FUNCTION sales_tax(subtotal real, OUT tax real) AS $$
453 tax := subtotal * 0.06;
458 Notice that we omitted <literal>RETURNS real</> — we could have
459 included it, but it would be redundant.
463 Output parameters are most useful when returning multiple values.
464 A trivial example is:
467 CREATE FUNCTION sum_n_product(x int, y int, OUT sum int, OUT prod int) AS $$
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</>.
482 Another way to declare a <application>PL/pgSQL</application> function
483 is with <literal>RETURNS TABLE</>, for example:
486 CREATE FUNCTION extended_sales(p_itemno int)
487 RETURNS TABLE(quantity int, total numeric) AS $$
489 RETURN QUERY SELECT quantity, quantity * price FROM sales
490 WHERE itemno = p_itemno;
495 This is exactly equivalent to declaring one or more <literal>OUT</>
496 parameters and specifying <literal>RETURNS SETOF
497 <replaceable>sometype</></literal>.
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:
517 CREATE FUNCTION add_three_values(v1 anyelement, v2 anyelement, v3 anyelement)
518 RETURNS anyelement AS $$
522 result := v1 + v2 + v3;
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:
536 CREATE FUNCTION add_three_values(v1 anyelement, v2 anyelement, v3 anyelement,
547 <sect2 id="plpgsql-declaration-alias">
548 <title><literal>ALIAS</></title>
551 <replaceable>newname</> ALIAS FOR <replaceable>oldname</>;
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
568 updated ALIAS FOR new;
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.
579 <sect2 id="plpgsql-declaration-type">
580 <title>Copying Types</title>
583 <replaceable>variable</replaceable>%TYPE
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:
594 user_id users.user_id%TYPE;
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.
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.
617 <sect2 id="plpgsql-declaration-rowtypes">
618 <title>Row Types</title>
621 <replaceable>name</replaceable> <replaceable>table_name</replaceable><literal>%ROWTYPE</literal>;
622 <replaceable>name</replaceable> <replaceable>composite_type_name</replaceable>;
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>.
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.)
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>.
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>.
663 Here is an example of using composite types. <structname>table1</>
664 and <structname>table2</> are existing tables having at least the
668 CREATE FUNCTION merge_fields(t_row table1) RETURNS text AS $$
670 t2_row table2%ROWTYPE;
672 SELECT * INTO t2_row FROM table2 WHERE ... ;
673 RETURN t_row.f1 || t2_row.f3 || t_row.f5 || t2_row.f7;
677 SELECT merge_fields(t.*) FROM table1 t WHERE ... ;
682 <sect2 id="plpgsql-declaration-records">
683 <title>Record Types</title>
686 <replaceable>name</replaceable> RECORD;
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.
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.
712 <sect2 id="plpgsql-declaration-collation">
713 <title>Collation of <application>PL/pgSQL</application> Variables</title>
716 <primary>collation</>
717 <secondary>in PL/pgSQL</>
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
732 CREATE FUNCTION less_than(a text, b text) RETURNS boolean AS $$
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;
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.
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
753 CREATE FUNCTION less_than(a text, b text) RETURNS boolean AS $$
758 RETURN local_a < local_b;
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
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
779 local_a text COLLATE "en_US";
782 This option overrides the collation that would otherwise be
783 given to the variable according to the rules above.
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,
792 CREATE FUNCTION less_than_c(a text, b text) RETURNS boolean AS $$
794 RETURN a < b COLLATE "C";
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.
806 <sect1 id="plpgsql-expressions">
807 <title>Expressions</title>
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
815 IF <replaceable>expression</replaceable> THEN ...
817 <application>PL/pgSQL</application> will evaluate the expression by
820 SELECT <replaceable>expression</replaceable>
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
835 what happens behind the scenes is equivalent to
837 PREPARE <replaceable>statement_name</>(integer, integer) AS SELECT $1 < $2;
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">.
849 <sect1 id="plpgsql-statements">
850 <title>Basic Statements</title>
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">.
862 <sect2 id="plpgsql-statements-assignment">
863 <title>Assignment</title>
866 An assignment of a value to a <application>PL/pgSQL</application>
867 variable is written as:
869 <replaceable>variable</replaceable> := <replaceable>expression</replaceable>;
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.
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.
894 tax := subtotal * 0.06;
895 my_record.user_id := 20;
900 <sect2 id="plpgsql-statements-sql-noresult">
901 <title>Executing a Command With No Result</title>
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.
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">.
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">.
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:
933 PERFORM <replaceable>query</replaceable>;
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
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">).
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
966 PERFORM create_mv('cs_session_page_requests_mv', my_query);
971 <sect2 id="plpgsql-statements-sql-onerow">
972 <title>Executing a Query with a Single-row Result</title>
974 <indexterm zone="plpgsql-statements-sql-onerow">
975 <primary>SELECT INTO</primary>
976 <secondary>in PL/pgSQL</secondary>
979 <indexterm zone="plpgsql-statements-sql-onerow">
980 <primary>RETURNING INTO</primary>
981 <secondary>in PL/pgSQL</secondary>
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,
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>;
997 where <replaceable>target</replaceable> can be a record variable, a row
998 variable, or a comma-separated list of simple variables and
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>.
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>.
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.
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.
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:
1053 SELECT * INTO myrec FROM emp WHERE empname = myname;
1055 RAISE EXCEPTION 'employee % not found', myname;
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:
1067 SELECT * INTO STRICT myrec FROM emp WHERE empname = myname;
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;
1075 Successful execution of a command with <literal>STRICT</>
1076 always sets <literal>FOUND</literal> to true.
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.
1090 The <literal>STRICT</> option matches the behavior of
1091 Oracle PL/SQL's <command>SELECT INTO</command> and related statements.
1096 To handle cases where you need to process multiple result rows
1097 from a SQL query, see <xref linkend="plpgsql-records-iterating">.
1102 <sect2 id="plpgsql-statements-executing-dyn">
1103 <title>Executing Dynamic Commands</title>
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:
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>;
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.
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
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.
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.
1157 If the <literal>STRICT</> option is given, an error is reported
1158 unless the query produces exactly one row.
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.
1171 EXECUTE 'SELECT count(*) FROM mytable WHERE inserted_by = $1 AND inserted <= $2'
1173 USING checked_user, checked_date;
1178 Note that parameter symbols can only be used for data values
1179 — 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:
1184 EXECUTE 'SELECT count(*) FROM '
1185 || tabname::regclass
1186 || ' WHERE inserted_by = $1 AND inserted <= $2'
1188 USING checked_user, checked_date;
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.
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
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</>
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).
1232 <example id="plpgsql-quote-literal-example">
1233 <title>Quoting Values In Dynamic Queries</title>
1236 <primary>quote_ident</primary>
1237 <secondary>use in PL/pgSQL</secondary>
1241 <primary>quote_literal</primary>
1242 <secondary>use in PL/pgSQL</secondary>
1246 <primary>quote_nullable</primary>
1247 <secondary>use in PL/pgSQL</secondary>
1251 <primary>format</primary>
1252 <secondary>use in PL/pgSQL</secondary>
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.)
1265 Dynamic values that are to be inserted into the constructed
1266 query require careful handling since they might themselves contain
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):
1271 EXECUTE 'UPDATE tbl SET '
1272 || quote_ident(colname)
1274 || quote_literal(newvalue)
1276 || quote_literal(keyvalue);
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.
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</>.
1305 EXECUTE 'UPDATE tbl SET '
1306 || quote_ident(colname)
1308 || quote_nullable(newvalue)
1310 || quote_nullable(keyvalue);
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</>.
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
1320 'WHERE key = ' || quote_nullable(keyvalue)
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
1327 'WHERE key IS NOT DISTINCT FROM ' || quote_nullable(keyvalue)
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</>.)
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:
1339 EXECUTE 'UPDATE tbl SET '
1340 || quote_ident(colname)
1343 || '$$ WHERE key = '
1344 || quote_literal(keyvalue);
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.
1355 Dynamic SQL statements can also be safely constructed using the
1356 <function>format</function> function (see <xref
1357 linkend="functions-string">). For example:
1359 EXECUTE format('UPDATE tbl SET %I = %L WHERE key = %L', colname, newvalue, keyvalue);
1361 The <function>format</function> function can be used in conjunction with
1362 the <literal>USING</literal> clause:
1364 EXECUTE format('UPDATE tbl SET %I = $1 WHERE key = $2', colname)
1365 USING newvalue, keyvalue;
1367 This form is more efficient, because the parameters
1368 <literal>newvalue</literal> and <literal>keyvalue</literal> are not
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.
1381 <sect2 id="plpgsql-statements-diagnostics">
1382 <title>Obtaining the Result Status</title>
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:
1390 GET <optional> CURRENT </optional> DIAGNOSTICS <replaceable>variable</replaceable> = <replaceable>item</replaceable> <optional> , ... </optional>;
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.
1409 GET DIAGNOSTICS integer_var = ROW_COUNT;
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:
1423 A <command>SELECT INTO</command> statement sets
1424 <literal>FOUND</literal> true if a row is assigned, false if no
1430 A <command>PERFORM</> statement sets <literal>FOUND</literal>
1431 true if it produces (and discards) one or more rows, false if
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.
1444 A <command>FETCH</> statement sets <literal>FOUND</literal>
1445 true if it returns a row, false if no row is returned.
1450 A <command>MOVE</> statement sets <literal>FOUND</literal>
1451 true if it successfully repositions the cursor, false otherwise.
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.
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
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>.
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.
1491 <sect2 id="plpgsql-statements-null">
1492 <title>Doing Nothing At All</title>
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:
1506 For example, the following two fragments of code are equivalent:
1511 WHEN division_by_zero THEN
1512 NULL; -- ignore the error
1520 WHEN division_by_zero THEN -- ignore the error
1523 Which is preferable is a matter of taste.
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.
1538 <sect1 id="plpgsql-control-structures">
1539 <title>Control Structures</title>
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.
1549 <sect2 id="plpgsql-statements-returning">
1550 <title>Returning From a Function</title>
1553 There are two commands available that allow you to return data
1554 from a function: <command>RETURN</command> and <command>RETURN
1559 <title><command>RETURN</></title>
1562 RETURN <replaceable>expression</replaceable>;
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
1574 When returning a scalar type, any expression can be used. The
1575 expression's result will be automatically cast into the
1576 function's return type as described for assignments. To return a
1577 composite (row) value, you must write a record or row variable
1578 as the <replaceable>expression</replaceable>.
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.
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>.
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.
1606 <title><command>RETURN NEXT</> and <command>RETURN QUERY</command></title>
1608 <primary>RETURN NEXT</primary>
1609 <secondary>in PL/pgSQL</secondary>
1612 <primary>RETURN QUERY</primary>
1613 <secondary>in PL/pgSQL</secondary>
1617 RETURN NEXT <replaceable>expression</replaceable>;
1618 RETURN QUERY <replaceable>query</replaceable>;
1619 RETURN QUERY EXECUTE <replaceable class="command">command-string</replaceable> <optional> USING <replaceable>expression</replaceable> <optional>, ... </optional> </optional>;
1623 When a <application>PL/pgSQL</> function is declared to return
1624 <literal>SETOF <replaceable>sometype</></literal>, the procedure
1625 to follow is slightly different. In that case, the individual
1626 items to return are specified by a sequence of <command>RETURN
1627 NEXT</command> or <command>RETURN QUERY</command> commands, and
1628 then a final <command>RETURN</command> command with no argument
1629 is used to indicate that the function has finished executing.
1630 <command>RETURN NEXT</command> can be used with both scalar and
1631 composite data types; with a composite result type, an entire
1632 <quote>table</quote> of results will be returned.
1633 <command>RETURN QUERY</command> appends the results of executing
1634 a query to the function's result set. <command>RETURN
1635 NEXT</command> and <command>RETURN QUERY</command> can be freely
1636 intermixed in a single set-returning function, in which case
1637 their results will be concatenated.
1641 <command>RETURN NEXT</command> and <command>RETURN
1642 QUERY</command> do not actually return from the function —
1643 they simply append zero or more rows to the function's result
1644 set. Execution then continues with the next statement in the
1645 <application>PL/pgSQL</> function. As successive
1646 <command>RETURN NEXT</command> or <command>RETURN
1647 QUERY</command> commands are executed, the result set is built
1648 up. A final <command>RETURN</command>, which should have no
1649 argument, causes control to exit the function (or you can just
1650 let control reach the end of the function).
1654 <command>RETURN QUERY</command> has a variant
1655 <command>RETURN QUERY EXECUTE</command>, which specifies the
1656 query to be executed dynamically. Parameter expressions can
1657 be inserted into the computed query string via <literal>USING</>,
1658 in just the same way as in the <command>EXECUTE</> command.
1662 If you declared the function with output parameters, write just
1663 <command>RETURN NEXT</command> with no expression. On each
1664 execution, the current values of the output parameter
1665 variable(s) will be saved for eventual return as a row of the
1666 result. Note that you must declare the function as returning
1667 <literal>SETOF record</literal> when there are multiple output
1668 parameters, or <literal>SETOF <replaceable>sometype</></literal>
1669 when there is just one output parameter of type
1670 <replaceable>sometype</>, in order to create a set-returning
1671 function with output parameters.
1675 Here is an example of a function using <command>RETURN
1679 CREATE TABLE foo (fooid INT, foosubid INT, fooname TEXT);
1680 INSERT INTO foo VALUES (1, 2, 'three');
1681 INSERT INTO foo VALUES (4, 5, 'six');
1683 CREATE OR REPLACE FUNCTION getAllFoo() RETURNS SETOF foo AS
1688 FOR r IN SELECT * FROM foo
1691 -- can do some processing here
1692 RETURN NEXT r; -- return current row of SELECT
1697 LANGUAGE 'plpgsql' ;
1699 SELECT * FROM getallfoo();
1705 The current implementation of <command>RETURN NEXT</command>
1706 and <command>RETURN QUERY</command> stores the entire result set
1707 before returning from the function, as discussed above. That
1708 means that if a <application>PL/pgSQL</> function produces a
1709 very large result set, performance might be poor: data will be
1710 written to disk to avoid memory exhaustion, but the function
1711 itself will not return until the entire result set has been
1712 generated. A future version of <application>PL/pgSQL</> might
1713 allow users to define set-returning functions
1714 that do not have this limitation. Currently, the point at
1715 which data begins being written to disk is controlled by the
1716 <xref linkend="guc-work-mem">
1717 configuration variable. Administrators who have sufficient
1718 memory to store larger result sets in memory should consider
1719 increasing this parameter.
1725 <sect2 id="plpgsql-conditionals">
1726 <title>Conditionals</title>
1729 <command>IF</> and <command>CASE</> statements let you execute
1730 alternative commands based on certain conditions.
1731 <application>PL/pgSQL</> has three forms of <command>IF</>:
1734 <para><literal>IF ... THEN</></>
1737 <para><literal>IF ... THEN ... ELSE</></>
1740 <para><literal>IF ... THEN ... ELSIF ... THEN ... ELSE</></>
1744 and two forms of <command>CASE</>:
1747 <para><literal>CASE ... WHEN ... THEN ... ELSE ... END CASE</></>
1750 <para><literal>CASE WHEN ... THEN ... ELSE ... END CASE</></>
1756 <title><literal>IF-THEN</></title>
1759 IF <replaceable>boolean-expression</replaceable> THEN
1760 <replaceable>statements</replaceable>
1765 <literal>IF-THEN</literal> statements are the simplest form of
1766 <literal>IF</literal>. The statements between
1767 <literal>THEN</literal> and <literal>END IF</literal> will be
1768 executed if the condition is true. Otherwise, they are
1775 IF v_user_id <> 0 THEN
1776 UPDATE users SET email = v_email WHERE user_id = v_user_id;
1783 <title><literal>IF-THEN-ELSE</></title>
1786 IF <replaceable>boolean-expression</replaceable> THEN
1787 <replaceable>statements</replaceable>
1789 <replaceable>statements</replaceable>
1794 <literal>IF-THEN-ELSE</literal> statements add to
1795 <literal>IF-THEN</literal> by letting you specify an
1796 alternative set of statements that should be executed if the
1797 condition is not true. (Note this includes the case where the
1798 condition evaluates to NULL.)
1804 IF parentid IS NULL OR parentid = ''
1808 RETURN hp_true_filename(parentid) || '/' || fullname;
1813 IF v_count > 0 THEN
1814 INSERT INTO users_count (count) VALUES (v_count);
1824 <title><literal>IF-THEN-ELSIF</></title>
1827 IF <replaceable>boolean-expression</replaceable> THEN
1828 <replaceable>statements</replaceable>
1829 <optional> ELSIF <replaceable>boolean-expression</replaceable> THEN
1830 <replaceable>statements</replaceable>
1831 <optional> ELSIF <replaceable>boolean-expression</replaceable> THEN
1832 <replaceable>statements</replaceable>
1837 <replaceable>statements</replaceable> </optional>
1842 Sometimes there are more than just two alternatives.
1843 <literal>IF-THEN-ELSIF</> provides a convenient
1844 method of checking several alternatives in turn.
1845 The <literal>IF</> conditions are tested successively
1846 until the first one that is true is found. Then the
1847 associated statement(s) are executed, after which control
1848 passes to the next statement after <literal>END IF</>.
1849 (Any subsequent <literal>IF</> conditions are <emphasis>not</>
1850 tested.) If none of the <literal>IF</> conditions is true,
1851 then the <literal>ELSE</> block (if any) is executed.
1860 ELSIF number > 0 THEN
1861 result := 'positive';
1862 ELSIF number < 0 THEN
1863 result := 'negative';
1865 -- hmm, the only other possibility is that number is null
1872 The key word <literal>ELSIF</> can also be spelled
1877 An alternative way of accomplishing the same task is to nest
1878 <literal>IF-THEN-ELSE</literal> statements, as in the
1882 IF demo_row.sex = 'm' THEN
1883 pretty_sex := 'man';
1885 IF demo_row.sex = 'f' THEN
1886 pretty_sex := 'woman';
1893 However, this method requires writing a matching <literal>END IF</>
1894 for each <literal>IF</>, so it is much more cumbersome than
1895 using <literal>ELSIF</> when there are many alternatives.
1900 <title>Simple <literal>CASE</></title>
1903 CASE <replaceable>search-expression</replaceable>
1904 WHEN <replaceable>expression</replaceable> <optional>, <replaceable>expression</replaceable> <optional> ... </optional></optional> THEN
1905 <replaceable>statements</replaceable>
1906 <optional> WHEN <replaceable>expression</replaceable> <optional>, <replaceable>expression</replaceable> <optional> ... </optional></optional> THEN
1907 <replaceable>statements</replaceable>
1910 <replaceable>statements</replaceable> </optional>
1915 The simple form of <command>CASE</> provides conditional execution
1916 based on equality of operands. The <replaceable>search-expression</>
1917 is evaluated (once) and successively compared to each
1918 <replaceable>expression</> in the <literal>WHEN</> clauses.
1919 If a match is found, then the corresponding
1920 <replaceable>statements</replaceable> are executed, and then control
1921 passes to the next statement after <literal>END CASE</>. (Subsequent
1922 <literal>WHEN</> expressions are not evaluated.) If no match is
1923 found, the <literal>ELSE</> <replaceable>statements</replaceable> are
1924 executed; but if <literal>ELSE</> is not present, then a
1925 <literal>CASE_NOT_FOUND</literal> exception is raised.
1929 Here is a simple example:
1934 msg := 'one or two';
1936 msg := 'other value than one or two';
1943 <title>Searched <literal>CASE</></title>
1947 WHEN <replaceable>boolean-expression</replaceable> THEN
1948 <replaceable>statements</replaceable>
1949 <optional> WHEN <replaceable>boolean-expression</replaceable> THEN
1950 <replaceable>statements</replaceable>
1953 <replaceable>statements</replaceable> </optional>
1958 The searched form of <command>CASE</> provides conditional execution
1959 based on truth of Boolean expressions. Each <literal>WHEN</> clause's
1960 <replaceable>boolean-expression</replaceable> is evaluated in turn,
1961 until one is found that yields <literal>true</>. Then the
1962 corresponding <replaceable>statements</replaceable> are executed, and
1963 then control passes to the next statement after <literal>END CASE</>.
1964 (Subsequent <literal>WHEN</> expressions are not evaluated.)
1965 If no true result is found, the <literal>ELSE</>
1966 <replaceable>statements</replaceable> are executed;
1967 but if <literal>ELSE</> is not present, then a
1968 <literal>CASE_NOT_FOUND</literal> exception is raised.
1976 WHEN x BETWEEN 0 AND 10 THEN
1977 msg := 'value is between zero and ten';
1978 WHEN x BETWEEN 11 AND 20 THEN
1979 msg := 'value is between eleven and twenty';
1985 This form of <command>CASE</> is entirely equivalent to
1986 <literal>IF-THEN-ELSIF</>, except for the rule that reaching
1987 an omitted <literal>ELSE</> clause results in an error rather
1994 <sect2 id="plpgsql-control-structures-loops">
1995 <title>Simple Loops</title>
1997 <indexterm zone="plpgsql-control-structures-loops">
1998 <primary>loop</primary>
1999 <secondary>in PL/pgSQL</secondary>
2003 With the <literal>LOOP</>, <literal>EXIT</>,
2004 <literal>CONTINUE</>, <literal>WHILE</>, <literal>FOR</>,
2005 and <literal>FOREACH</> statements, you can arrange for your
2006 <application>PL/pgSQL</> function to repeat a series of commands.
2010 <title><literal>LOOP</></title>
2013 <optional> <<<replaceable>label</replaceable>>> </optional>
2015 <replaceable>statements</replaceable>
2016 END LOOP <optional> <replaceable>label</replaceable> </optional>;
2020 <literal>LOOP</> defines an unconditional loop that is repeated
2021 indefinitely until terminated by an <literal>EXIT</> or
2022 <command>RETURN</command> statement. The optional
2023 <replaceable>label</replaceable> can be used by <literal>EXIT</>
2024 and <literal>CONTINUE</literal> statements within nested loops to
2025 specify which loop those statements refer to.
2030 <title><literal>EXIT</></title>
2033 <primary>EXIT</primary>
2034 <secondary>in PL/pgSQL</secondary>
2038 EXIT <optional> <replaceable>label</replaceable> </optional> <optional> WHEN <replaceable>boolean-expression</replaceable> </optional>;
2042 If no <replaceable>label</replaceable> is given, the innermost
2043 loop is terminated and the statement following <literal>END
2044 LOOP</> is executed next. If <replaceable>label</replaceable>
2045 is given, it must be the label of the current or some outer
2046 level of nested loop or block. Then the named loop or block is
2047 terminated and control continues with the statement after the
2048 loop's/block's corresponding <literal>END</>.
2052 If <literal>WHEN</> is specified, the loop exit occurs only if
2053 <replaceable>boolean-expression</> is true. Otherwise, control passes
2054 to the statement after <literal>EXIT</>.
2058 <literal>EXIT</> can be used with all types of loops; it is
2059 not limited to use with unconditional loops.
2064 <literal>BEGIN</literal> block, <literal>EXIT</literal> passes
2065 control to the next statement after the end of the block.
2066 Note that a label must be used for this purpose; an unlabelled
2067 <literal>EXIT</literal> is never considered to match a
2068 <literal>BEGIN</literal> block. (This is a change from
2069 pre-8.4 releases of <productname>PostgreSQL</productname>, which
2070 would allow an unlabelled <literal>EXIT</literal> to match
2071 a <literal>BEGIN</literal> block.)
2078 -- some computations
2079 IF count > 0 THEN
2085 -- some computations
2086 EXIT WHEN count > 0; -- same result as previous example
2089 <<ablock>>
2091 -- some computations
2092 IF stocks > 100000 THEN
2093 EXIT ablock; -- causes exit from the BEGIN block
2095 -- computations here will be skipped when stocks > 100000
2102 <title><literal>CONTINUE</></title>
2105 <primary>CONTINUE</primary>
2106 <secondary>in PL/pgSQL</secondary>
2110 CONTINUE <optional> <replaceable>label</replaceable> </optional> <optional> WHEN <replaceable>boolean-expression</replaceable> </optional>;
2114 If no <replaceable>label</> is given, the next iteration of
2115 the innermost loop is begun. That is, all statements remaining
2116 in the loop body are skipped, and control returns
2117 to the loop control expression (if any) to determine whether
2118 another loop iteration is needed.
2119 If <replaceable>label</> is present, it
2120 specifies the label of the loop whose execution will be
2125 If <literal>WHEN</> is specified, the next iteration of the
2126 loop is begun only if <replaceable>boolean-expression</> is
2127 true. Otherwise, control passes to the statement after
2128 <literal>CONTINUE</>.
2132 <literal>CONTINUE</> can be used with all types of loops; it
2133 is not limited to use with unconditional loops.
2140 -- some computations
2141 EXIT WHEN count > 100;
2142 CONTINUE WHEN count < 50;
2143 -- some computations for count IN [50 .. 100]
2151 <title><literal>WHILE</></title>
2154 <primary>WHILE</primary>
2155 <secondary>in PL/pgSQL</secondary>
2159 <optional> <<<replaceable>label</replaceable>>> </optional>
2160 WHILE <replaceable>boolean-expression</replaceable> LOOP
2161 <replaceable>statements</replaceable>
2162 END LOOP <optional> <replaceable>label</replaceable> </optional>;
2166 The <literal>WHILE</> statement repeats a
2167 sequence of statements so long as the
2168 <replaceable>boolean-expression</replaceable>
2169 evaluates to true. The expression is checked just before
2170 each entry to the loop body.
2176 WHILE amount_owed > 0 AND gift_certificate_balance > 0 LOOP
2177 -- some computations here
2181 -- some computations here
2187 <sect3 id="plpgsql-integer-for">
2188 <title><literal>FOR</> (Integer Variant)</title>
2191 <optional> <<<replaceable>label</replaceable>>> </optional>
2192 FOR <replaceable>name</replaceable> IN <optional> REVERSE </optional> <replaceable>expression</replaceable> .. <replaceable>expression</replaceable> <optional> BY <replaceable>expression</replaceable> </optional> LOOP
2193 <replaceable>statements</replaceable>
2194 END LOOP <optional> <replaceable>label</replaceable> </optional>;
2198 This form of <literal>FOR</> creates a loop that iterates over a range
2199 of integer values. The variable
2200 <replaceable>name</replaceable> is automatically defined as type
2201 <type>integer</> and exists only inside the loop (any existing
2202 definition of the variable name is ignored within the loop).
2203 The two expressions giving
2204 the lower and upper bound of the range are evaluated once when entering
2205 the loop. If the <literal>BY</> clause isn't specified the iteration
2206 step is 1, otherwise it's the value specified in the <literal>BY</>
2207 clause, which again is evaluated once on loop entry.
2208 If <literal>REVERSE</> is specified then the step value is
2209 subtracted, rather than added, after each iteration.
2213 Some examples of integer <literal>FOR</> loops:
2216 -- i will take on the values 1,2,3,4,5,6,7,8,9,10 within the loop
2219 FOR i IN REVERSE 10..1 LOOP
2220 -- i will take on the values 10,9,8,7,6,5,4,3,2,1 within the loop
2223 FOR i IN REVERSE 10..1 BY 2 LOOP
2224 -- i will take on the values 10,8,6,4,2 within the loop
2230 If the lower bound is greater than the upper bound (or less than,
2231 in the <literal>REVERSE</> case), the loop body is not
2232 executed at all. No error is raised.
2236 If a <replaceable>label</replaceable> is attached to the
2237 <literal>FOR</> loop then the integer loop variable can be
2238 referenced with a qualified name, using that
2239 <replaceable>label</replaceable>.
2244 <sect2 id="plpgsql-records-iterating">
2245 <title>Looping Through Query Results</title>
2248 Using a different type of <literal>FOR</> loop, you can iterate through
2249 the results of a query and manipulate that data
2250 accordingly. The syntax is:
2252 <optional> <<<replaceable>label</replaceable>>> </optional>
2253 FOR <replaceable>target</replaceable> IN <replaceable>query</replaceable> LOOP
2254 <replaceable>statements</replaceable>
2255 END LOOP <optional> <replaceable>label</replaceable> </optional>;
2257 The <replaceable>target</replaceable> is a record variable, row variable,
2258 or comma-separated list of scalar variables.
2259 The <replaceable>target</replaceable> is successively assigned each row
2260 resulting from the <replaceable>query</replaceable> and the loop body is
2261 executed for each row. Here is an example:
2263 CREATE FUNCTION cs_refresh_mviews() RETURNS integer AS $$
2267 RAISE NOTICE 'Refreshing materialized views...';
2269 FOR mviews IN SELECT * FROM cs_materialized_views ORDER BY sort_key LOOP
2271 -- Now "mviews" has one record from cs_materialized_views
2273 RAISE NOTICE 'Refreshing materialized view %s ...', quote_ident(mviews.mv_name);
2274 EXECUTE 'TRUNCATE TABLE ' || quote_ident(mviews.mv_name);
2275 EXECUTE 'INSERT INTO '
2276 || quote_ident(mviews.mv_name) || ' '
2280 RAISE NOTICE 'Done refreshing materialized views.';
2283 $$ LANGUAGE plpgsql;
2286 If the loop is terminated by an <literal>EXIT</> statement, the last
2287 assigned row value is still accessible after the loop.
2291 The <replaceable>query</replaceable> used in this type of <literal>FOR</>
2292 statement can be any SQL command that returns rows to the caller:
2293 <command>SELECT</> is the most common case,
2294 but you can also use <command>INSERT</>, <command>UPDATE</>, or
2295 <command>DELETE</> with a <literal>RETURNING</> clause. Some utility
2296 commands such as <command>EXPLAIN</> will work too.
2300 <application>PL/pgSQL</> variables are substituted into the query text,
2301 and the query plan is cached for possible re-use, as discussed in
2302 detail in <xref linkend="plpgsql-var-subst"> and
2303 <xref linkend="plpgsql-plan-caching">.
2307 The <literal>FOR-IN-EXECUTE</> statement is another way to iterate over
2310 <optional> <<<replaceable>label</replaceable>>> </optional>
2311 FOR <replaceable>target</replaceable> IN EXECUTE <replaceable>text_expression</replaceable> <optional> USING <replaceable>expression</replaceable> <optional>, ... </optional> </optional> LOOP
2312 <replaceable>statements</replaceable>
2313 END LOOP <optional> <replaceable>label</replaceable> </optional>;
2315 This is like the previous form, except that the source query
2316 is specified as a string expression, which is evaluated and replanned
2317 on each entry to the <literal>FOR</> loop. This allows the programmer to
2318 choose the speed of a preplanned query or the flexibility of a dynamic
2319 query, just as with a plain <command>EXECUTE</command> statement.
2320 As with <command>EXECUTE</command>, parameter values can be inserted
2321 into the dynamic command via <literal>USING</>.
2325 Another way to specify the query whose results should be iterated
2326 through is to declare it as a cursor. This is described in
2327 <xref linkend="plpgsql-cursor-for-loop">.
2331 <sect2 id="plpgsql-foreach-array">
2332 <title>Looping Through Arrays</title>
2335 The <literal>FOREACH</> loop is much like a <literal>FOR</> loop,
2336 but instead of iterating through the rows returned by a SQL query,
2337 it iterates through the elements of an array value.
2338 (In general, <literal>FOREACH</> is meant for looping through
2339 components of a composite-valued expression; variants for looping
2340 through composites besides arrays may be added in future.)
2341 The <literal>FOREACH</> statement to loop over an array is:
2344 <optional> <<<replaceable>label</replaceable>>> </optional>
2345 FOREACH <replaceable>target</replaceable> <optional> SLICE <replaceable>number</replaceable> </optional> IN ARRAY <replaceable>expression</replaceable> LOOP
2346 <replaceable>statements</replaceable>
2347 END LOOP <optional> <replaceable>label</replaceable> </optional>;
2352 Without <literal>SLICE</>, or if <literal>SLICE 0</> is specified,
2353 the loop iterates through individual elements of the array produced
2354 by evaluating the <replaceable>expression</replaceable>.
2355 The <replaceable>target</replaceable> variable is assigned each
2356 element value in sequence, and the loop body is executed for each element.
2357 Here is an example of looping through the elements of an integer
2361 CREATE FUNCTION sum(int[]) RETURNS int8 AS $$
2366 FOREACH x IN ARRAY $1
2372 $$ LANGUAGE plpgsql;
2375 The elements are visited in storage order, regardless of the number of
2376 array dimensions. Although the <replaceable>target</replaceable> is
2377 usually just a single variable, it can be a list of variables when
2378 looping through an array of composite values (records). In that case,
2379 for each array element, the variables are assigned from successive
2380 columns of the composite value.
2384 With a positive <literal>SLICE</> value, <literal>FOREACH</>
2385 iterates through slices of the array rather than single elements.
2386 The <literal>SLICE</> value must be an integer constant not larger
2387 than the number of dimensions of the array. The
2388 <replaceable>target</replaceable> variable must be an array,
2389 and it receives successive slices of the array value, where each slice
2390 is of the number of dimensions specified by <literal>SLICE</>.
2391 Here is an example of iterating through one-dimensional slices:
2394 CREATE FUNCTION scan_rows(int[]) RETURNS void AS $$
2398 FOREACH x SLICE 1 IN ARRAY $1
2400 RAISE NOTICE 'row = %', x;
2403 $$ LANGUAGE plpgsql;
2405 SELECT scan_rows(ARRAY[[1,2,3],[4,5,6],[7,8,9],[10,11,12]]);
2407 NOTICE: row = {1,2,3}
2408 NOTICE: row = {4,5,6}
2409 NOTICE: row = {7,8,9}
2410 NOTICE: row = {10,11,12}
2415 <sect2 id="plpgsql-error-trapping">
2416 <title>Trapping Errors</title>
2419 <primary>exceptions</primary>
2420 <secondary>in PL/pgSQL</secondary>
2424 By default, any error occurring in a <application>PL/pgSQL</>
2425 function aborts execution of the function, and indeed of the
2426 surrounding transaction as well. You can trap errors and recover
2427 from them by using a <command>BEGIN</> block with an
2428 <literal>EXCEPTION</> clause. The syntax is an extension of the
2429 normal syntax for a <command>BEGIN</> block:
2432 <optional> <<<replaceable>label</replaceable>>> </optional>
2434 <replaceable>declarations</replaceable> </optional>
2436 <replaceable>statements</replaceable>
2438 WHEN <replaceable>condition</replaceable> <optional> OR <replaceable>condition</replaceable> ... </optional> THEN
2439 <replaceable>handler_statements</replaceable>
2440 <optional> WHEN <replaceable>condition</replaceable> <optional> OR <replaceable>condition</replaceable> ... </optional> THEN
2441 <replaceable>handler_statements</replaceable>
2448 If no error occurs, this form of block simply executes all the
2449 <replaceable>statements</replaceable>, and then control passes
2450 to the next statement after <literal>END</>. But if an error
2451 occurs within the <replaceable>statements</replaceable>, further
2452 processing of the <replaceable>statements</replaceable> is
2453 abandoned, and control passes to the <literal>EXCEPTION</> list.
2454 The list is searched for the first <replaceable>condition</replaceable>
2455 matching the error that occurred. If a match is found, the
2456 corresponding <replaceable>handler_statements</replaceable> are
2457 executed, and then control passes to the next statement after
2458 <literal>END</>. If no match is found, the error propagates out
2459 as though the <literal>EXCEPTION</> clause were not there at all:
2460 the error can be caught by an enclosing block with
2461 <literal>EXCEPTION</>, or if there is none it aborts processing
2466 The <replaceable>condition</replaceable> names can be any of
2467 those shown in <xref linkend="errcodes-appendix">. A category
2468 name matches any error within its category. The special
2469 condition name <literal>OTHERS</> matches every error type except
2470 <literal>QUERY_CANCELED</>. (It is possible, but often unwise,
2471 to trap <literal>QUERY_CANCELED</> by name.) Condition names are
2472 not case-sensitive. Also, an error condition can be specified
2473 by <literal>SQLSTATE</> code; for example these are equivalent:
2475 WHEN division_by_zero THEN ...
2476 WHEN SQLSTATE '22012' THEN ...
2481 If a new error occurs within the selected
2482 <replaceable>handler_statements</replaceable>, it cannot be caught
2483 by this <literal>EXCEPTION</> clause, but is propagated out.
2484 A surrounding <literal>EXCEPTION</> clause could catch it.
2488 When an error is caught by an <literal>EXCEPTION</> clause,
2489 the local variables of the <application>PL/pgSQL</> function
2490 remain as they were when the error occurred, but all changes
2491 to persistent database state within the block are rolled back.
2492 As an example, consider this fragment:
2495 INSERT INTO mytab(firstname, lastname) VALUES('Tom', 'Jones');
2497 UPDATE mytab SET firstname = 'Joe' WHERE lastname = 'Jones';
2501 WHEN division_by_zero THEN
2502 RAISE NOTICE 'caught division_by_zero';
2507 When control reaches the assignment to <literal>y</>, it will
2508 fail with a <literal>division_by_zero</> error. This will be caught by
2509 the <literal>EXCEPTION</> clause. The value returned in the
2510 <command>RETURN</> statement will be the incremented value of
2511 <literal>x</>, but the effects of the <command>UPDATE</> command will
2512 have been rolled back. The <command>INSERT</> command preceding the
2513 block is not rolled back, however, so the end result is that the database
2514 contains <literal>Tom Jones</> not <literal>Joe Jones</>.
2519 A block containing an <literal>EXCEPTION</> clause is significantly
2520 more expensive to enter and exit than a block without one. Therefore,
2521 don't use <literal>EXCEPTION</> without need.
2525 <example id="plpgsql-upsert-example">
2526 <title>Exceptions with <command>UPDATE</>/<command>INSERT</></title>
2529 This example uses exception handling to perform either
2530 <command>UPDATE</> or <command>INSERT</>, as appropriate:
2533 CREATE TABLE db (a INT PRIMARY KEY, b TEXT);
2535 CREATE FUNCTION merge_db(key INT, data TEXT) RETURNS VOID AS
2539 -- first try to update the key
2540 UPDATE db SET b = data WHERE a = key;
2544 -- not there, so try to insert the key
2545 -- if someone else inserts the same key concurrently,
2546 -- we could get a unique-key failure
2548 INSERT INTO db(a,b) VALUES (key, data);
2550 EXCEPTION WHEN unique_violation THEN
2551 -- Do nothing, and loop to try the UPDATE again.
2558 SELECT merge_db(1, 'david');
2559 SELECT merge_db(1, 'dennis');
2562 This coding assumes the <literal>unique_violation</> error is caused by
2563 the <command>INSERT</>, and not by, say, an <command>INSERT</> in a
2564 trigger function on the table. It might also misbehave if there is
2565 more than one unique index on the table, since it will retry the
2566 operation regardless of which index caused the error.
2567 More safety could be had by using the
2568 features discussed next to check that the trapped error was the one
2573 <sect3 id="plpgsql-exception-diagnostics">
2574 <title>Obtaining information about an error</title>
2577 Exception handlers frequently need to identify the specific error that
2578 occurred. There are two ways to get information about the current
2579 exception in <application>PL/pgSQL</>: special variables and the
2580 <command>GET STACKED DIAGNOSTICS</command> command.
2584 Within an exception handler, the special variable
2585 <varname>SQLSTATE</varname> contains the error code that corresponds to
2586 the exception that was raised (refer to <xref linkend="errcodes-table">
2587 for a list of possible error codes). The special variable
2588 <varname>SQLERRM</varname> contains the error message associated with the
2589 exception. These variables are undefined outside exception handlers.
2593 Within an exception handler, one may also retrieve
2594 information about the current exception by using the
2595 <command>GET STACKED DIAGNOSTICS</command> command, which has the form:
2598 GET STACKED DIAGNOSTICS <replaceable>variable</replaceable> = <replaceable>item</replaceable> <optional> , ... </optional>;
2601 Each <replaceable>item</replaceable> is a key word identifying a status
2602 value to be assigned to the specified variable (which should be
2603 of the right data type to receive it). The currently available
2604 status items are shown in <xref linkend="plpgsql-exception-diagnostics-values">.
2607 <table id="plpgsql-exception-diagnostics-values">
2608 <title>Error diagnostics values</title>
2614 <entry>Description</entry>
2619 <entry><literal>RETURNED_SQLSTATE</literal></entry>
2621 <entry>the SQLSTATE error code of the exception</entry>
2624 <entry><literal>MESSAGE_TEXT</literal></entry>
2626 <entry>the text of the exception's primary message</entry>
2629 <entry><literal>PG_EXCEPTION_DETAIL</literal></entry>
2631 <entry>the text of the exception's detail message, if any</entry>
2634 <entry><literal>PG_EXCEPTION_HINT</literal></entry>
2636 <entry>the text of the exception's hint message, if any</entry>
2639 <entry><literal>PG_EXCEPTION_CONTEXT</literal></entry>
2641 <entry>line(s) of text describing the call stack</entry>
2648 If the exception did not set a value for an item, an empty string
2660 -- some processing which might cause an exception
2662 EXCEPTION WHEN OTHERS THEN
2663 GET STACKED DIAGNOSTICS text_var1 = MESSAGE_TEXT,
2664 text_var2 = PG_EXCEPTION_DETAIL,
2665 text_var3 = PG_EXCEPTION_HINT;
2673 <sect1 id="plpgsql-cursors">
2674 <title>Cursors</title>
2676 <indexterm zone="plpgsql-cursors">
2677 <primary>cursor</primary>
2678 <secondary>in PL/pgSQL</secondary>
2682 Rather than executing a whole query at once, it is possible to set
2683 up a <firstterm>cursor</> that encapsulates the query, and then read
2684 the query result a few rows at a time. One reason for doing this is
2685 to avoid memory overrun when the result contains a large number of
2686 rows. (However, <application>PL/pgSQL</> users do not normally need
2687 to worry about that, since <literal>FOR</> loops automatically use a cursor
2688 internally to avoid memory problems.) A more interesting usage is to
2689 return a reference to a cursor that a function has created, allowing the
2690 caller to read the rows. This provides an efficient way to return
2691 large row sets from functions.
2694 <sect2 id="plpgsql-cursor-declarations">
2695 <title>Declaring Cursor Variables</title>
2698 All access to cursors in <application>PL/pgSQL</> goes through
2699 cursor variables, which are always of the special data type
2700 <type>refcursor</>. One way to create a cursor variable
2701 is just to declare it as a variable of type <type>refcursor</>.
2702 Another way is to use the cursor declaration syntax,
2703 which in general is:
2705 <replaceable>name</replaceable> <optional> <optional> NO </optional> SCROLL </optional> CURSOR <optional> ( <replaceable>arguments</replaceable> ) </optional> FOR <replaceable>query</replaceable>;
2707 (<literal>FOR</> can be replaced by <literal>IS</> for
2708 <productname>Oracle</productname> compatibility.)
2709 If <literal>SCROLL</> is specified, the cursor will be capable of
2710 scrolling backward; if <literal>NO SCROLL</> is specified, backward
2711 fetches will be rejected; if neither specification appears, it is
2712 query-dependent whether backward fetches will be allowed.
2713 <replaceable>arguments</replaceable>, if specified, is a
2714 comma-separated list of pairs <literal><replaceable>name</replaceable>
2715 <replaceable>datatype</replaceable></literal> that define names to be
2716 replaced by parameter values in the given query. The actual
2717 values to substitute for these names will be specified later,
2718 when the cursor is opened.
2725 curs2 CURSOR FOR SELECT * FROM tenk1;
2726 curs3 CURSOR (key integer) FOR SELECT * FROM tenk1 WHERE unique1 = key;
2728 All three of these variables have the data type <type>refcursor</>,
2729 but the first can be used with any query, while the second has
2730 a fully specified query already <firstterm>bound</> to it, and the last
2731 has a parameterized query bound to it. (<literal>key</> will be
2732 replaced by an integer parameter value when the cursor is opened.)
2733 The variable <literal>curs1</>
2734 is said to be <firstterm>unbound</> since it is not bound to
2735 any particular query.
2739 <sect2 id="plpgsql-cursor-opening">
2740 <title>Opening Cursors</title>
2743 Before a cursor can be used to retrieve rows, it must be
2744 <firstterm>opened</>. (This is the equivalent action to the SQL
2745 command <command>DECLARE CURSOR</>.) <application>PL/pgSQL</> has
2746 three forms of the <command>OPEN</> statement, two of which use unbound
2747 cursor variables while the third uses a bound cursor variable.
2752 Bound cursor variables can also be used without explicitly opening the cursor,
2753 via the <command>FOR</> statement described in
2754 <xref linkend="plpgsql-cursor-for-loop">.
2759 <title><command>OPEN FOR</command> <replaceable>query</replaceable></title>
2762 OPEN <replaceable>unbound_cursorvar</replaceable> <optional> <optional> NO </optional> SCROLL </optional> FOR <replaceable>query</replaceable>;
2766 The cursor variable is opened and given the specified query to
2767 execute. The cursor cannot be open already, and it must have been
2768 declared as an unbound cursor variable (that is, as a simple
2769 <type>refcursor</> variable). The query must be a
2770 <command>SELECT</command>, or something else that returns rows
2771 (such as <command>EXPLAIN</>). The query
2772 is treated in the same way as other SQL commands in
2773 <application>PL/pgSQL</>: <application>PL/pgSQL</>
2774 variable names are substituted, and the query plan is cached for
2775 possible reuse. When a <application>PL/pgSQL</>
2776 variable is substituted into the cursor query, the value that is
2777 substituted is the one it has at the time of the <command>OPEN</>;
2778 subsequent changes to the variable will not affect the cursor's
2780 The <literal>SCROLL</> and <literal>NO SCROLL</>
2781 options have the same meanings as for a bound cursor.
2787 OPEN curs1 FOR SELECT * FROM foo WHERE key = mykey;
2793 <title><command>OPEN FOR EXECUTE</command></title>
2796 OPEN <replaceable>unbound_cursorvar</replaceable> <optional> <optional> NO </optional> SCROLL </optional> FOR EXECUTE <replaceable class="command">query_string</replaceable>
2797 <optional> USING <replaceable>expression</replaceable> <optional>, ... </optional> </optional>;
2801 The cursor variable is opened and given the specified query to
2802 execute. The cursor cannot be open already, and it must have been
2803 declared as an unbound cursor variable (that is, as a simple
2804 <type>refcursor</> variable). The query is specified as a string
2805 expression, in the same way as in the <command>EXECUTE</command>
2806 command. As usual, this gives flexibility so the query plan can vary
2807 from one run to the next (see <xref linkend="plpgsql-plan-caching">),
2808 and it also means that variable substitution is not done on the
2809 command string. As with <command>EXECUTE</command>, parameter values
2810 can be inserted into the dynamic command via <literal>USING</>.
2811 The <literal>SCROLL</> and
2812 <literal>NO SCROLL</> options have the same meanings as for a bound
2819 OPEN curs1 FOR EXECUTE 'SELECT * FROM ' || quote_ident(tabname)
2820 || ' WHERE col1 = $1' USING keyvalue;
2822 In this example, the table name is inserted into the query textually,
2823 so use of <function>quote_ident()</> is recommended to guard against
2824 SQL injection. The comparison value for <literal>col1</> is inserted
2825 via a <literal>USING</> parameter, so it needs no quoting.
2829 <sect3 id="plpgsql-open-bound-cursor">
2830 <title>Opening a Bound Cursor</title>
2833 OPEN <replaceable>bound_cursorvar</replaceable> <optional> ( <optional> <replaceable>argument_name</replaceable> := </optional> <replaceable>argument_value</replaceable> <optional>, ...</optional> ) </optional>;
2837 This form of <command>OPEN</command> is used to open a cursor
2838 variable whose query was bound to it when it was declared. The
2839 cursor cannot be open already. A list of actual argument value
2840 expressions must appear if and only if the cursor was declared to
2841 take arguments. These values will be substituted in the query.
2845 The query plan for a bound cursor is always considered cacheable;
2846 there is no equivalent of <command>EXECUTE</command> in this case.
2847 Notice that <literal>SCROLL</> and <literal>NO SCROLL</> cannot be
2848 specified in <command>OPEN</>, as the cursor's scrolling
2849 behavior was already determined.
2853 Argument values can be passed using either <firstterm>positional</firstterm>
2854 or <firstterm>named</firstterm> notation. In positional
2855 notation, all arguments are specified in order. In named notation,
2856 each argument's name is specified using <literal>:=</literal> to
2857 separate it from the argument expression. Similar to calling
2858 functions, described in <xref linkend="sql-syntax-calling-funcs">, it
2859 is also allowed to mix positional and named notation.
2863 Examples (these use the cursor declaration examples above):
2867 OPEN curs3(key := 42);
2872 Because variable substitution is done on a bound cursor's query,
2873 there are really two ways to pass values into the cursor: either
2874 with an explicit argument to <command>OPEN</>, or implicitly by
2875 referencing a <application>PL/pgSQL</> variable in the query.
2876 However, only variables declared before the bound cursor was
2877 declared will be substituted into it. In either case the value to
2878 be passed is determined at the time of the <command>OPEN</>.
2879 For example, another way to get the same effect as the
2880 <literal>curs3</> example above is
2884 curs4 CURSOR FOR SELECT * FROM tenk1 WHERE unique1 = key;
2893 <sect2 id="plpgsql-cursor-using">
2894 <title>Using Cursors</title>
2897 Once a cursor has been opened, it can be manipulated with the
2898 statements described here.
2902 These manipulations need not occur in the same function that
2903 opened the cursor to begin with. You can return a <type>refcursor</>
2904 value out of a function and let the caller operate on the cursor.
2905 (Internally, a <type>refcursor</> value is simply the string name
2906 of a so-called portal containing the active query for the cursor. This name
2907 can be passed around, assigned to other <type>refcursor</> variables,
2908 and so on, without disturbing the portal.)
2912 All portals are implicitly closed at transaction end. Therefore
2913 a <type>refcursor</> value is usable to reference an open cursor
2914 only until the end of the transaction.
2918 <title><literal>FETCH</></title>
2921 FETCH <optional> <replaceable>direction</replaceable> { FROM | IN } </optional> <replaceable>cursor</replaceable> INTO <replaceable>target</replaceable>;
2925 <command>FETCH</command> retrieves the next row from the
2926 cursor into a target, which might be a row variable, a record
2927 variable, or a comma-separated list of simple variables, just like
2928 <command>SELECT INTO</command>. If there is no next row, the
2929 target is set to NULL(s). As with <command>SELECT
2930 INTO</command>, the special variable <literal>FOUND</literal> can
2931 be checked to see whether a row was obtained or not.
2935 The <replaceable>direction</replaceable> clause can be any of the
2936 variants allowed in the SQL <xref linkend="sql-fetch">
2937 command except the ones that can fetch
2938 more than one row; namely, it can be
2943 <literal>ABSOLUTE</> <replaceable>count</replaceable>,
2944 <literal>RELATIVE</> <replaceable>count</replaceable>,
2945 <literal>FORWARD</>, or
2946 <literal>BACKWARD</>.
2947 Omitting <replaceable>direction</replaceable> is the same
2948 as specifying <literal>NEXT</>.
2949 <replaceable>direction</replaceable> values that require moving
2950 backward are likely to fail unless the cursor was declared or opened
2951 with the <literal>SCROLL</> option.
2955 <replaceable>cursor</replaceable> must be the name of a <type>refcursor</>
2956 variable that references an open cursor portal.
2962 FETCH curs1 INTO rowvar;
2963 FETCH curs2 INTO foo, bar, baz;
2964 FETCH LAST FROM curs3 INTO x, y;
2965 FETCH RELATIVE -2 FROM curs4 INTO x;
2971 <title><literal>MOVE</></title>
2974 MOVE <optional> <replaceable>direction</replaceable> { FROM | IN } </optional> <replaceable>cursor</replaceable>;
2978 <command>MOVE</command> repositions a cursor without retrieving
2979 any data. <command>MOVE</command> works exactly like the
2980 <command>FETCH</command> command, except it only repositions the
2981 cursor and does not return the row moved to. As with <command>SELECT
2982 INTO</command>, the special variable <literal>FOUND</literal> can
2983 be checked to see whether there was a next row to move to.
2987 The <replaceable>direction</replaceable> clause can be any of the
2988 variants allowed in the SQL <xref linkend="sql-fetch">
2994 <literal>ABSOLUTE</> <replaceable>count</replaceable>,
2995 <literal>RELATIVE</> <replaceable>count</replaceable>,
2997 <literal>FORWARD</> <optional> <replaceable>count</replaceable> | <literal>ALL</> </optional>, or
2998 <literal>BACKWARD</> <optional> <replaceable>count</replaceable> | <literal>ALL</> </optional>.
2999 Omitting <replaceable>direction</replaceable> is the same
3000 as specifying <literal>NEXT</>.
3001 <replaceable>direction</replaceable> values that require moving
3002 backward are likely to fail unless the cursor was declared or opened
3003 with the <literal>SCROLL</> option.
3010 MOVE LAST FROM curs3;
3011 MOVE RELATIVE -2 FROM curs4;
3012 MOVE FORWARD 2 FROM curs4;
3018 <title><literal>UPDATE/DELETE WHERE CURRENT OF</></title>
3021 UPDATE <replaceable>table</replaceable> SET ... WHERE CURRENT OF <replaceable>cursor</replaceable>;
3022 DELETE FROM <replaceable>table</replaceable> WHERE CURRENT OF <replaceable>cursor</replaceable>;
3026 When a cursor is positioned on a table row, that row can be updated
3027 or deleted using the cursor to identify the row. There are
3028 restrictions on what the cursor's query can be (in particular,
3029 no grouping) and it's best to use <literal>FOR UPDATE</> in the
3030 cursor. For more information see the
3031 <xref linkend="sql-declare">
3038 UPDATE foo SET dataval = myval WHERE CURRENT OF curs1;
3044 <title><literal>CLOSE</></title>
3047 CLOSE <replaceable>cursor</replaceable>;
3051 <command>CLOSE</command> closes the portal underlying an open
3052 cursor. This can be used to release resources earlier than end of
3053 transaction, or to free up the cursor variable to be opened again.
3065 <title>Returning Cursors</title>
3068 <application>PL/pgSQL</> functions can return cursors to the
3069 caller. This is useful to return multiple rows or columns,
3070 especially with very large result sets. To do this, the function
3071 opens the cursor and returns the cursor name to the caller (or simply
3072 opens the cursor using a portal name specified by or otherwise known
3073 to the caller). The caller can then fetch rows from the cursor. The
3074 cursor can be closed by the caller, or it will be closed automatically
3075 when the transaction closes.
3079 The portal name used for a cursor can be specified by the
3080 programmer or automatically generated. To specify a portal name,
3081 simply assign a string to the <type>refcursor</> variable before
3082 opening it. The string value of the <type>refcursor</> variable
3083 will be used by <command>OPEN</> as the name of the underlying portal.
3084 However, if the <type>refcursor</> variable is null,
3085 <command>OPEN</> automatically generates a name that does not
3086 conflict with any existing portal, and assigns it to the
3087 <type>refcursor</> variable.
3092 A bound cursor variable is initialized to the string value
3093 representing its name, so that the portal name is the same as
3094 the cursor variable name, unless the programmer overrides it
3095 by assignment before opening the cursor. But an unbound cursor
3096 variable defaults to the null value initially, so it will receive
3097 an automatically-generated unique name, unless overridden.
3102 The following example shows one way a cursor name can be supplied by
3106 CREATE TABLE test (col text);
3107 INSERT INTO test VALUES ('123');
3109 CREATE FUNCTION reffunc(refcursor) RETURNS refcursor AS '
3111 OPEN $1 FOR SELECT col FROM test;
3117 SELECT reffunc('funccursor');
3118 FETCH ALL IN funccursor;
3124 The following example uses automatic cursor name generation:
3127 CREATE FUNCTION reffunc2() RETURNS refcursor AS '
3131 OPEN ref FOR SELECT col FROM test;
3136 -- need to be in a transaction to use cursors.
3141 --------------------
3142 <unnamed cursor 1>
3145 FETCH ALL IN "<unnamed cursor 1>";
3151 The following example shows one way to return multiple cursors
3152 from a single function:
3155 CREATE FUNCTION myfunc(refcursor, refcursor) RETURNS SETOF refcursor AS $$
3157 OPEN $1 FOR SELECT * FROM table_1;
3159 OPEN $2 FOR SELECT * FROM table_2;
3162 $$ LANGUAGE plpgsql;
3164 -- need to be in a transaction to use cursors.
3167 SELECT * FROM myfunc('a', 'b');
3177 <sect2 id="plpgsql-cursor-for-loop">
3178 <title>Looping Through a Cursor's Result</title>
3181 There is a variant of the <command>FOR</> statement that allows
3182 iterating through the rows returned by a cursor. The syntax is:
3185 <optional> <<<replaceable>label</replaceable>>> </optional>
3186 FOR <replaceable>recordvar</replaceable> IN <replaceable>bound_cursorvar</replaceable> <optional> ( <optional> <replaceable>argument_name</replaceable> := </optional> <replaceable>argument_value</replaceable> <optional>, ...</optional> ) </optional> LOOP
3187 <replaceable>statements</replaceable>
3188 END LOOP <optional> <replaceable>label</replaceable> </optional>;
3191 The cursor variable must have been bound to some query when it was
3192 declared, and it <emphasis>cannot</> be open already. The
3193 <command>FOR</> statement automatically opens the cursor, and it closes
3194 the cursor again when the loop exits. A list of actual argument value
3195 expressions must appear if and only if the cursor was declared to take
3196 arguments. These values will be substituted in the query, in just
3197 the same way as during an <command>OPEN</> (see <xref
3198 linkend="plpgsql-open-bound-cursor">).
3202 The variable <replaceable>recordvar</replaceable> is automatically
3203 defined as type <type>record</> and exists only inside the loop (any
3204 existing definition of the variable name is ignored within the loop).
3205 Each row returned by the cursor is successively assigned to this
3206 record variable and the loop body is executed.
3212 <sect1 id="plpgsql-errors-and-messages">
3213 <title>Errors and Messages</title>
3216 <primary>RAISE</primary>
3220 <primary>reporting errors</primary>
3221 <secondary>in PL/pgSQL</secondary>
3225 Use the <command>RAISE</command> statement to report messages and
3229 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>;
3230 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>;
3231 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>;
3232 RAISE <optional> <replaceable class="parameter">level</replaceable> </optional> USING <replaceable class="parameter">option</replaceable> = <replaceable class="parameter">expression</replaceable> <optional>, ... </optional>;
3236 The <replaceable class="parameter">level</replaceable> option specifies
3237 the error severity. Allowed levels are <literal>DEBUG</literal>,
3238 <literal>LOG</literal>, <literal>INFO</literal>,
3239 <literal>NOTICE</literal>, <literal>WARNING</literal>,
3240 and <literal>EXCEPTION</literal>, with <literal>EXCEPTION</literal>
3242 <literal>EXCEPTION</literal> raises an error (which normally aborts the
3243 current transaction); the other levels only generate messages of different
3245 Whether messages of a particular priority are reported to the client,
3246 written to the server log, or both is controlled by the
3247 <xref linkend="guc-log-min-messages"> and
3248 <xref linkend="guc-client-min-messages"> configuration
3249 variables. See <xref linkend="runtime-config"> for more
3254 After <replaceable class="parameter">level</replaceable> if any,
3255 you can write a <replaceable class="parameter">format</replaceable>
3256 (which must be a simple string literal, not an expression). The
3257 format string specifies the error message text to be reported.
3258 The format string can be followed
3259 by optional argument expressions to be inserted into the message.
3260 Inside the format string, <literal>%</literal> is replaced by the
3261 string representation of the next optional argument's value. Write
3262 <literal>%%</literal> to emit a literal <literal>%</literal>.
3266 In this example, the value of <literal>v_job_id</> will replace the
3267 <literal>%</literal> in the string:
3269 RAISE NOTICE 'Calling cs_create_job(%)', v_job_id;
3274 You can attach additional information to the error report by writing
3275 <literal>USING</> followed by <replaceable
3276 class="parameter">option</replaceable> = <replaceable
3277 class="parameter">expression</replaceable> items. The allowed
3278 <replaceable class="parameter">option</replaceable> keywords are
3279 <literal>MESSAGE</>, <literal>DETAIL</>, <literal>HINT</>, and
3280 <literal>ERRCODE</>, while each <replaceable
3281 class="parameter">expression</replaceable> can be any string-valued
3283 <literal>MESSAGE</> sets the error message text (this option can't
3284 be used in the form of <command>RAISE</> that includes a format
3285 string before <literal>USING</>).
3286 <literal>DETAIL</> supplies an error detail message, while
3287 <literal>HINT</> supplies a hint message.
3288 <literal>ERRCODE</> specifies the error code (SQLSTATE) to report,
3289 either by condition name as shown in <xref linkend="errcodes-appendix">,
3290 or directly as a five-character SQLSTATE code.
3294 This example will abort the transaction with the given error message
3297 RAISE EXCEPTION 'Nonexistent ID --> %', user_id
3298 USING HINT = 'Please check your user ID';
3303 These two examples show equivalent ways of setting the SQLSTATE:
3305 RAISE 'Duplicate user ID: %', user_id USING ERRCODE = 'unique_violation';
3306 RAISE 'Duplicate user ID: %', user_id USING ERRCODE = '23505';
3311 There is a second <command>RAISE</> syntax in which the main argument
3312 is the condition name or SQLSTATE to be reported, for example:
3314 RAISE division_by_zero;
3315 RAISE SQLSTATE '22012';
3317 In this syntax, <literal>USING</> can be used to supply a custom
3318 error message, detail, or hint. Another way to do the earlier
3321 RAISE unique_violation USING MESSAGE = 'Duplicate user ID: ' || user_id;
3326 Still another variant is to write <literal>RAISE USING</> or <literal>RAISE
3327 <replaceable class="parameter">level</replaceable> USING</> and put
3328 everything else into the <literal>USING</> list.
3332 The last variant of <command>RAISE</> has no parameters at all.
3333 This form can only be used inside a <literal>BEGIN</> block's
3334 <literal>EXCEPTION</> clause;
3335 it causes the error currently being handled to be re-thrown.
3340 Before <productname>PostgreSQL</> 9.1, <command>RAISE</> without
3341 parameters was interpreted as re-throwing the error from the block
3342 containing the active exception handler. Thus an <literal>EXCEPTION</>
3343 clause nested within that handler could not catch it, even if the
3344 <command>RAISE</> was within the nested <literal>EXCEPTION</> clause's
3345 block. This was deemed surprising as well as being incompatible with
3351 If no condition name nor SQLSTATE is specified in a
3352 <command>RAISE EXCEPTION</command> command, the default is to use
3353 <literal>RAISE_EXCEPTION</> (<literal>P0001</>). If no message
3354 text is specified, the default is to use the condition name or
3355 SQLSTATE as message text.
3360 When specifying an error code by SQLSTATE code, you are not
3361 limited to the predefined error codes, but can select any
3362 error code consisting of five digits and/or upper-case ASCII
3363 letters, other than <literal>00000</>. It is recommended that
3364 you avoid throwing error codes that end in three zeroes, because
3365 these are category codes and can only be trapped by trapping
3372 <sect1 id="plpgsql-trigger">
3373 <title>Trigger Procedures</title>
3375 <indexterm zone="plpgsql-trigger">
3376 <primary>trigger</primary>
3377 <secondary>in PL/pgSQL</secondary>
3380 <sect2 id="plpgsql-dml-trigger">
3381 <title>Triggers on data changes</title>
3384 <application>PL/pgSQL</application> can be used to define trigger
3385 procedures. A trigger procedure is created with the
3386 <command>CREATE FUNCTION</> command, declaring it as a function with
3387 no arguments and a return type of <type>trigger</type>. Note that
3388 the function must be declared with no arguments even if it expects
3389 to receive arguments specified in <command>CREATE TRIGGER</> —
3390 trigger arguments are passed via <varname>TG_ARGV</>, as described
3395 When a <application>PL/pgSQL</application> function is called as a
3396 trigger, several special variables are created automatically in the
3397 top-level block. They are:
3401 <term><varname>NEW</varname></term>
3404 Data type <type>RECORD</type>; variable holding the new
3405 database row for <command>INSERT</>/<command>UPDATE</> operations in row-level
3406 triggers. This variable is <symbol>NULL</symbol> in statement-level triggers
3407 and for <command>DELETE</command> operations.
3413 <term><varname>OLD</varname></term>
3416 Data type <type>RECORD</type>; variable holding the old
3417 database row for <command>UPDATE</>/<command>DELETE</> operations in row-level
3418 triggers. This variable is <symbol>NULL</symbol> in statement-level triggers
3419 and for <command>INSERT</command> operations.
3425 <term><varname>TG_NAME</varname></term>
3428 Data type <type>name</type>; variable that contains the name of the trigger actually
3435 <term><varname>TG_WHEN</varname></term>
3438 Data type <type>text</type>; a string of
3439 <literal>BEFORE</literal>, <literal>AFTER</literal>, or
3440 <literal>INSTEAD OF</literal>, depending on the trigger's definition.
3446 <term><varname>TG_LEVEL</varname></term>
3449 Data type <type>text</type>; a string of either
3450 <literal>ROW</literal> or <literal>STATEMENT</literal>
3451 depending on the trigger's definition.
3457 <term><varname>TG_OP</varname></term>
3460 Data type <type>text</type>; a string of
3461 <literal>INSERT</literal>, <literal>UPDATE</literal>,
3462 <literal>DELETE</literal>, or <literal>TRUNCATE</>
3463 telling for which operation the trigger was fired.
3469 <term><varname>TG_RELID</varname></term>
3472 Data type <type>oid</type>; the object ID of the table that caused the
3479 <term><varname>TG_RELNAME</varname></term>
3482 Data type <type>name</type>; the name of the table that caused the trigger
3483 invocation. This is now deprecated, and could disappear in a future
3484 release. Use <literal>TG_TABLE_NAME</> instead.
3490 <term><varname>TG_TABLE_NAME</varname></term>
3493 Data type <type>name</type>; the name of the table that
3494 caused the trigger invocation.
3500 <term><varname>TG_TABLE_SCHEMA</varname></term>
3503 Data type <type>name</type>; the name of the schema of the
3504 table that caused the trigger invocation.
3510 <term><varname>TG_NARGS</varname></term>
3513 Data type <type>integer</type>; the number of arguments given to the trigger
3514 procedure in the <command>CREATE TRIGGER</command> statement.
3520 <term><varname>TG_ARGV[]</varname></term>
3523 Data type array of <type>text</type>; the arguments from
3524 the <command>CREATE TRIGGER</command> statement.
3525 The index counts from 0. Invalid
3526 indexes (less than 0 or greater than or equal to <varname>tg_nargs</>)
3527 result in a null value.
3535 A trigger function must return either <symbol>NULL</symbol> or a
3536 record/row value having exactly the structure of the table the
3537 trigger was fired for.
3541 Row-level triggers fired <literal>BEFORE</> can return null to signal the
3542 trigger manager to skip the rest of the operation for this row
3543 (i.e., subsequent triggers are not fired, and the
3544 <command>INSERT</>/<command>UPDATE</>/<command>DELETE</> does not occur
3545 for this row). If a nonnull
3546 value is returned then the operation proceeds with that row value.
3547 Returning a row value different from the original value
3548 of <varname>NEW</> alters the row that will be inserted or
3549 updated. Thus, if the trigger function wants the triggering
3550 action to succeed normally without altering the row
3551 value, <varname>NEW</varname> (or a value equal thereto) has to be
3552 returned. To alter the row to be stored, it is possible to
3553 replace single values directly in <varname>NEW</> and return the
3554 modified <varname>NEW</>, or to build a complete new record/row to
3555 return. In the case of a before-trigger
3556 on <command>DELETE</command>, the returned value has no direct
3557 effect, but it has to be nonnull to allow the trigger action to
3558 proceed. Note that <varname>NEW</varname> is null
3559 in <command>DELETE</command> triggers, so returning that is
3560 usually not sensible. The usual idiom in <command>DELETE</command>
3561 triggers is to return <varname>OLD</varname>.
3565 <literal>INSTEAD OF</> triggers (which are always row-level triggers,
3566 and may only be used on views) can return null to signal that they did
3567 not perform any updates, and that the rest of the operation for this
3568 row should be skipped (i.e., subsequent triggers are not fired, and the
3569 row is not counted in the rows-affected status for the surrounding
3570 <command>INSERT</>/<command>UPDATE</>/<command>DELETE</>).
3571 Otherwise a nonnull value should be returned, to signal
3572 that the trigger performed the requested operation. For
3573 <command>INSERT</> and <command>UPDATE</> operations, the return value
3574 should be <varname>NEW</>, which the trigger function may modify to
3575 support <command>INSERT RETURNING</> and <command>UPDATE RETURNING</>
3576 (this will also affect the row value passed to any subsequent triggers).
3577 For <command>DELETE</> operations, the return value should be
3582 The return value of a row-level trigger
3583 fired <literal>AFTER</literal> or a statement-level trigger
3584 fired <literal>BEFORE</> or <literal>AFTER</> is
3585 always ignored; it might as well be null. However, any of these types of
3586 triggers might still abort the entire operation by raising an error.
3590 <xref linkend="plpgsql-trigger-example"> shows an example of a
3591 trigger procedure in <application>PL/pgSQL</application>.
3594 <example id="plpgsql-trigger-example">
3595 <title>A <application>PL/pgSQL</application> Trigger Procedure</title>
3598 This example trigger ensures that any time a row is inserted or updated
3599 in the table, the current user name and time are stamped into the
3600 row. And it checks that an employee's name is given and that the
3601 salary is a positive value.
3608 last_date timestamp,
3612 CREATE FUNCTION emp_stamp() RETURNS trigger AS $emp_stamp$
3614 -- Check that empname and salary are given
3615 IF NEW.empname IS NULL THEN
3616 RAISE EXCEPTION 'empname cannot be null';
3618 IF NEW.salary IS NULL THEN
3619 RAISE EXCEPTION '% cannot have null salary', NEW.empname;
3622 -- Who works for us when she must pay for it?
3623 IF NEW.salary < 0 THEN
3624 RAISE EXCEPTION '% cannot have a negative salary', NEW.empname;
3627 -- Remember who changed the payroll when
3628 NEW.last_date := current_timestamp;
3629 NEW.last_user := current_user;
3632 $emp_stamp$ LANGUAGE plpgsql;
3634 CREATE TRIGGER emp_stamp BEFORE INSERT OR UPDATE ON emp
3635 FOR EACH ROW EXECUTE PROCEDURE emp_stamp();
3640 Another way to log changes to a table involves creating a new table that
3641 holds a row for each insert, update, or delete that occurs. This approach
3642 can be thought of as auditing changes to a table.
3643 <xref linkend="plpgsql-trigger-audit-example"> shows an example of an
3644 audit trigger procedure in <application>PL/pgSQL</application>.
3647 <example id="plpgsql-trigger-audit-example">
3648 <title>A <application>PL/pgSQL</application> Trigger Procedure For Auditing</title>
3651 This example trigger ensures that any insert, update or delete of a row
3652 in the <literal>emp</literal> table is recorded (i.e., audited) in the <literal>emp_audit</literal> table.
3653 The current time and user name are stamped into the row, together with
3654 the type of operation performed on it.
3659 empname text NOT NULL,
3663 CREATE TABLE emp_audit(
3664 operation char(1) NOT NULL,
3665 stamp timestamp NOT NULL,
3666 userid text NOT NULL,
3667 empname text NOT NULL,
3671 CREATE OR REPLACE FUNCTION process_emp_audit() RETURNS TRIGGER AS $emp_audit$
3674 -- Create a row in emp_audit to reflect the operation performed on emp,
3675 -- make use of the special variable TG_OP to work out the operation.
3677 IF (TG_OP = 'DELETE') THEN
3678 INSERT INTO emp_audit SELECT 'D', now(), user, OLD.*;
3680 ELSIF (TG_OP = 'UPDATE') THEN
3681 INSERT INTO emp_audit SELECT 'U', now(), user, NEW.*;
3683 ELSIF (TG_OP = 'INSERT') THEN
3684 INSERT INTO emp_audit SELECT 'I', now(), user, NEW.*;
3687 RETURN NULL; -- result is ignored since this is an AFTER trigger
3689 $emp_audit$ LANGUAGE plpgsql;
3691 CREATE TRIGGER emp_audit
3692 AFTER INSERT OR UPDATE OR DELETE ON emp
3693 FOR EACH ROW EXECUTE PROCEDURE process_emp_audit();
3698 A variation of the previous example uses a view joining the main table
3699 to the audit table, to show when each entry was last modified. This
3700 approach still records the full audit trail of changes to the table,
3701 but also presents a simplified view of the audit trail, showing just
3702 the last modified timestamp derived from the audit trail for each entry.
3703 <xref linkend="plpgsql-view-trigger-audit-example"> shows an example
3704 of an audit trigger on a view in <application>PL/pgSQL</application>.
3707 <example id="plpgsql-view-trigger-audit-example">
3708 <title>A <application>PL/pgSQL</application> View Trigger Procedure For Auditing</title>
3711 This example uses a trigger on the view to make it updatable, and
3712 ensure that any insert, update or delete of a row in the view is
3713 recorded (i.e., audited) in the <literal>emp_audit</literal> table. The current time
3714 and user name are recorded, together with the type of operation
3715 performed, and the view displays the last modified time of each row.
3720 empname text PRIMARY KEY,
3724 CREATE TABLE emp_audit(
3725 operation char(1) NOT NULL,
3726 userid text NOT NULL,
3727 empname text NOT NULL,
3729 stamp timestamp NOT NULL
3732 CREATE VIEW emp_view AS
3735 max(ea.stamp) AS last_updated
3737 LEFT JOIN emp_audit ea ON ea.empname = e.empname
3740 CREATE OR REPLACE FUNCTION update_emp_view() RETURNS TRIGGER AS $$
3743 -- Perform the required operation on emp, and create a row in emp_audit
3744 -- to reflect the change made to emp.
3746 IF (TG_OP = 'DELETE') THEN
3747 DELETE FROM emp WHERE empname = OLD.empname;
3748 IF NOT FOUND THEN RETURN NULL; END IF;
3750 OLD.last_updated = now();
3751 INSERT INTO emp_audit VALUES('D', user, OLD.*);
3753 ELSIF (TG_OP = 'UPDATE') THEN
3754 UPDATE emp SET salary = NEW.salary WHERE empname = OLD.empname;
3755 IF NOT FOUND THEN RETURN NULL; END IF;
3757 NEW.last_updated = now();
3758 INSERT INTO emp_audit VALUES('U', user, NEW.*);
3760 ELSIF (TG_OP = 'INSERT') THEN
3761 INSERT INTO emp VALUES(NEW.empname, NEW.salary);
3763 NEW.last_updated = now();
3764 INSERT INTO emp_audit VALUES('I', user, NEW.*);
3768 $$ LANGUAGE plpgsql;
3770 CREATE TRIGGER emp_audit
3771 INSTEAD OF INSERT OR UPDATE OR DELETE ON emp_view
3772 FOR EACH ROW EXECUTE PROCEDURE update_emp_view();
3777 One use of triggers is to maintain a summary table
3778 of another table. The resulting summary can be used in place of the
3779 original table for certain queries — often with vastly reduced run
3781 This technique is commonly used in Data Warehousing, where the tables
3782 of measured or observed data (called fact tables) might be extremely large.
3783 <xref linkend="plpgsql-trigger-summary-example"> shows an example of a
3784 trigger procedure in <application>PL/pgSQL</application> that maintains
3785 a summary table for a fact table in a data warehouse.
3789 <example id="plpgsql-trigger-summary-example">
3790 <title>A <application>PL/pgSQL</application> Trigger Procedure For Maintaining A Summary Table</title>
3793 The schema detailed here is partly based on the <emphasis>Grocery Store
3794 </emphasis> example from <emphasis>The Data Warehouse Toolkit</emphasis>
3800 -- Main tables - time dimension and sales fact.
3802 CREATE TABLE time_dimension (
3803 time_key integer NOT NULL,
3804 day_of_week integer NOT NULL,
3805 day_of_month integer NOT NULL,
3806 month integer NOT NULL,
3807 quarter integer NOT NULL,
3808 year integer NOT NULL
3810 CREATE UNIQUE INDEX time_dimension_key ON time_dimension(time_key);
3812 CREATE TABLE sales_fact (
3813 time_key integer NOT NULL,
3814 product_key integer NOT NULL,
3815 store_key integer NOT NULL,
3816 amount_sold numeric(12,2) NOT NULL,
3817 units_sold integer NOT NULL,
3818 amount_cost numeric(12,2) NOT NULL
3820 CREATE INDEX sales_fact_time ON sales_fact(time_key);
3823 -- Summary table - sales by time.
3825 CREATE TABLE sales_summary_bytime (
3826 time_key integer NOT NULL,
3827 amount_sold numeric(15,2) NOT NULL,
3828 units_sold numeric(12) NOT NULL,
3829 amount_cost numeric(15,2) NOT NULL
3831 CREATE UNIQUE INDEX sales_summary_bytime_key ON sales_summary_bytime(time_key);
3834 -- Function and trigger to amend summarized column(s) on UPDATE, INSERT, DELETE.
3836 CREATE OR REPLACE FUNCTION maint_sales_summary_bytime() RETURNS TRIGGER
3837 AS $maint_sales_summary_bytime$
3839 delta_time_key integer;
3840 delta_amount_sold numeric(15,2);
3841 delta_units_sold numeric(12);
3842 delta_amount_cost numeric(15,2);
3845 -- Work out the increment/decrement amount(s).
3846 IF (TG_OP = 'DELETE') THEN
3848 delta_time_key = OLD.time_key;
3849 delta_amount_sold = -1 * OLD.amount_sold;
3850 delta_units_sold = -1 * OLD.units_sold;
3851 delta_amount_cost = -1 * OLD.amount_cost;
3853 ELSIF (TG_OP = 'UPDATE') THEN
3855 -- forbid updates that change the time_key -
3856 -- (probably not too onerous, as DELETE + INSERT is how most
3857 -- changes will be made).
3858 IF ( OLD.time_key != NEW.time_key) THEN
3859 RAISE EXCEPTION 'Update of time_key : % -> % not allowed',
3860 OLD.time_key, NEW.time_key;
3863 delta_time_key = OLD.time_key;
3864 delta_amount_sold = NEW.amount_sold - OLD.amount_sold;
3865 delta_units_sold = NEW.units_sold - OLD.units_sold;
3866 delta_amount_cost = NEW.amount_cost - OLD.amount_cost;
3868 ELSIF (TG_OP = 'INSERT') THEN
3870 delta_time_key = NEW.time_key;
3871 delta_amount_sold = NEW.amount_sold;
3872 delta_units_sold = NEW.units_sold;
3873 delta_amount_cost = NEW.amount_cost;
3878 -- Insert or update the summary row with the new values.
3879 <<insert_update>>
3881 UPDATE sales_summary_bytime
3882 SET amount_sold = amount_sold + delta_amount_sold,
3883 units_sold = units_sold + delta_units_sold,
3884 amount_cost = amount_cost + delta_amount_cost
3885 WHERE time_key = delta_time_key;
3887 EXIT insert_update WHEN found;
3890 INSERT INTO sales_summary_bytime (
3905 WHEN UNIQUE_VIOLATION THEN
3908 END LOOP insert_update;
3913 $maint_sales_summary_bytime$ LANGUAGE plpgsql;
3915 CREATE TRIGGER maint_sales_summary_bytime
3916 AFTER INSERT OR UPDATE OR DELETE ON sales_fact
3917 FOR EACH ROW EXECUTE PROCEDURE maint_sales_summary_bytime();
3919 INSERT INTO sales_fact VALUES(1,1,1,10,3,15);
3920 INSERT INTO sales_fact VALUES(1,2,1,20,5,35);
3921 INSERT INTO sales_fact VALUES(2,2,1,40,15,135);
3922 INSERT INTO sales_fact VALUES(2,3,1,10,1,13);
3923 SELECT * FROM sales_summary_bytime;
3924 DELETE FROM sales_fact WHERE product_key = 1;
3925 SELECT * FROM sales_summary_bytime;
3926 UPDATE sales_fact SET units_sold = units_sold * 2;
3927 SELECT * FROM sales_summary_bytime;
3932 <sect2 id="plpgsql-event-trigger">
3933 <title>Triggers on events</title>
3936 <application>PL/pgSQL</application> can be used to define event
3937 triggers. <productname>PostgreSQL</> requires that a procedure that
3938 is to be called as an event trigger must be declared as a function with
3939 no arguments and a return type of <literal>event_trigger</>.
3943 When a <application>PL/pgSQL</application> function is called as a
3944 event trigger, several special variables are created automatically
3945 in the top-level block. They are:
3949 <term><varname>TG_EVENT</varname></term>
3952 Data type <type>text</type>; a string representing the event the
3953 trigger is fired for.
3959 <term><varname>TG_TAG</varname></term>
3962 Data type <type>text</type>; variable that contains the command tag
3963 for which the trigger is fired.
3971 <xref linkend="plpgsql-event-trigger-example"> shows an example of a
3972 event trigger procedure in <application>PL/pgSQL</application>.
3975 <example id="plpgsql-event-trigger-example">
3976 <title>A <application>PL/pgSQL</application> Event Trigger Procedure</title>
3979 This example trigger simply raises a <literal>NOTICE</literal> message
3980 each time a supported command is executed.
3984 CREATE OR REPLACE FUNCTION snitch() RETURNS event_trigger AS $$
3986 RAISE NOTICE 'snitch: % %', tg_event, tg_tag;
3988 $$ LANGUAGE plpgsql;
3990 CREATE EVENT TRIGGER snitch ON ddl_command_start EXECUTE PROCEDURE snitch();
3997 <sect1 id="plpgsql-implementation">
3998 <title><application>PL/pgSQL</> Under the Hood</title>
4001 This section discusses some implementation details that are
4002 frequently important for <application>PL/pgSQL</> users to know.
4005 <sect2 id="plpgsql-var-subst">
4006 <title>Variable Substitution</title>
4009 SQL statements and expressions within a <application>PL/pgSQL</> function
4010 can refer to variables and parameters of the function. Behind the scenes,
4011 <application>PL/pgSQL</> substitutes query parameters for such references.
4012 Parameters will only be substituted in places where a parameter or
4013 column reference is syntactically allowed. As an extreme case, consider
4014 this example of poor programming style:
4016 INSERT INTO foo (foo) VALUES (foo);
4018 The first occurrence of <literal>foo</> must syntactically be a table
4019 name, so it will not be substituted, even if the function has a variable
4020 named <literal>foo</>. The second occurrence must be the name of a
4021 column of the table, so it will not be substituted either. Only the
4022 third occurrence is a candidate to be a reference to the function's
4028 <productname>PostgreSQL</productname> versions before 9.0 would try
4029 to substitute the variable in all three cases, leading to syntax errors.
4034 Since the names of variables are syntactically no different from the names
4035 of table columns, there can be ambiguity in statements that also refer to
4036 tables: is a given name meant to refer to a table column, or a variable?
4037 Let's change the previous example to
4039 INSERT INTO dest (col) SELECT foo + bar FROM src;
4041 Here, <literal>dest</> and <literal>src</> must be table names, and
4042 <literal>col</> must be a column of <literal>dest</>, but <literal>foo</>
4043 and <literal>bar</> might reasonably be either variables of the function
4044 or columns of <literal>src</>.
4048 By default, <application>PL/pgSQL</> will report an error if a name
4049 in a SQL statement could refer to either a variable or a table column.
4050 You can fix such a problem by renaming the variable or column,
4051 or by qualifying the ambiguous reference, or by telling
4052 <application>PL/pgSQL</> which interpretation to prefer.
4056 The simplest solution is to rename the variable or column.
4057 A common coding rule is to use a
4058 different naming convention for <application>PL/pgSQL</application>
4059 variables than you use for column names. For example,
4060 if you consistently name function variables
4061 <literal>v_<replaceable>something</></literal> while none of your
4062 column names start with <literal>v_</>, no conflicts will occur.
4066 Alternatively you can qualify ambiguous references to make them clear.
4067 In the above example, <literal>src.foo</> would be an unambiguous reference
4068 to the table column. To create an unambiguous reference to a variable,
4069 declare it in a labeled block and use the block's label
4070 (see <xref linkend="plpgsql-structure">). For example,
4072 <<block>>
4077 INSERT INTO dest (col) SELECT block.foo + bar FROM src;
4079 Here <literal>block.foo</> means the variable even if there is a column
4080 <literal>foo</> in <literal>src</>. Function parameters, as well as
4081 special variables such as <literal>FOUND</>, can be qualified by the
4082 function's name, because they are implicitly declared in an outer block
4083 labeled with the function's name.
4087 Sometimes it is impractical to fix all the ambiguous references in a
4088 large body of <application>PL/pgSQL</> code. In such cases you can
4089 specify that <application>PL/pgSQL</> should resolve ambiguous references
4090 as the variable (which is compatible with <application>PL/pgSQL</>'s
4091 behavior before <productname>PostgreSQL</productname> 9.0), or as the
4092 table column (which is compatible with some other systems such as
4093 <productname>Oracle</productname>).
4097 <primary><varname>plpgsql.variable_conflict</> configuration parameter</primary>
4101 To change this behavior on a system-wide basis, set the configuration
4102 parameter <literal>plpgsql.variable_conflict</> to one of
4103 <literal>error</>, <literal>use_variable</>, or
4104 <literal>use_column</> (where <literal>error</> is the factory default).
4105 This parameter affects subsequent compilations
4106 of statements in <application>PL/pgSQL</> functions, but not statements
4107 already compiled in the current session.
4108 Because changing this setting
4109 can cause unexpected changes in the behavior of <application>PL/pgSQL</>
4110 functions, it can only be changed by a superuser.
4114 You can also set the behavior on a function-by-function basis, by
4115 inserting one of these special commands at the start of the function
4118 #variable_conflict error
4119 #variable_conflict use_variable
4120 #variable_conflict use_column
4122 These commands affect only the function they are written in, and override
4123 the setting of <literal>plpgsql.variable_conflict</>. An example is
4125 CREATE FUNCTION stamp_user(id int, comment text) RETURNS void AS $$
4126 #variable_conflict use_variable
4128 curtime timestamp := now();
4130 UPDATE users SET last_modified = curtime, comment = comment
4131 WHERE users.id = id;
4133 $$ LANGUAGE plpgsql;
4135 In the <literal>UPDATE</> command, <literal>curtime</>, <literal>comment</>,
4136 and <literal>id</> will refer to the function's variable and parameters
4137 whether or not <literal>users</> has columns of those names. Notice
4138 that we had to qualify the reference to <literal>users.id</> in the
4139 <literal>WHERE</> clause to make it refer to the table column.
4140 But we did not have to qualify the reference to <literal>comment</>
4141 as a target in the <literal>UPDATE</> list, because syntactically
4142 that must be a column of <literal>users</>. We could write the same
4143 function without depending on the <literal>variable_conflict</> setting
4146 CREATE FUNCTION stamp_user(id int, comment text) RETURNS void AS $$
4149 curtime timestamp := now();
4151 UPDATE users SET last_modified = fn.curtime, comment = stamp_user.comment
4152 WHERE users.id = stamp_user.id;
4154 $$ LANGUAGE plpgsql;
4159 Variable substitution does not happen in the command string given
4160 to <command>EXECUTE</> or one of its variants. If you need to
4161 insert a varying value into such a command, do so as part of
4162 constructing the string value, or use <literal>USING</>, as illustrated in
4163 <xref linkend="plpgsql-statements-executing-dyn">.
4167 Variable substitution currently works only in <command>SELECT</>,
4168 <command>INSERT</>, <command>UPDATE</>, and <command>DELETE</> commands,
4169 because the main SQL engine allows query parameters only in these
4170 commands. To use a non-constant name or value in other statement
4171 types (generically called utility statements), you must construct
4172 the utility statement as a string and <command>EXECUTE</> it.
4177 <sect2 id="plpgsql-plan-caching">
4178 <title>Plan Caching</title>
4181 The <application>PL/pgSQL</> interpreter parses the function's source
4182 text and produces an internal binary instruction tree the first time the
4183 function is called (within each session). The instruction tree
4184 fully translates the
4185 <application>PL/pgSQL</> statement structure, but individual
4186 <acronym>SQL</acronym> expressions and <acronym>SQL</acronym> commands
4187 used in the function are not translated immediately.
4192 <primary>preparing a query</>
4193 <secondary>in PL/pgSQL</>
4195 As each expression and <acronym>SQL</acronym> command is first
4196 executed in the function, the <application>PL/pgSQL</> interpreter
4197 parses and analyzes the command to create a prepared statement,
4198 using the <acronym>SPI</acronym> manager's
4199 <function>SPI_prepare</function> function.
4200 Subsequent visits to that expression or command
4201 reuse the prepared statement. Thus, a function with conditional code
4202 paths that are seldom visited will never incur the overhead of
4203 analyzing those commands that are never executed within the current
4204 session. A disadvantage is that errors
4205 in a specific expression or command cannot be detected until that
4206 part of the function is reached in execution. (Trivial syntax
4207 errors will be detected during the initial parsing pass, but
4208 anything deeper will not be detected until execution.)
4212 <application>PL/pgSQL</> (or more precisely, the SPI manager) can
4213 furthermore attempt to cache the execution plan associated with any
4214 particular prepared statement. If a cached plan is not used, then
4215 a fresh execution plan is generated on each visit to the statement,
4216 and the current parameter values (that is, <application>PL/pgSQL</>
4217 variable values) can be used to optimize the selected plan. If the
4218 statement has no parameters, or is executed many times, the SPI manager
4219 will consider creating a <firstterm>generic</> plan that is not dependent
4220 on specific parameter values, and caching that for re-use. Typically
4221 this will happen only if the execution plan is not very sensitive to
4222 the values of the <application>PL/pgSQL</> variables referenced in it.
4223 If it is, generating a plan each time is a net win.
4227 Because <application>PL/pgSQL</application> saves prepared statements
4228 and sometimes execution plans in this way,
4229 SQL commands that appear directly in a
4230 <application>PL/pgSQL</application> function must refer to the
4231 same tables and columns on every execution; that is, you cannot use
4232 a parameter as the name of a table or column in an SQL command. To get
4233 around this restriction, you can construct dynamic commands using
4234 the <application>PL/pgSQL</application> <command>EXECUTE</command>
4235 statement — at the price of performing new parse analysis and
4236 constructing a new execution plan on every execution.
4240 The mutable nature of record variables presents another problem in this
4241 connection. When fields of a record variable are used in
4242 expressions or statements, the data types of the fields must not
4243 change from one call of the function to the next, since each
4244 expression will be analyzed using the data type that is present
4245 when the expression is first reached. <command>EXECUTE</command> can be
4246 used to get around this problem when necessary.
4250 If the same function is used as a trigger for more than one table,
4251 <application>PL/pgSQL</application> prepares and caches statements
4252 independently for each such table — that is, there is a cache
4253 for each trigger function and table combination, not just for each
4254 function. This alleviates some of the problems with varying
4255 data types; for instance, a trigger function will be able to work
4256 successfully with a column named <literal>key</> even if it happens
4257 to have different types in different tables.
4261 Likewise, functions having polymorphic argument types have a separate
4262 statement cache for each combination of actual argument types they have
4263 been invoked for, so that data type differences do not cause unexpected
4268 Statement caching can sometimes have surprising effects on the
4269 interpretation of time-sensitive values. For example there
4270 is a difference between what these two functions do:
4273 CREATE FUNCTION logfunc1(logtxt text) RETURNS void AS $$
4275 INSERT INTO logtable VALUES (logtxt, 'now');
4277 $$ LANGUAGE plpgsql;
4283 CREATE FUNCTION logfunc2(logtxt text) RETURNS void AS $$
4288 INSERT INTO logtable VALUES (logtxt, curtime);
4290 $$ LANGUAGE plpgsql;
4295 In the case of <function>logfunc1</function>, the
4296 <productname>PostgreSQL</productname> main parser knows when
4297 analyzing the <command>INSERT</command> that the
4298 string <literal>'now'</literal> should be interpreted as
4299 <type>timestamp</type>, because the target column of
4300 <classname>logtable</classname> is of that type. Thus,
4301 <literal>'now'</literal> will be converted to a <type>timestamp</type>
4303 <command>INSERT</command> is analyzed, and then used in all
4304 invocations of <function>logfunc1</function> during the lifetime
4305 of the session. Needless to say, this isn't what the programmer
4306 wanted. A better idea is to use the <literal>now()</> or
4307 <literal>current_timestamp</> function.
4311 In the case of <function>logfunc2</function>, the
4312 <productname>PostgreSQL</productname> main parser does not know
4313 what type <literal>'now'</literal> should become and therefore
4314 it returns a data value of type <type>text</type> containing the string
4315 <literal>now</literal>. During the ensuing assignment
4316 to the local variable <varname>curtime</varname>, the
4317 <application>PL/pgSQL</application> interpreter casts this
4318 string to the <type>timestamp</type> type by calling the
4319 <function>text_out</function> and <function>timestamp_in</function>
4320 functions for the conversion. So, the computed time stamp is updated
4321 on each execution as the programmer expects. Even though this
4322 happens to work as expected, it's not terribly efficient, so
4323 use of the <literal>now()</> function would still be a better idea.
4330 <sect1 id="plpgsql-development-tips">
4331 <title>Tips for Developing in <application>PL/pgSQL</application></title>
4334 One good way to develop in
4335 <application>PL/pgSQL</> is to use the text editor of your
4336 choice to create your functions, and in another window, use
4337 <application>psql</application> to load and test those functions.
4338 If you are doing it this way, it
4339 is a good idea to write the function using <command>CREATE OR
4340 REPLACE FUNCTION</>. That way you can just reload the file to update
4341 the function definition. For example:
4343 CREATE OR REPLACE FUNCTION testfunc(integer) RETURNS integer AS $$
4345 $$ LANGUAGE plpgsql;
4350 While running <application>psql</application>, you can load or reload such
4351 a function definition file with:
4355 and then immediately issue SQL commands to test the function.
4359 Another good way to develop in <application>PL/pgSQL</> is with a
4360 GUI database access tool that facilitates development in a
4361 procedural language. One example of such a tool is
4362 <application>pgAdmin</>, although others exist. These tools often
4363 provide convenient features such as escaping single quotes and
4364 making it easier to recreate and debug functions.
4367 <sect2 id="plpgsql-quote-tips">
4368 <title>Handling of Quotation Marks</title>
4371 The code of a <application>PL/pgSQL</> function is specified in
4372 <command>CREATE FUNCTION</command> as a string literal. If you
4373 write the string literal in the ordinary way with surrounding
4374 single quotes, then any single quotes inside the function body
4375 must be doubled; likewise any backslashes must be doubled (assuming
4376 escape string syntax is used).
4377 Doubling quotes is at best tedious, and in more complicated cases
4378 the code can become downright incomprehensible, because you can
4379 easily find yourself needing half a dozen or more adjacent quote marks.
4380 It's recommended that you instead write the function body as a
4381 <quote>dollar-quoted</> string literal (see <xref
4382 linkend="sql-syntax-dollar-quoting">). In the dollar-quoting
4383 approach, you never double any quote marks, but instead take care to
4384 choose a different dollar-quoting delimiter for each level of
4385 nesting you need. For example, you might write the <command>CREATE
4386 FUNCTION</command> command as:
4388 CREATE OR REPLACE FUNCTION testfunc(integer) RETURNS integer AS $PROC$
4390 $PROC$ LANGUAGE plpgsql;
4392 Within this, you might use quote marks for simple literal strings in
4393 SQL commands and <literal>$$</> to delimit fragments of SQL commands
4394 that you are assembling as strings. If you need to quote text that
4395 includes <literal>$$</>, you could use <literal>$Q$</>, and so on.
4399 The following chart shows what you have to do when writing quote
4400 marks without dollar quoting. It might be useful when translating
4401 pre-dollar quoting code into something more comprehensible.
4406 <term>1 quotation mark</term>
4409 To begin and end the function body, for example:
4411 CREATE FUNCTION foo() RETURNS integer AS '
4415 Anywhere within a single-quoted function body, quote marks
4416 <emphasis>must</> appear in pairs.
4422 <term>2 quotation marks</term>
4425 For string literals inside the function body, for example:
4427 a_output := ''Blah'';
4428 SELECT * FROM users WHERE f_name=''foobar'';
4430 In the dollar-quoting approach, you'd just write:
4433 SELECT * FROM users WHERE f_name='foobar';
4435 which is exactly what the <application>PL/pgSQL</> parser would see
4442 <term>4 quotation marks</term>
4445 When you need a single quotation mark in a string constant inside the
4446 function body, for example:
4448 a_output := a_output || '' AND name LIKE ''''foobar'''' AND xyz''
4450 The value actually appended to <literal>a_output</literal> would be:
4451 <literal> AND name LIKE 'foobar' AND xyz</literal>.
4454 In the dollar-quoting approach, you'd write:
4456 a_output := a_output || $$ AND name LIKE 'foobar' AND xyz$$
4458 being careful that any dollar-quote delimiters around this are not
4459 just <literal>$$</>.
4465 <term>6 quotation marks</term>
4468 When a single quotation mark in a string inside the function body is
4469 adjacent to the end of that string constant, for example:
4471 a_output := a_output || '' AND name LIKE ''''foobar''''''
4473 The value appended to <literal>a_output</literal> would then be:
4474 <literal> AND name LIKE 'foobar'</literal>.
4477 In the dollar-quoting approach, this becomes:
4479 a_output := a_output || $$ AND name LIKE 'foobar'$$
4486 <term>10 quotation marks</term>
4489 When you want two single quotation marks in a string constant (which
4490 accounts for 8 quotation marks) and this is adjacent to the end of that
4491 string constant (2 more). You will probably only need that if
4492 you are writing a function that generates other functions, as in
4493 <xref linkend="plpgsql-porting-ex2">.
4496 a_output := a_output || '' if v_'' ||
4497 referrer_keys.kind || '' like ''''''''''
4498 || referrer_keys.key_string || ''''''''''
4499 then return '''''' || referrer_keys.referrer_type
4500 || ''''''; end if;'';
4502 The value of <literal>a_output</literal> would then be:
4504 if v_... like ''...'' then return ''...''; end if;
4508 In the dollar-quoting approach, this becomes:
4510 a_output := a_output || $$ if v_$$ || referrer_keys.kind || $$ like '$$
4511 || referrer_keys.key_string || $$'
4512 then return '$$ || referrer_keys.referrer_type
4515 where we assume we only need to put single quote marks into
4516 <literal>a_output</literal>, because it will be re-quoted before use.
4525 <!-- **** Porting from Oracle PL/SQL **** -->
4527 <sect1 id="plpgsql-porting">
4528 <title>Porting from <productname>Oracle</productname> PL/SQL</title>
4530 <indexterm zone="plpgsql-porting">
4531 <primary>Oracle</primary>
4532 <secondary>porting from PL/SQL to PL/pgSQL</secondary>
4535 <indexterm zone="plpgsql-porting">
4536 <primary>PL/SQL (Oracle)</primary>
4537 <secondary>porting to PL/pgSQL</secondary>
4541 This section explains differences between
4542 <productname>PostgreSQL</>'s <application>PL/pgSQL</application>
4543 language and Oracle's <application>PL/SQL</application> language,
4544 to help developers who port applications from
4545 <trademark class="registered">Oracle</> to <productname>PostgreSQL</>.
4549 <application>PL/pgSQL</application> is similar to PL/SQL in many
4550 aspects. It is a block-structured, imperative language, and all
4551 variables have to be declared. Assignments, loops, conditionals
4552 are similar. The main differences you should keep in mind when
4553 porting from <application>PL/SQL</> to
4554 <application>PL/pgSQL</application> are:
4559 If a name used in a SQL command could be either a column name of a
4560 table or a reference to a variable of the function,
4561 <application>PL/SQL</> treats it as a column name. This corresponds
4562 to <application>PL/pgSQL</>'s
4563 <literal>plpgsql.variable_conflict</> = <literal>use_column</>
4564 behavior, which is not the default,
4565 as explained in <xref linkend="plpgsql-var-subst">.
4566 It's often best to avoid such ambiguities in the first place,
4567 but if you have to port a large amount of code that depends on
4568 this behavior, setting <literal>variable_conflict</> may be the
4575 In <productname>PostgreSQL</> the function body must be written as
4576 a string literal. Therefore you need to use dollar quoting or escape
4577 single quotes in the function body. (See <xref
4578 linkend="plpgsql-quote-tips">.)
4584 Instead of packages, use schemas to organize your functions
4591 Since there are no packages, there are no package-level variables
4592 either. This is somewhat annoying. You can keep per-session state
4593 in temporary tables instead.
4599 Integer <command>FOR</> loops with <literal>REVERSE</> work
4600 differently: <application>PL/SQL</> counts down from the second
4601 number to the first, while <application>PL/pgSQL</> counts down
4602 from the first number to the second, requiring the loop bounds
4603 to be swapped when porting. This incompatibility is unfortunate
4604 but is unlikely to be changed. (See <xref
4605 linkend="plpgsql-integer-for">.)
4611 <command>FOR</> loops over queries (other than cursors) also work
4612 differently: the target variable(s) must have been declared,
4613 whereas <application>PL/SQL</> always declares them implicitly.
4614 An advantage of this is that the variable values are still accessible
4615 after the loop exits.
4621 There are various notational differences for the use of cursor
4630 <title>Porting Examples</title>
4633 <xref linkend="pgsql-porting-ex1"> shows how to port a simple
4634 function from <application>PL/SQL</> to <application>PL/pgSQL</>.
4637 <example id="pgsql-porting-ex1">
4638 <title>Porting a Simple Function from <application>PL/SQL</> to <application>PL/pgSQL</></title>
4641 Here is an <productname>Oracle</productname> <application>PL/SQL</> function:
4643 CREATE OR REPLACE FUNCTION cs_fmt_browser_version(v_name varchar,
4647 IF v_version IS NULL THEN
4650 RETURN v_name || '/' || v_version;
4658 Let's go through this function and see the differences compared to
4659 <application>PL/pgSQL</>:
4664 The <literal>RETURN</literal> key word in the function
4665 prototype (not the function body) becomes
4666 <literal>RETURNS</literal> in
4667 <productname>PostgreSQL</productname>.
4668 Also, <literal>IS</> becomes <literal>AS</>, and you need to
4669 add a <literal>LANGUAGE</> clause because <application>PL/pgSQL</>
4670 is not the only possible function language.
4676 In <productname>PostgreSQL</>, the function body is considered
4677 to be a string literal, so you need to use quote marks or dollar
4678 quotes around it. This substitutes for the terminating <literal>/</>
4679 in the Oracle approach.
4685 The <literal>show errors</literal> command does not exist in
4686 <productname>PostgreSQL</>, and is not needed since errors are
4687 reported automatically.
4694 This is how this function would look when ported to
4695 <productname>PostgreSQL</>:
4698 CREATE OR REPLACE FUNCTION cs_fmt_browser_version(v_name varchar,
4700 RETURNS varchar AS $$
4702 IF v_version IS NULL THEN
4705 RETURN v_name || '/' || v_version;
4707 $$ LANGUAGE plpgsql;
4713 <xref linkend="plpgsql-porting-ex2"> shows how to port a
4714 function that creates another function and how to handle the
4715 ensuing quoting problems.
4718 <example id="plpgsql-porting-ex2">
4719 <title>Porting a Function that Creates Another Function from <application>PL/SQL</> to <application>PL/pgSQL</></title>
4722 The following procedure grabs rows from a
4723 <command>SELECT</command> statement and builds a large function
4724 with the results in <literal>IF</literal> statements, for the
4729 This is the Oracle version:
4731 CREATE OR REPLACE PROCEDURE cs_update_referrer_type_proc IS
4732 CURSOR referrer_keys IS
4733 SELECT * FROM cs_referrer_keys
4735 func_cmd VARCHAR(4000);
4737 func_cmd := 'CREATE OR REPLACE FUNCTION cs_find_referrer_type(v_host IN VARCHAR,
4738 v_domain IN VARCHAR, v_url IN VARCHAR) RETURN VARCHAR IS BEGIN';
4740 FOR referrer_key IN referrer_keys LOOP
4741 func_cmd := func_cmd ||
4742 ' IF v_' || referrer_key.kind
4743 || ' LIKE ''' || referrer_key.key_string
4744 || ''' THEN RETURN ''' || referrer_key.referrer_type
4748 func_cmd := func_cmd || ' RETURN NULL; END;';
4750 EXECUTE IMMEDIATE func_cmd;
4758 Here is how this function would end up in <productname>PostgreSQL</>:
4760 CREATE OR REPLACE FUNCTION cs_update_referrer_type_proc() RETURNS void AS $func$
4762 referrer_keys CURSOR IS
4763 SELECT * FROM cs_referrer_keys
4768 func_body := 'BEGIN';
4770 FOR referrer_key IN referrer_keys LOOP
4771 func_body := func_body ||
4772 ' IF v_' || referrer_key.kind
4773 || ' LIKE ' || quote_literal(referrer_key.key_string)
4774 || ' THEN RETURN ' || quote_literal(referrer_key.referrer_type)
4778 func_body := func_body || ' RETURN NULL; END;';
4781 'CREATE OR REPLACE FUNCTION cs_find_referrer_type(v_host varchar,
4784 RETURNS varchar AS '
4785 || quote_literal(func_body)
4786 || ' LANGUAGE plpgsql;' ;
4790 $func$ LANGUAGE plpgsql;
4792 Notice how the body of the function is built separately and passed
4793 through <literal>quote_literal</> to double any quote marks in it. This
4794 technique is needed because we cannot safely use dollar quoting for
4795 defining the new function: we do not know for sure what strings will
4796 be interpolated from the <structfield>referrer_key.key_string</> field.
4797 (We are assuming here that <structfield>referrer_key.kind</> can be
4798 trusted to always be <literal>host</>, <literal>domain</>, or
4799 <literal>url</>, but <structfield>referrer_key.key_string</> might be
4800 anything, in particular it might contain dollar signs.) This function
4801 is actually an improvement on the Oracle original, because it will
4802 not generate broken code when <structfield>referrer_key.key_string</> or
4803 <structfield>referrer_key.referrer_type</> contain quote marks.
4808 <xref linkend="plpgsql-porting-ex3"> shows how to port a function
4809 with <literal>OUT</> parameters and string manipulation.
4810 <productname>PostgreSQL</> does not have a built-in
4811 <function>instr</function> function, but you can create one
4812 using a combination of other
4813 functions.<indexterm><primary>instr</></indexterm> In <xref
4814 linkend="plpgsql-porting-appendix"> there is a
4815 <application>PL/pgSQL</application> implementation of
4816 <function>instr</function> that you can use to make your porting
4820 <example id="plpgsql-porting-ex3">
4821 <title>Porting a Procedure With String Manipulation and
4822 <literal>OUT</> Parameters from <application>PL/SQL</> to
4823 <application>PL/pgSQL</></title>
4826 The following <productname>Oracle</productname> PL/SQL procedure is used
4827 to parse a URL and return several elements (host, path, and query).
4831 This is the Oracle version:
4833 CREATE OR REPLACE PROCEDURE cs_parse_url(
4835 v_host OUT VARCHAR, -- This will be passed back
4836 v_path OUT VARCHAR, -- This one too
4837 v_query OUT VARCHAR) -- And this one
4845 a_pos1 := instr(v_url, '//');
4850 a_pos2 := instr(v_url, '/', a_pos1 + 2);
4852 v_host := substr(v_url, a_pos1 + 2);
4857 v_host := substr(v_url, a_pos1 + 2, a_pos2 - a_pos1 - 2);
4858 a_pos1 := instr(v_url, '?', a_pos2 + 1);
4861 v_path := substr(v_url, a_pos2);
4865 v_path := substr(v_url, a_pos2, a_pos1 - a_pos2);
4866 v_query := substr(v_url, a_pos1 + 1);
4874 Here is a possible translation into <application>PL/pgSQL</>:
4876 CREATE OR REPLACE FUNCTION cs_parse_url(
4878 v_host OUT VARCHAR, -- This will be passed back
4879 v_path OUT VARCHAR, -- This one too
4880 v_query OUT VARCHAR) -- And this one
4889 a_pos1 := instr(v_url, '//');
4894 a_pos2 := instr(v_url, '/', a_pos1 + 2);
4896 v_host := substr(v_url, a_pos1 + 2);
4901 v_host := substr(v_url, a_pos1 + 2, a_pos2 - a_pos1 - 2);
4902 a_pos1 := instr(v_url, '?', a_pos2 + 1);
4905 v_path := substr(v_url, a_pos2);
4909 v_path := substr(v_url, a_pos2, a_pos1 - a_pos2);
4910 v_query := substr(v_url, a_pos1 + 1);
4912 $$ LANGUAGE plpgsql;
4915 This function could be used like this:
4917 SELECT * FROM cs_parse_url('http://foobar.com/query.cgi?baz');
4923 <xref linkend="plpgsql-porting-ex4"> shows how to port a procedure
4924 that uses numerous features that are specific to Oracle.
4927 <example id="plpgsql-porting-ex4">
4928 <title>Porting a Procedure from <application>PL/SQL</> to <application>PL/pgSQL</></title>
4934 CREATE OR REPLACE PROCEDURE cs_create_job(v_job_id IN INTEGER) IS
4935 a_running_job_count INTEGER;
4936 PRAGMA AUTONOMOUS_TRANSACTION;<co id="co.plpgsql-porting-pragma">
4938 LOCK TABLE cs_jobs IN EXCLUSIVE MODE;<co id="co.plpgsql-porting-locktable">
4940 SELECT count(*) INTO a_running_job_count FROM cs_jobs WHERE end_stamp IS NULL;
4942 IF a_running_job_count > 0 THEN
4943 COMMIT; -- free lock<co id="co.plpgsql-porting-commit">
4944 raise_application_error(-20000,
4945 'Unable to create a new job: a job is currently running.');
4948 DELETE FROM cs_active_job;
4949 INSERT INTO cs_active_job(job_id) VALUES (v_job_id);
4952 INSERT INTO cs_jobs (job_id, start_stamp) VALUES (v_job_id, sysdate);
4954 WHEN dup_val_on_index THEN NULL; -- don't worry if it already exists
4964 Procedures like this can easily be converted into <productname>PostgreSQL</>
4965 functions returning <type>void</type>. This procedure in
4966 particular is interesting because it can teach us some things:
4969 <callout arearefs="co.plpgsql-porting-pragma">
4971 There is no <literal>PRAGMA</literal> statement in <productname>PostgreSQL</>.
4975 <callout arearefs="co.plpgsql-porting-locktable">
4977 If you do a <command>LOCK TABLE</command> in <application>PL/pgSQL</>,
4978 the lock will not be released until the calling transaction is
4983 <callout arearefs="co.plpgsql-porting-commit">
4985 You cannot issue <command>COMMIT</> in a
4986 <application>PL/pgSQL</application> function. The function is
4987 running within some outer transaction and so <command>COMMIT</>
4988 would imply terminating the function's execution. However, in
4989 this particular case it is not necessary anyway, because the lock
4990 obtained by the <command>LOCK TABLE</command> will be released when
4998 This is how we could port this procedure to <application>PL/pgSQL</>:
5001 CREATE OR REPLACE FUNCTION cs_create_job(v_job_id integer) RETURNS void AS $$
5003 a_running_job_count integer;
5005 LOCK TABLE cs_jobs IN EXCLUSIVE MODE;
5007 SELECT count(*) INTO a_running_job_count FROM cs_jobs WHERE end_stamp IS NULL;
5009 IF a_running_job_count > 0 THEN
5010 RAISE EXCEPTION 'Unable to create a new job: a job is currently running';<co id="co.plpgsql-porting-raise">
5013 DELETE FROM cs_active_job;
5014 INSERT INTO cs_active_job(job_id) VALUES (v_job_id);
5017 INSERT INTO cs_jobs (job_id, start_stamp) VALUES (v_job_id, now());
5019 WHEN unique_violation THEN <co id="co.plpgsql-porting-exception">
5020 -- don't worry if it already exists
5023 $$ LANGUAGE plpgsql;
5027 <callout arearefs="co.plpgsql-porting-raise">
5029 The syntax of <literal>RAISE</> is considerably different from
5030 Oracle's statement, although the basic case <literal>RAISE</>
5031 <replaceable class="parameter">exception_name</replaceable> works
5035 <callout arearefs="co.plpgsql-porting-exception">
5037 The exception names supported by <application>PL/pgSQL</> are
5038 different from Oracle's. The set of built-in exception names
5039 is much larger (see <xref linkend="errcodes-appendix">). There
5040 is not currently a way to declare user-defined exception names,
5041 although you can throw user-chosen SQLSTATE values instead.
5046 The main functional difference between this procedure and the
5047 Oracle equivalent is that the exclusive lock on the <literal>cs_jobs</>
5048 table will be held until the calling transaction completes. Also, if
5049 the caller later aborts (for example due to an error), the effects of
5050 this procedure will be rolled back.
5055 <sect2 id="plpgsql-porting-other">
5056 <title>Other Things to Watch For</title>
5059 This section explains a few other things to watch for when porting
5060 Oracle <application>PL/SQL</> functions to
5061 <productname>PostgreSQL</productname>.
5064 <sect3 id="plpgsql-porting-exceptions">
5065 <title>Implicit Rollback after Exceptions</title>
5068 In <application>PL/pgSQL</>, when an exception is caught by an
5069 <literal>EXCEPTION</> clause, all database changes since the block's
5070 <literal>BEGIN</> are automatically rolled back. That is, the behavior
5071 is equivalent to what you'd get in Oracle with:
5087 If you are translating an Oracle procedure that uses
5088 <command>SAVEPOINT</> and <command>ROLLBACK TO</> in this style,
5089 your task is easy: just omit the <command>SAVEPOINT</> and
5090 <command>ROLLBACK TO</>. If you have a procedure that uses
5091 <command>SAVEPOINT</> and <command>ROLLBACK TO</> in a different way
5092 then some actual thought will be required.
5097 <title><command>EXECUTE</command></title>
5100 The <application>PL/pgSQL</> version of
5101 <command>EXECUTE</command> works similarly to the
5102 <application>PL/SQL</> version, but you have to remember to use
5103 <function>quote_literal</function> and
5104 <function>quote_ident</function> as described in <xref
5105 linkend="plpgsql-statements-executing-dyn">. Constructs of the
5106 type <literal>EXECUTE 'SELECT * FROM $1';</literal> will not work
5107 reliably unless you use these functions.
5111 <sect3 id="plpgsql-porting-optimization">
5112 <title>Optimizing <application>PL/pgSQL</application> Functions</title>
5115 <productname>PostgreSQL</> gives you two function creation
5116 modifiers to optimize execution: <quote>volatility</> (whether
5117 the function always returns the same result when given the same
5118 arguments) and <quote>strictness</quote> (whether the function
5119 returns null if any argument is null). Consult the <xref
5120 linkend="sql-createfunction">
5121 reference page for details.
5125 When making use of these optimization attributes, your
5126 <command>CREATE FUNCTION</command> statement might look something
5130 CREATE FUNCTION foo(...) RETURNS integer AS $$
5132 $$ LANGUAGE plpgsql STRICT IMMUTABLE;
5138 <sect2 id="plpgsql-porting-appendix">
5139 <title>Appendix</title>
5142 This section contains the code for a set of Oracle-compatible
5143 <function>instr</function> functions that you can use to simplify
5144 your porting efforts.
5149 -- instr functions that mimic Oracle's counterpart
5150 -- Syntax: instr(string1, string2, [n], [m]) where [] denotes optional parameters.
5152 -- Searches string1 beginning at the nth character for the mth occurrence
5153 -- of string2. If n is negative, search backwards. If m is not passed,
5154 -- assume 1 (search starts at first character).
5157 CREATE FUNCTION instr(varchar, varchar) RETURNS integer AS $$
5161 pos:= instr($1, $2, 1);
5164 $$ LANGUAGE plpgsql STRICT IMMUTABLE;
5167 CREATE FUNCTION instr(string varchar, string_to_search varchar, beg_index integer)
5168 RETURNS integer AS $$
5170 pos integer NOT NULL DEFAULT 0;
5176 IF beg_index > 0 THEN
5177 temp_str := substring(string FROM beg_index);
5178 pos := position(string_to_search IN temp_str);
5183 RETURN pos + beg_index - 1;
5185 ELSIF beg_index < 0 THEN
5186 ss_length := char_length(string_to_search);
5187 length := char_length(string);
5188 beg := length + beg_index - ss_length + 2;
5190 WHILE beg > 0 LOOP
5191 temp_str := substring(string FROM beg FOR ss_length);
5192 pos := position(string_to_search IN temp_str);
5206 $$ LANGUAGE plpgsql STRICT IMMUTABLE;
5209 CREATE FUNCTION instr(string varchar, string_to_search varchar,
5210 beg_index integer, occur_index integer)
5211 RETURNS integer AS $$
5213 pos integer NOT NULL DEFAULT 0;
5214 occur_number integer NOT NULL DEFAULT 0;
5221 IF beg_index > 0 THEN
5223 temp_str := substring(string FROM beg_index);
5225 FOR i IN 1..occur_index LOOP
5226 pos := position(string_to_search IN temp_str);
5229 beg := beg + pos - 1;
5234 temp_str := substring(string FROM beg + 1);
5242 ELSIF beg_index < 0 THEN
5243 ss_length := char_length(string_to_search);
5244 length := char_length(string);
5245 beg := length + beg_index - ss_length + 2;
5247 WHILE beg > 0 LOOP
5248 temp_str := substring(string FROM beg FOR ss_length);
5249 pos := position(string_to_search IN temp_str);
5252 occur_number := occur_number + 1;
5254 IF occur_number = occur_index THEN
5267 $$ LANGUAGE plpgsql STRICT IMMUTABLE;