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.
346 Equal (<literal>=</>) can be used instead of PL/SQL-compliant
351 A variable's default value is evaluated and assigned to the variable
352 each time the block is entered (not just once per function call).
353 So, for example, assigning <literal>now()</literal> to a variable of type
354 <type>timestamp</type> causes the variable to have the
355 time of the current function call, not the time when the function was
362 quantity integer DEFAULT 32;
363 url varchar := 'http://mysite.com';
364 user_id CONSTANT integer := 10;
368 <sect2 id="plpgsql-declaration-parameters">
369 <title>Declaring Function Parameters</title>
372 Parameters passed to functions are named with the identifiers
373 <literal>$1</literal>, <literal>$2</literal>,
374 etc. Optionally, aliases can be declared for
375 <literal>$<replaceable>n</replaceable></literal>
376 parameter names for increased readability. Either the alias or the
377 numeric identifier can then be used to refer to the parameter value.
381 There are two ways to create an alias. The preferred way is to give a
382 name to the parameter in the <command>CREATE FUNCTION</command> command,
385 CREATE FUNCTION sales_tax(subtotal real) RETURNS real AS $$
387 RETURN subtotal * 0.06;
391 The other way is to explicitly declare an alias, using the
395 <replaceable>name</replaceable> ALIAS FOR $<replaceable>n</replaceable>;
398 The same example in this style looks like:
400 CREATE FUNCTION sales_tax(real) RETURNS real AS $$
402 subtotal ALIAS FOR $1;
404 RETURN subtotal * 0.06;
412 These two examples are not perfectly equivalent. In the first case,
413 <literal>subtotal</> could be referenced as
414 <literal>sales_tax.subtotal</>, but in the second case it could not.
415 (Had we attached a label to the inner block, <literal>subtotal</> could
416 be qualified with that label, instead.)
423 CREATE FUNCTION instr(varchar, integer) RETURNS integer AS $$
425 v_string ALIAS FOR $1;
428 -- some computations using v_string and index here
433 CREATE FUNCTION concat_selected_fields(in_t sometablename) RETURNS text AS $$
435 RETURN in_t.f1 || in_t.f3 || in_t.f5 || in_t.f7;
442 When a <application>PL/pgSQL</application> function is declared
443 with output parameters, the output parameters are given
444 <literal>$<replaceable>n</replaceable></literal> names and optional
445 aliases in just the same way as the normal input parameters. An
446 output parameter is effectively a variable that starts out NULL;
447 it should be assigned to during the execution of the function.
448 The final value of the parameter is what is returned. For instance,
449 the sales-tax example could also be done this way:
452 CREATE FUNCTION sales_tax(subtotal real, OUT tax real) AS $$
454 tax := subtotal * 0.06;
459 Notice that we omitted <literal>RETURNS real</> — we could have
460 included it, but it would be redundant.
464 Output parameters are most useful when returning multiple values.
465 A trivial example is:
468 CREATE FUNCTION sum_n_product(x int, y int, OUT sum int, OUT prod int) AS $$
476 As discussed in <xref linkend="xfunc-output-parameters">, this
477 effectively creates an anonymous record type for the function's
478 results. If a <literal>RETURNS</> clause is given, it must say
479 <literal>RETURNS record</>.
483 Another way to declare a <application>PL/pgSQL</application> function
484 is with <literal>RETURNS TABLE</>, for example:
487 CREATE FUNCTION extended_sales(p_itemno int)
488 RETURNS TABLE(quantity int, total numeric) AS $$
490 RETURN QUERY SELECT s.quantity, s.quantity * s.price FROM sales AS s
491 WHERE s.itemno = p_itemno;
496 This is exactly equivalent to declaring one or more <literal>OUT</>
497 parameters and specifying <literal>RETURNS SETOF
498 <replaceable>sometype</></literal>.
502 When the return type of a <application>PL/pgSQL</application>
503 function is declared as a polymorphic type (<type>anyelement</type>,
504 <type>anyarray</type>, <type>anynonarray</type>, <type>anyenum</type>,
505 or <type>anyrange</type>), a special parameter <literal>$0</literal>
506 is created. Its data type is the actual return type of the function,
507 as deduced from the actual input types (see <xref
508 linkend="extend-types-polymorphic">).
509 This allows the function to access its actual return type
510 as shown in <xref linkend="plpgsql-declaration-type">.
511 <literal>$0</literal> is initialized to null and can be modified by
512 the function, so it can be used to hold the return value if desired,
513 though that is not required. <literal>$0</literal> can also be
514 given an alias. For example, this function works on any data type
515 that has a <literal>+</> operator:
518 CREATE FUNCTION add_three_values(v1 anyelement, v2 anyelement, v3 anyelement)
519 RETURNS anyelement AS $$
523 result := v1 + v2 + v3;
531 The same effect can be obtained by declaring one or more output parameters as
532 polymorphic types. In this case the
533 special <literal>$0</literal> parameter is not used; the output
534 parameters themselves serve the same purpose. For example:
537 CREATE FUNCTION add_three_values(v1 anyelement, v2 anyelement, v3 anyelement,
548 <sect2 id="plpgsql-declaration-alias">
549 <title><literal>ALIAS</></title>
552 <replaceable>newname</> ALIAS FOR <replaceable>oldname</>;
556 The <literal>ALIAS</> syntax is more general than is suggested in the
557 previous section: you can declare an alias for any variable, not just
558 function parameters. The main practical use for this is to assign
559 a different name for variables with predetermined names, such as
560 <varname>NEW</varname> or <varname>OLD</varname> within
569 updated ALIAS FOR new;
574 Since <literal>ALIAS</> creates two different ways to name the same
575 object, unrestricted use can be confusing. It's best to use it only
576 for the purpose of overriding predetermined names.
580 <sect2 id="plpgsql-declaration-type">
581 <title>Copying Types</title>
584 <replaceable>variable</replaceable>%TYPE
588 <literal>%TYPE</literal> provides the data type of a variable or
589 table column. You can use this to declare variables that will hold
590 database values. For example, let's say you have a column named
591 <literal>user_id</literal> in your <literal>users</literal>
592 table. To declare a variable with the same data type as
593 <literal>users.user_id</> you write:
595 user_id users.user_id%TYPE;
600 By using <literal>%TYPE</literal> you don't need to know the data
601 type of the structure you are referencing, and most importantly,
602 if the data type of the referenced item changes in the future (for
603 instance: you change the type of <literal>user_id</>
604 from <type>integer</type> to <type>real</type>), you might not need
605 to change your function definition.
609 <literal>%TYPE</literal> is particularly valuable in polymorphic
610 functions, since the data types needed for internal variables can
611 change from one call to the next. Appropriate variables can be
612 created by applying <literal>%TYPE</literal> to the function's
613 arguments or result placeholders.
618 <sect2 id="plpgsql-declaration-rowtypes">
619 <title>Row Types</title>
622 <replaceable>name</replaceable> <replaceable>table_name</replaceable><literal>%ROWTYPE</literal>;
623 <replaceable>name</replaceable> <replaceable>composite_type_name</replaceable>;
627 A variable of a composite type is called a <firstterm>row</>
628 variable (or <firstterm>row-type</> variable). Such a variable
629 can hold a whole row of a <command>SELECT</> or <command>FOR</>
630 query result, so long as that query's column set matches the
631 declared type of the variable.
632 The individual fields of the row value
633 are accessed using the usual dot notation, for example
634 <literal>rowvar.field</literal>.
638 A row variable can be declared to have the same type as the rows of
639 an existing table or view, by using the
640 <replaceable>table_name</replaceable><literal>%ROWTYPE</literal>
641 notation; or it can be declared by giving a composite type's name.
642 (Since every table has an associated composite type of the same name,
643 it actually does not matter in <productname>PostgreSQL</> whether you
644 write <literal>%ROWTYPE</literal> or not. But the form with
645 <literal>%ROWTYPE</literal> is more portable.)
649 Parameters to a function can be
650 composite types (complete table rows). In that case, the
651 corresponding identifier <literal>$<replaceable>n</replaceable></> will be a row variable, and fields can
652 be selected from it, for example <literal>$1.user_id</literal>.
656 Only the user-defined columns of a table row are accessible in a
657 row-type variable, not the OID or other system columns (because the
658 row could be from a view). The fields of the row type inherit the
659 table's field size or precision for data types such as
660 <type>char(<replaceable>n</>)</type>.
664 Here is an example of using composite types. <structname>table1</>
665 and <structname>table2</> are existing tables having at least the
669 CREATE FUNCTION merge_fields(t_row table1) RETURNS text AS $$
671 t2_row table2%ROWTYPE;
673 SELECT * INTO t2_row FROM table2 WHERE ... ;
674 RETURN t_row.f1 || t2_row.f3 || t_row.f5 || t2_row.f7;
678 SELECT merge_fields(t.*) FROM table1 t WHERE ... ;
683 <sect2 id="plpgsql-declaration-records">
684 <title>Record Types</title>
687 <replaceable>name</replaceable> RECORD;
691 Record variables are similar to row-type variables, but they have no
692 predefined structure. They take on the actual row structure of the
693 row they are assigned during a <command>SELECT</> or <command>FOR</> command. The substructure
694 of a record variable can change each time it is assigned to.
695 A consequence of this is that until a record variable is first assigned
696 to, it has no substructure, and any attempt to access a
697 field in it will draw a run-time error.
701 Note that <literal>RECORD</> is not a true data type, only a placeholder.
702 One should also realize that when a <application>PL/pgSQL</application>
703 function is declared to return type <type>record</>, this is not quite the
704 same concept as a record variable, even though such a function might
705 use a record variable to hold its result. In both cases the actual row
706 structure is unknown when the function is written, but for a function
707 returning <type>record</> the actual structure is determined when the
708 calling query is parsed, whereas a record variable can change its row
709 structure on-the-fly.
713 <sect2 id="plpgsql-declaration-collation">
714 <title>Collation of <application>PL/pgSQL</application> Variables</title>
717 <primary>collation</>
718 <secondary>in PL/pgSQL</>
722 When a <application>PL/pgSQL</application> function has one or more
723 parameters of collatable data types, a collation is identified for each
724 function call depending on the collations assigned to the actual
725 arguments, as described in <xref linkend="collation">. If a collation is
726 successfully identified (i.e., there are no conflicts of implicit
727 collations among the arguments) then all the collatable parameters are
728 treated as having that collation implicitly. This will affect the
729 behavior of collation-sensitive operations within the function.
730 For example, consider
733 CREATE FUNCTION less_than(a text, b text) RETURNS boolean AS $$
739 SELECT less_than(text_field_1, text_field_2) FROM table1;
740 SELECT less_than(text_field_1, text_field_2 COLLATE "C") FROM table1;
743 The first use of <function>less_than</> will use the common collation
744 of <structfield>text_field_1</> and <structfield>text_field_2</> for
745 the comparison, while the second use will use <literal>C</> collation.
749 Furthermore, the identified collation is also assumed as the collation of
750 any local variables that are of collatable types. Thus this function
751 would not work any differently if it were written as
754 CREATE FUNCTION less_than(a text, b text) RETURNS boolean AS $$
759 RETURN local_a < local_b;
766 If there are no parameters of collatable data types, or no common
767 collation can be identified for them, then parameters and local variables
768 use the default collation of their data type (which is usually the
769 database's default collation, but could be different for variables of
774 A local variable of a collatable data type can have a different collation
775 associated with it by including the <literal>COLLATE</> option in its
776 declaration, for example
780 local_a text COLLATE "en_US";
783 This option overrides the collation that would otherwise be
784 given to the variable according to the rules above.
788 Also, of course explicit <literal>COLLATE</> clauses can be written inside
789 a function if it is desired to force a particular collation to be used in
790 a particular operation. For example,
793 CREATE FUNCTION less_than_c(a text, b text) RETURNS boolean AS $$
795 RETURN a < b COLLATE "C";
800 This overrides the collations associated with the table columns,
801 parameters, or local variables used in the expression, just as would
802 happen in a plain SQL command.
807 <sect1 id="plpgsql-expressions">
808 <title>Expressions</title>
811 All expressions used in <application>PL/pgSQL</application>
812 statements are processed using the server's main
813 <acronym>SQL</acronym> executor. For example, when you write
814 a <application>PL/pgSQL</application> statement like
816 IF <replaceable>expression</replaceable> THEN ...
818 <application>PL/pgSQL</application> will evaluate the expression by
821 SELECT <replaceable>expression</replaceable>
823 to the main SQL engine. While forming the <command>SELECT</> command,
824 any occurrences of <application>PL/pgSQL</application> variable names
825 are replaced by parameters, as discussed in detail in
826 <xref linkend="plpgsql-var-subst">.
827 This allows the query plan for the <command>SELECT</command> to
828 be prepared just once and then reused for subsequent
829 evaluations with different values of the variables. Thus, what
830 really happens on first use of an expression is essentially a
831 <command>PREPARE</> command. For example, if we have declared
832 two integer variables <literal>x</> and <literal>y</>, and we write
836 what happens behind the scenes is equivalent to
838 PREPARE <replaceable>statement_name</>(integer, integer) AS SELECT $1 < $2;
840 and then this prepared statement is <command>EXECUTE</>d for each
841 execution of the <command>IF</> statement, with the current values
842 of the <application>PL/pgSQL</application> variables supplied as
843 parameter values. Normally these details are
844 not important to a <application>PL/pgSQL</application> user, but
845 they are useful to know when trying to diagnose a problem.
846 More information appears in <xref linkend="plpgsql-plan-caching">.
850 <sect1 id="plpgsql-statements">
851 <title>Basic Statements</title>
854 In this section and the following ones, we describe all the statement
855 types that are explicitly understood by
856 <application>PL/pgSQL</application>.
857 Anything not recognized as one of these statement types is presumed
858 to be an SQL command and is sent to the main database engine to execute,
859 as described in <xref linkend="plpgsql-statements-sql-noresult">
860 and <xref linkend="plpgsql-statements-sql-onerow">.
863 <sect2 id="plpgsql-statements-assignment">
864 <title>Assignment</title>
867 An assignment of a value to a <application>PL/pgSQL</application>
868 variable is written as:
870 <replaceable>variable</replaceable> { := | = } <replaceable>expression</replaceable>;
872 As explained previously, the expression in such a statement is evaluated
873 by means of an SQL <command>SELECT</> command sent to the main
874 database engine. The expression must yield a single value (possibly
875 a row value, if the variable is a row or record variable). The target
876 variable can be a simple variable (optionally qualified with a block
877 name), a field of a row or record variable, or an element of an array
878 that is a simple variable or field. Equal (<literal>=</>) can be
879 used instead of PL/SQL-compliant <literal>:=</>.
883 If the expression's result data type doesn't match the variable's
884 data type, the value will be coerced as though by an assignment cast
885 (see <xref linkend="typeconv-query">). If no assignment cast is known
886 for the pair of data types involved, the <application>PL/pgSQL</>
887 interpreter will attempt to convert the result value textually, that is
888 by applying the result type's output function followed by the variable
889 type's input function. Note that this could result in run-time errors
890 generated by the input function, if the string form of the result value
891 is not acceptable to the input function.
897 tax := subtotal * 0.06;
898 my_record.user_id := 20;
903 <sect2 id="plpgsql-statements-sql-noresult">
904 <title>Executing a Command With No Result</title>
907 For any SQL command that does not return rows, for example
908 <command>INSERT</> without a <literal>RETURNING</> clause, you can
909 execute the command within a <application>PL/pgSQL</application> function
910 just by writing the command.
914 Any <application>PL/pgSQL</application> variable name appearing
915 in the command text is treated as a parameter, and then the
916 current value of the variable is provided as the parameter value
917 at run time. This is exactly like the processing described earlier
918 for expressions; for details see <xref linkend="plpgsql-var-subst">.
922 When executing a SQL command in this way,
923 <application>PL/pgSQL</application> may cache and re-use the execution
924 plan for the command, as discussed in
925 <xref linkend="plpgsql-plan-caching">.
929 Sometimes it is useful to evaluate an expression or <command>SELECT</>
930 query but discard the result, for example when calling a function
931 that has side-effects but no useful result value. To do
932 this in <application>PL/pgSQL</application>, use the
933 <command>PERFORM</command> statement:
936 PERFORM <replaceable>query</replaceable>;
939 This executes <replaceable>query</replaceable> and discards the
940 result. Write the <replaceable>query</replaceable> the same
941 way you would write an SQL <command>SELECT</> command, but replace the
942 initial keyword <command>SELECT</> with <command>PERFORM</command>.
943 For <command>WITH</> queries, use <command>PERFORM</> and then
944 place the query in parentheses. (In this case, the query can only
946 <application>PL/pgSQL</application> variables will be
947 substituted into the query just as for commands that return no result,
948 and the plan is cached in the same way. Also, the special variable
949 <literal>FOUND</literal> is set to true if the query produced at
950 least one row, or false if it produced no rows (see
951 <xref linkend="plpgsql-statements-diagnostics">).
956 One might expect that writing <command>SELECT</command> directly
957 would accomplish this result, but at
958 present the only accepted way to do it is
959 <command>PERFORM</command>. A SQL command that can return rows,
960 such as <command>SELECT</command>, will be rejected as an error
961 unless it has an <literal>INTO</> clause as discussed in the
969 PERFORM create_mv('cs_session_page_requests_mv', my_query);
974 <sect2 id="plpgsql-statements-sql-onerow">
975 <title>Executing a Query with a Single-row Result</title>
977 <indexterm zone="plpgsql-statements-sql-onerow">
978 <primary>SELECT INTO</primary>
979 <secondary>in PL/pgSQL</secondary>
982 <indexterm zone="plpgsql-statements-sql-onerow">
983 <primary>RETURNING INTO</primary>
984 <secondary>in PL/pgSQL</secondary>
988 The result of a SQL command yielding a single row (possibly of multiple
989 columns) can be assigned to a record variable, row-type variable, or list
990 of scalar variables. This is done by writing the base SQL command and
991 adding an <literal>INTO</> clause. For example,
994 SELECT <replaceable>select_expressions</replaceable> INTO <optional>STRICT</optional> <replaceable>target</replaceable> FROM ...;
995 INSERT ... RETURNING <replaceable>expressions</replaceable> INTO <optional>STRICT</optional> <replaceable>target</replaceable>;
996 UPDATE ... RETURNING <replaceable>expressions</replaceable> INTO <optional>STRICT</optional> <replaceable>target</replaceable>;
997 DELETE ... RETURNING <replaceable>expressions</replaceable> INTO <optional>STRICT</optional> <replaceable>target</replaceable>;
1000 where <replaceable>target</replaceable> can be a record variable, a row
1001 variable, or a comma-separated list of simple variables and
1003 <application>PL/pgSQL</application> variables will be
1004 substituted into the rest of the query, and the plan is cached,
1005 just as described above for commands that do not return rows.
1006 This works for <command>SELECT</>,
1007 <command>INSERT</>/<command>UPDATE</>/<command>DELETE</> with
1008 <literal>RETURNING</>, and utility commands that return row-set
1009 results (such as <command>EXPLAIN</>).
1010 Except for the <literal>INTO</> clause, the SQL command is the same
1011 as it would be written outside <application>PL/pgSQL</application>.
1016 Note that this interpretation of <command>SELECT</> with <literal>INTO</>
1017 is quite different from <productname>PostgreSQL</>'s regular
1018 <command>SELECT INTO</command> command, wherein the <literal>INTO</>
1019 target is a newly created table. If you want to create a table from a
1020 <command>SELECT</> result inside a
1021 <application>PL/pgSQL</application> function, use the syntax
1022 <command>CREATE TABLE ... AS SELECT</command>.
1027 If a row or a variable list is used as target, the query's result columns
1028 must exactly match the structure of the target as to number and data
1029 types, or else a run-time error
1030 occurs. When a record variable is the target, it automatically
1031 configures itself to the row type of the query result columns.
1035 The <literal>INTO</> clause can appear almost anywhere in the SQL
1036 command. Customarily it is written either just before or just after
1037 the list of <replaceable>select_expressions</replaceable> in a
1038 <command>SELECT</> command, or at the end of the command for other
1039 command types. It is recommended that you follow this convention
1040 in case the <application>PL/pgSQL</application> parser becomes
1041 stricter in future versions.
1045 If <literal>STRICT</literal> is not specified in the <literal>INTO</>
1046 clause, then <replaceable>target</replaceable> will be set to the first
1047 row returned by the query, or to nulls if the query returned no rows.
1048 (Note that <quote>the first row</> is not
1049 well-defined unless you've used <literal>ORDER BY</>.) Any result rows
1050 after the first row are discarded.
1051 You can check the special <literal>FOUND</literal> variable (see
1052 <xref linkend="plpgsql-statements-diagnostics">) to
1053 determine whether a row was returned:
1056 SELECT * INTO myrec FROM emp WHERE empname = myname;
1058 RAISE EXCEPTION 'employee % not found', myname;
1062 If the <literal>STRICT</literal> option is specified, the query must
1063 return exactly one row or a run-time error will be reported, either
1064 <literal>NO_DATA_FOUND</> (no rows) or <literal>TOO_MANY_ROWS</>
1065 (more than one row). You can use an exception block if you wish
1066 to catch the error, for example:
1070 SELECT * INTO STRICT myrec FROM emp WHERE empname = myname;
1072 WHEN NO_DATA_FOUND THEN
1073 RAISE EXCEPTION 'employee % not found', myname;
1074 WHEN TOO_MANY_ROWS THEN
1075 RAISE EXCEPTION 'employee % not unique', myname;
1078 Successful execution of a command with <literal>STRICT</>
1079 always sets <literal>FOUND</literal> to true.
1083 For <command>INSERT</>/<command>UPDATE</>/<command>DELETE</> with
1084 <literal>RETURNING</>, <application>PL/pgSQL</application> reports
1085 an error for more than one returned row, even when
1086 <literal>STRICT</literal> is not specified. This is because there
1087 is no option such as <literal>ORDER BY</> with which to determine
1088 which affected row should be returned.
1092 If <literal>print_strict_params</> is enabled for the function,
1093 then when an error is thrown because the requirements
1094 of <literal>STRICT</> are not met, the <literal>DETAIL</> part of
1095 the error message will include information about the parameters
1096 passed to the query.
1097 You can change the <literal>print_strict_params</>
1098 setting for all functions by setting
1099 <varname>plpgsql.print_strict_params</>, though only subsequent
1100 function compilations will be affected. You can also enable it
1101 on a per-function basis by using a compiler option, for example:
1103 CREATE FUNCTION get_userid(username text) RETURNS int
1105 #print_strict_params on
1109 SELECT users.userid INTO STRICT userid
1110 FROM users WHERE users.username = get_userid.username;
1113 $$ LANGUAGE plpgsql;
1115 On failure, this function might produce an error message such as
1117 ERROR: query returned no rows
1118 DETAIL: parameters: $1 = 'nosuchuser'
1119 CONTEXT: PL/pgSQL function get_userid(text) line 6 at SQL statement
1125 The <literal>STRICT</> option matches the behavior of
1126 Oracle PL/SQL's <command>SELECT INTO</command> and related statements.
1131 To handle cases where you need to process multiple result rows
1132 from a SQL query, see <xref linkend="plpgsql-records-iterating">.
1137 <sect2 id="plpgsql-statements-executing-dyn">
1138 <title>Executing Dynamic Commands</title>
1141 Oftentimes you will want to generate dynamic commands inside your
1142 <application>PL/pgSQL</application> functions, that is, commands
1143 that will involve different tables or different data types each
1144 time they are executed. <application>PL/pgSQL</application>'s
1145 normal attempts to cache plans for commands (as discussed in
1146 <xref linkend="plpgsql-plan-caching">) will not work in such
1147 scenarios. To handle this sort of problem, the
1148 <command>EXECUTE</command> statement is provided:
1151 EXECUTE <replaceable class="command">command-string</replaceable> <optional> INTO <optional>STRICT</optional> <replaceable>target</replaceable> </optional> <optional> USING <replaceable>expression</replaceable> <optional>, ... </optional> </optional>;
1154 where <replaceable>command-string</replaceable> is an expression
1155 yielding a string (of type <type>text</type>) containing the
1156 command to be executed. The optional <replaceable>target</replaceable>
1157 is a record variable, a row variable, or a comma-separated list of
1158 simple variables and record/row fields, into which the results of
1159 the command will be stored. The optional <literal>USING</> expressions
1160 supply values to be inserted into the command.
1164 No substitution of <application>PL/pgSQL</> variables is done on the
1165 computed command string. Any required variable values must be inserted
1166 in the command string as it is constructed; or you can use parameters
1171 Also, there is no plan caching for commands executed via
1172 <command>EXECUTE</command>. Instead, the command is always planned
1173 each time the statement is run. Thus the command
1174 string can be dynamically created within the function to perform
1175 actions on different tables and columns.
1179 The <literal>INTO</literal> clause specifies where the results of
1180 a SQL command returning rows should be assigned. If a row
1181 or variable list is provided, it must exactly match the structure
1182 of the query's results (when a
1183 record variable is used, it will configure itself to match the
1184 result structure automatically). If multiple rows are returned,
1185 only the first will be assigned to the <literal>INTO</literal>
1186 variable. If no rows are returned, NULL is assigned to the
1187 <literal>INTO</literal> variable(s). If no <literal>INTO</literal>
1188 clause is specified, the query results are discarded.
1192 If the <literal>STRICT</> option is given, an error is reported
1193 unless the query produces exactly one row.
1197 The command string can use parameter values, which are referenced
1198 in the command as <literal>$1</>, <literal>$2</>, etc.
1199 These symbols refer to values supplied in the <literal>USING</>
1200 clause. This method is often preferable to inserting data values
1201 into the command string as text: it avoids run-time overhead of
1202 converting the values to text and back, and it is much less prone
1203 to SQL-injection attacks since there is no need for quoting or escaping.
1206 EXECUTE 'SELECT count(*) FROM mytable WHERE inserted_by = $1 AND inserted <= $2'
1208 USING checked_user, checked_date;
1213 Note that parameter symbols can only be used for data values
1214 — if you want to use dynamically determined table or column
1215 names, you must insert them into the command string textually.
1216 For example, if the preceding query needed to be done against a
1217 dynamically selected table, you could do this:
1219 EXECUTE 'SELECT count(*) FROM '
1220 || quote_ident(tabname)
1221 || ' WHERE inserted_by = $1 AND inserted <= $2'
1223 USING checked_user, checked_date;
1225 A cleaner approach is to use <function>format()</>'s <literal>%I</>
1226 specification for table or column names (strings separated by a
1227 newline are concatenated):
1229 EXECUTE format('SELECT count(*) FROM %I '
1230 'WHERE inserted_by = $1 AND inserted <= $2', tabname)
1232 USING checked_user, checked_date;
1234 Another restriction on parameter symbols is that they only work in
1235 <command>SELECT</>, <command>INSERT</>, <command>UPDATE</>, and
1236 <command>DELETE</> commands. In other statement
1237 types (generically called utility statements), you must insert
1238 values textually even if they are just data values.
1242 An <command>EXECUTE</> with a simple constant command string and some
1243 <literal>USING</> parameters, as in the first example above, is
1244 functionally equivalent to just writing the command directly in
1245 <application>PL/pgSQL</application> and allowing replacement of
1246 <application>PL/pgSQL</application> variables to happen automatically.
1247 The important difference is that <command>EXECUTE</> will re-plan
1248 the command on each execution, generating a plan that is specific
1249 to the current parameter values; whereas
1250 <application>PL/pgSQL</application> may otherwise create a generic plan
1251 and cache it for re-use. In situations where the best plan depends
1252 strongly on the parameter values, it can be helpful to use
1253 <command>EXECUTE</> to positively ensure that a generic plan is not
1258 <command>SELECT INTO</command> is not currently supported within
1259 <command>EXECUTE</command>; instead, execute a plain <command>SELECT</>
1260 command and specify <literal>INTO</> as part of the <command>EXECUTE</>
1266 The <application>PL/pgSQL</application>
1267 <command>EXECUTE</command> statement is not related to the
1268 <xref linkend="sql-execute"> SQL
1269 statement supported by the
1270 <productname>PostgreSQL</productname> server. The server's
1271 <command>EXECUTE</command> statement cannot be used directly within
1272 <application>PL/pgSQL</> functions (and is not needed).
1276 <example id="plpgsql-quote-literal-example">
1277 <title>Quoting Values In Dynamic Queries</title>
1280 <primary>quote_ident</primary>
1281 <secondary>use in PL/pgSQL</secondary>
1285 <primary>quote_literal</primary>
1286 <secondary>use in PL/pgSQL</secondary>
1290 <primary>quote_nullable</primary>
1291 <secondary>use in PL/pgSQL</secondary>
1295 <primary>format</primary>
1296 <secondary>use in PL/pgSQL</secondary>
1300 When working with dynamic commands you will often have to handle escaping
1301 of single quotes. The recommended method for quoting fixed text in your
1302 function body is dollar quoting. (If you have legacy code that does
1303 not use dollar quoting, please refer to the
1304 overview in <xref linkend="plpgsql-quote-tips">, which can save you
1305 some effort when translating said code to a more reasonable scheme.)
1309 Dynamic values require careful handling since they might contain
1311 An example using <function>format()</> (this assumes that you are
1312 dollar quoting the function body so quote marks need not be doubled):
1314 EXECUTE format('UPDATE tbl SET %I = $1 '
1315 'WHERE key = $2', colname) USING newvalue, keyvalue;
1317 It is also possible to call the quoting functions directly:
1319 EXECUTE 'UPDATE tbl SET '
1320 || quote_ident(colname)
1322 || quote_literal(newvalue)
1324 || quote_literal(keyvalue);
1329 This example demonstrates the use of the
1330 <function>quote_ident</function> and
1331 <function>quote_literal</function> functions (see <xref
1332 linkend="functions-string">). For safety, expressions containing column
1333 or table identifiers should be passed through
1334 <function>quote_ident</function> before insertion in a dynamic query.
1335 Expressions containing values that should be literal strings in the
1336 constructed command should be passed through <function>quote_literal</>.
1337 These functions take the appropriate steps to return the input text
1338 enclosed in double or single quotes respectively, with any embedded
1339 special characters properly escaped.
1343 Because <function>quote_literal</function> is labeled
1344 <literal>STRICT</literal>, it will always return null when called with a
1345 null argument. In the above example, if <literal>newvalue</> or
1346 <literal>keyvalue</> were null, the entire dynamic query string would
1347 become null, leading to an error from <command>EXECUTE</command>.
1348 You can avoid this problem by using the <function>quote_nullable</>
1349 function, which works the same as <function>quote_literal</> except that
1350 when called with a null argument it returns the string <literal>NULL</>.
1353 EXECUTE 'UPDATE tbl SET '
1354 || quote_ident(colname)
1356 || quote_nullable(newvalue)
1358 || quote_nullable(keyvalue);
1360 If you are dealing with values that might be null, you should usually
1361 use <function>quote_nullable</> in place of <function>quote_literal</>.
1365 As always, care must be taken to ensure that null values in a query do
1366 not deliver unintended results. For example the <literal>WHERE</> clause
1368 'WHERE key = ' || quote_nullable(keyvalue)
1370 will never succeed if <literal>keyvalue</> is null, because the
1371 result of using the equality operator <literal>=</> with a null operand
1372 is always null. If you wish null to work like an ordinary key value,
1373 you would need to rewrite the above as
1375 'WHERE key IS NOT DISTINCT FROM ' || quote_nullable(keyvalue)
1377 (At present, <literal>IS NOT DISTINCT FROM</> is handled much less
1378 efficiently than <literal>=</>, so don't do this unless you must.
1379 See <xref linkend="functions-comparison"> for
1380 more information on nulls and <literal>IS DISTINCT</>.)
1384 Note that dollar quoting is only useful for quoting fixed text.
1385 It would be a very bad idea to try to write this example as:
1387 EXECUTE 'UPDATE tbl SET '
1388 || quote_ident(colname)
1391 || '$$ WHERE key = '
1392 || quote_literal(keyvalue);
1394 because it would break if the contents of <literal>newvalue</>
1395 happened to contain <literal>$$</>. The same objection would
1396 apply to any other dollar-quoting delimiter you might pick.
1397 So, to safely quote text that is not known in advance, you
1398 <emphasis>must</> use <function>quote_literal</>,
1399 <function>quote_nullable</>, or <function>quote_ident</>, as appropriate.
1403 Dynamic SQL statements can also be safely constructed using the
1404 <function>format</function> function (see <xref
1405 linkend="functions-string">). For example:
1407 EXECUTE format('UPDATE tbl SET %I = %L '
1408 'WHERE key = %L', colname, newvalue, keyvalue);
1410 <literal>%I</> is equivalent to <function>quote_ident</>, and
1411 <literal>%L</> is equivalent to <function>quote_nullable</function>.
1412 The <function>format</function> function can be used in conjunction with
1413 the <literal>USING</literal> clause:
1415 EXECUTE format('UPDATE tbl SET %I = $1 WHERE key = $2', colname)
1416 USING newvalue, keyvalue;
1418 This form is better because the variables are handled in their native
1419 data type format, rather than unconditionally converting them to
1420 text and quoting them via <literal>%L</>. It is also more efficient.
1425 A much larger example of a dynamic command and
1426 <command>EXECUTE</command> can be seen in <xref
1427 linkend="plpgsql-porting-ex2">, which builds and executes a
1428 <command>CREATE FUNCTION</> command to define a new function.
1432 <sect2 id="plpgsql-statements-diagnostics">
1433 <title>Obtaining the Result Status</title>
1436 There are several ways to determine the effect of a command. The
1437 first method is to use the <command>GET DIAGNOSTICS</command>
1438 command, which has the form:
1441 GET <optional> CURRENT </optional> DIAGNOSTICS <replaceable>variable</replaceable> { = | := } <replaceable>item</replaceable> <optional> , ... </optional>;
1444 This command allows retrieval of system status indicators. Each
1445 <replaceable>item</replaceable> is a key word identifying a status
1446 value to be assigned to the specified variable (which should be
1447 of the right data type to receive it). The currently available
1448 status items are <varname>ROW_COUNT</>, the number of rows
1449 processed by the last <acronym>SQL</acronym> command sent to
1450 the <acronym>SQL</acronym> engine, and <varname>RESULT_OID</>,
1451 the OID of the last row inserted by the most recent
1452 <acronym>SQL</acronym> command. Note that <varname>RESULT_OID</>
1453 is only useful after an <command>INSERT</command> command into a
1454 table containing OIDs.
1455 Colon-equal (<literal>:=</>) can be used instead of SQL-standard
1456 <literal>=</> for <command>GET DIAGNOSTICS</>.
1462 GET DIAGNOSTICS integer_var = ROW_COUNT;
1467 The second method to determine the effects of a command is to check the
1468 special variable named <literal>FOUND</literal>, which is of
1469 type <type>boolean</type>. <literal>FOUND</literal> starts out
1470 false within each <application>PL/pgSQL</application> function call.
1471 It is set by each of the following types of statements:
1476 A <command>SELECT INTO</command> statement sets
1477 <literal>FOUND</literal> true if a row is assigned, false if no
1483 A <command>PERFORM</> statement sets <literal>FOUND</literal>
1484 true if it produces (and discards) one or more rows, false if
1490 <command>UPDATE</>, <command>INSERT</>, and <command>DELETE</>
1491 statements set <literal>FOUND</literal> true if at least one
1492 row is affected, false if no row is affected.
1497 A <command>FETCH</> statement sets <literal>FOUND</literal>
1498 true if it returns a row, false if no row is returned.
1503 A <command>MOVE</> statement sets <literal>FOUND</literal>
1504 true if it successfully repositions the cursor, false otherwise.
1509 A <command>FOR</> or <command>FOREACH</> statement sets
1510 <literal>FOUND</literal> true
1511 if it iterates one or more times, else false.
1512 <literal>FOUND</literal> is set this way when the
1513 loop exits; inside the execution of the loop,
1514 <literal>FOUND</literal> is not modified by the
1515 loop statement, although it might be changed by the
1516 execution of other statements within the loop body.
1521 <command>RETURN QUERY</command> and <command>RETURN QUERY
1522 EXECUTE</command> statements set <literal>FOUND</literal>
1523 true if the query returns at least one row, false if no row
1529 Other <application>PL/pgSQL</application> statements do not change
1530 the state of <literal>FOUND</literal>.
1531 Note in particular that <command>EXECUTE</command>
1532 changes the output of <command>GET DIAGNOSTICS</command>, but
1533 does not change <literal>FOUND</literal>.
1537 <literal>FOUND</literal> is a local variable within each
1538 <application>PL/pgSQL</application> function; any changes to it
1539 affect only the current function.
1544 <sect2 id="plpgsql-statements-null">
1545 <title>Doing Nothing At All</title>
1548 Sometimes a placeholder statement that does nothing is useful.
1549 For example, it can indicate that one arm of an if/then/else
1550 chain is deliberately empty. For this purpose, use the
1551 <command>NULL</command> statement:
1559 For example, the following two fragments of code are equivalent:
1564 WHEN division_by_zero THEN
1565 NULL; -- ignore the error
1573 WHEN division_by_zero THEN -- ignore the error
1576 Which is preferable is a matter of taste.
1581 In Oracle's PL/SQL, empty statement lists are not allowed, and so
1582 <command>NULL</> statements are <emphasis>required</> for situations
1583 such as this. <application>PL/pgSQL</application> allows you to
1584 just write nothing, instead.
1591 <sect1 id="plpgsql-control-structures">
1592 <title>Control Structures</title>
1595 Control structures are probably the most useful (and
1596 important) part of <application>PL/pgSQL</>. With
1597 <application>PL/pgSQL</>'s control structures,
1598 you can manipulate <productname>PostgreSQL</> data in a very
1599 flexible and powerful way.
1602 <sect2 id="plpgsql-statements-returning">
1603 <title>Returning From a Function</title>
1606 There are two commands available that allow you to return data
1607 from a function: <command>RETURN</command> and <command>RETURN
1612 <title><command>RETURN</></title>
1615 RETURN <replaceable>expression</replaceable>;
1619 <command>RETURN</command> with an expression terminates the
1620 function and returns the value of
1621 <replaceable>expression</replaceable> to the caller. This form
1622 is used for <application>PL/pgSQL</> functions that do
1627 In a function that returns a scalar type, the expression's result will
1628 automatically be cast into the function's return type as described for
1629 assignments. But to return a composite (row) value, you must write an
1630 expression delivering exactly the requested column set. This may
1631 require use of explicit casting.
1635 If you declared the function with output parameters, write just
1636 <command>RETURN</command> with no expression. The current values
1637 of the output parameter variables will be returned.
1641 If you declared the function to return <type>void</type>, a
1642 <command>RETURN</command> statement can be used to exit the function
1643 early; but do not write an expression following
1644 <command>RETURN</command>.
1648 The return value of a function cannot be left undefined. If
1649 control reaches the end of the top-level block of the function
1650 without hitting a <command>RETURN</command> statement, a run-time
1651 error will occur. This restriction does not apply to functions
1652 with output parameters and functions returning <type>void</type>,
1653 however. In those cases a <command>RETURN</command> statement is
1654 automatically executed if the top-level block finishes.
1661 -- functions returning a scalar type
1665 -- functions returning a composite type
1666 RETURN composite_type_var;
1667 RETURN (1, 2, 'three'::text); -- must cast columns to correct types
1673 <title><command>RETURN NEXT</> and <command>RETURN QUERY</command></title>
1675 <primary>RETURN NEXT</primary>
1676 <secondary>in PL/pgSQL</secondary>
1679 <primary>RETURN QUERY</primary>
1680 <secondary>in PL/pgSQL</secondary>
1684 RETURN NEXT <replaceable>expression</replaceable>;
1685 RETURN QUERY <replaceable>query</replaceable>;
1686 RETURN QUERY EXECUTE <replaceable class="command">command-string</replaceable> <optional> USING <replaceable>expression</replaceable> <optional>, ... </optional> </optional>;
1690 When a <application>PL/pgSQL</> function is declared to return
1691 <literal>SETOF <replaceable>sometype</></literal>, the procedure
1692 to follow is slightly different. In that case, the individual
1693 items to return are specified by a sequence of <command>RETURN
1694 NEXT</command> or <command>RETURN QUERY</command> commands, and
1695 then a final <command>RETURN</command> command with no argument
1696 is used to indicate that the function has finished executing.
1697 <command>RETURN NEXT</command> can be used with both scalar and
1698 composite data types; with a composite result type, an entire
1699 <quote>table</quote> of results will be returned.
1700 <command>RETURN QUERY</command> appends the results of executing
1701 a query to the function's result set. <command>RETURN
1702 NEXT</command> and <command>RETURN QUERY</command> can be freely
1703 intermixed in a single set-returning function, in which case
1704 their results will be concatenated.
1708 <command>RETURN NEXT</command> and <command>RETURN
1709 QUERY</command> do not actually return from the function —
1710 they simply append zero or more rows to the function's result
1711 set. Execution then continues with the next statement in the
1712 <application>PL/pgSQL</> function. As successive
1713 <command>RETURN NEXT</command> or <command>RETURN
1714 QUERY</command> commands are executed, the result set is built
1715 up. A final <command>RETURN</command>, which should have no
1716 argument, causes control to exit the function (or you can just
1717 let control reach the end of the function).
1721 <command>RETURN QUERY</command> has a variant
1722 <command>RETURN QUERY EXECUTE</command>, which specifies the
1723 query to be executed dynamically. Parameter expressions can
1724 be inserted into the computed query string via <literal>USING</>,
1725 in just the same way as in the <command>EXECUTE</> command.
1729 If you declared the function with output parameters, write just
1730 <command>RETURN NEXT</command> with no expression. On each
1731 execution, the current values of the output parameter
1732 variable(s) will be saved for eventual return as a row of the
1733 result. Note that you must declare the function as returning
1734 <literal>SETOF record</literal> when there are multiple output
1735 parameters, or <literal>SETOF <replaceable>sometype</></literal>
1736 when there is just one output parameter of type
1737 <replaceable>sometype</>, in order to create a set-returning
1738 function with output parameters.
1742 Here is an example of a function using <command>RETURN
1746 CREATE TABLE foo (fooid INT, foosubid INT, fooname TEXT);
1747 INSERT INTO foo VALUES (1, 2, 'three');
1748 INSERT INTO foo VALUES (4, 5, 'six');
1750 CREATE OR REPLACE FUNCTION get_all_foo() RETURNS SETOF foo AS
1756 SELECT * FROM foo WHERE fooid > 0
1758 -- can do some processing here
1759 RETURN NEXT r; -- return current row of SELECT
1766 SELECT * FROM get_all_foo();
1771 Here is an example of a function using <command>RETURN
1775 CREATE FUNCTION get_available_flightid(date) RETURNS SETOF integer AS
1778 RETURN QUERY SELECT flightid
1780 WHERE flightdate >= $1
1781 AND flightdate < ($1 + 1);
1783 -- Since execution is not finished, we can check whether rows were returned
1784 -- and raise exception if not.
1786 RAISE EXCEPTION 'No flight at %.', $1;
1794 -- Returns available flights or raises exception if there are no
1795 -- available flights.
1796 SELECT * FROM get_available_flightid(CURRENT_DATE);
1802 The current implementation of <command>RETURN NEXT</command>
1803 and <command>RETURN QUERY</command> stores the entire result set
1804 before returning from the function, as discussed above. That
1805 means that if a <application>PL/pgSQL</> function produces a
1806 very large result set, performance might be poor: data will be
1807 written to disk to avoid memory exhaustion, but the function
1808 itself will not return until the entire result set has been
1809 generated. A future version of <application>PL/pgSQL</> might
1810 allow users to define set-returning functions
1811 that do not have this limitation. Currently, the point at
1812 which data begins being written to disk is controlled by the
1813 <xref linkend="guc-work-mem">
1814 configuration variable. Administrators who have sufficient
1815 memory to store larger result sets in memory should consider
1816 increasing this parameter.
1822 <sect2 id="plpgsql-conditionals">
1823 <title>Conditionals</title>
1826 <command>IF</> and <command>CASE</> statements let you execute
1827 alternative commands based on certain conditions.
1828 <application>PL/pgSQL</> has three forms of <command>IF</>:
1831 <para><literal>IF ... THEN</></>
1834 <para><literal>IF ... THEN ... ELSE</></>
1837 <para><literal>IF ... THEN ... ELSIF ... THEN ... ELSE</></>
1841 and two forms of <command>CASE</>:
1844 <para><literal>CASE ... WHEN ... THEN ... ELSE ... END CASE</></>
1847 <para><literal>CASE WHEN ... THEN ... ELSE ... END CASE</></>
1853 <title><literal>IF-THEN</></title>
1856 IF <replaceable>boolean-expression</replaceable> THEN
1857 <replaceable>statements</replaceable>
1862 <literal>IF-THEN</literal> statements are the simplest form of
1863 <literal>IF</literal>. The statements between
1864 <literal>THEN</literal> and <literal>END IF</literal> will be
1865 executed if the condition is true. Otherwise, they are
1872 IF v_user_id <> 0 THEN
1873 UPDATE users SET email = v_email WHERE user_id = v_user_id;
1880 <title><literal>IF-THEN-ELSE</></title>
1883 IF <replaceable>boolean-expression</replaceable> THEN
1884 <replaceable>statements</replaceable>
1886 <replaceable>statements</replaceable>
1891 <literal>IF-THEN-ELSE</literal> statements add to
1892 <literal>IF-THEN</literal> by letting you specify an
1893 alternative set of statements that should be executed if the
1894 condition is not true. (Note this includes the case where the
1895 condition evaluates to NULL.)
1901 IF parentid IS NULL OR parentid = ''
1905 RETURN hp_true_filename(parentid) || '/' || fullname;
1910 IF v_count > 0 THEN
1911 INSERT INTO users_count (count) VALUES (v_count);
1921 <title><literal>IF-THEN-ELSIF</></title>
1924 IF <replaceable>boolean-expression</replaceable> THEN
1925 <replaceable>statements</replaceable>
1926 <optional> ELSIF <replaceable>boolean-expression</replaceable> THEN
1927 <replaceable>statements</replaceable>
1928 <optional> ELSIF <replaceable>boolean-expression</replaceable> THEN
1929 <replaceable>statements</replaceable>
1934 <replaceable>statements</replaceable> </optional>
1939 Sometimes there are more than just two alternatives.
1940 <literal>IF-THEN-ELSIF</> provides a convenient
1941 method of checking several alternatives in turn.
1942 The <literal>IF</> conditions are tested successively
1943 until the first one that is true is found. Then the
1944 associated statement(s) are executed, after which control
1945 passes to the next statement after <literal>END IF</>.
1946 (Any subsequent <literal>IF</> conditions are <emphasis>not</>
1947 tested.) If none of the <literal>IF</> conditions is true,
1948 then the <literal>ELSE</> block (if any) is executed.
1957 ELSIF number > 0 THEN
1958 result := 'positive';
1959 ELSIF number < 0 THEN
1960 result := 'negative';
1962 -- hmm, the only other possibility is that number is null
1969 The key word <literal>ELSIF</> can also be spelled
1974 An alternative way of accomplishing the same task is to nest
1975 <literal>IF-THEN-ELSE</literal> statements, as in the
1979 IF demo_row.sex = 'm' THEN
1980 pretty_sex := 'man';
1982 IF demo_row.sex = 'f' THEN
1983 pretty_sex := 'woman';
1990 However, this method requires writing a matching <literal>END IF</>
1991 for each <literal>IF</>, so it is much more cumbersome than
1992 using <literal>ELSIF</> when there are many alternatives.
1997 <title>Simple <literal>CASE</></title>
2000 CASE <replaceable>search-expression</replaceable>
2001 WHEN <replaceable>expression</replaceable> <optional>, <replaceable>expression</replaceable> <optional> ... </optional></optional> THEN
2002 <replaceable>statements</replaceable>
2003 <optional> WHEN <replaceable>expression</replaceable> <optional>, <replaceable>expression</replaceable> <optional> ... </optional></optional> THEN
2004 <replaceable>statements</replaceable>
2007 <replaceable>statements</replaceable> </optional>
2012 The simple form of <command>CASE</> provides conditional execution
2013 based on equality of operands. The <replaceable>search-expression</>
2014 is evaluated (once) and successively compared to each
2015 <replaceable>expression</> in the <literal>WHEN</> clauses.
2016 If a match is found, then the corresponding
2017 <replaceable>statements</replaceable> are executed, and then control
2018 passes to the next statement after <literal>END CASE</>. (Subsequent
2019 <literal>WHEN</> expressions are not evaluated.) If no match is
2020 found, the <literal>ELSE</> <replaceable>statements</replaceable> are
2021 executed; but if <literal>ELSE</> is not present, then a
2022 <literal>CASE_NOT_FOUND</literal> exception is raised.
2026 Here is a simple example:
2031 msg := 'one or two';
2033 msg := 'other value than one or two';
2040 <title>Searched <literal>CASE</></title>
2044 WHEN <replaceable>boolean-expression</replaceable> THEN
2045 <replaceable>statements</replaceable>
2046 <optional> WHEN <replaceable>boolean-expression</replaceable> THEN
2047 <replaceable>statements</replaceable>
2050 <replaceable>statements</replaceable> </optional>
2055 The searched form of <command>CASE</> provides conditional execution
2056 based on truth of Boolean expressions. Each <literal>WHEN</> clause's
2057 <replaceable>boolean-expression</replaceable> is evaluated in turn,
2058 until one is found that yields <literal>true</>. Then the
2059 corresponding <replaceable>statements</replaceable> are executed, and
2060 then control passes to the next statement after <literal>END CASE</>.
2061 (Subsequent <literal>WHEN</> expressions are not evaluated.)
2062 If no true result is found, the <literal>ELSE</>
2063 <replaceable>statements</replaceable> are executed;
2064 but if <literal>ELSE</> is not present, then a
2065 <literal>CASE_NOT_FOUND</literal> exception is raised.
2073 WHEN x BETWEEN 0 AND 10 THEN
2074 msg := 'value is between zero and ten';
2075 WHEN x BETWEEN 11 AND 20 THEN
2076 msg := 'value is between eleven and twenty';
2082 This form of <command>CASE</> is entirely equivalent to
2083 <literal>IF-THEN-ELSIF</>, except for the rule that reaching
2084 an omitted <literal>ELSE</> clause results in an error rather
2091 <sect2 id="plpgsql-control-structures-loops">
2092 <title>Simple Loops</title>
2094 <indexterm zone="plpgsql-control-structures-loops">
2095 <primary>loop</primary>
2096 <secondary>in PL/pgSQL</secondary>
2100 With the <literal>LOOP</>, <literal>EXIT</>,
2101 <literal>CONTINUE</>, <literal>WHILE</>, <literal>FOR</>,
2102 and <literal>FOREACH</> statements, you can arrange for your
2103 <application>PL/pgSQL</> function to repeat a series of commands.
2107 <title><literal>LOOP</></title>
2110 <optional> <<<replaceable>label</replaceable>>> </optional>
2112 <replaceable>statements</replaceable>
2113 END LOOP <optional> <replaceable>label</replaceable> </optional>;
2117 <literal>LOOP</> defines an unconditional loop that is repeated
2118 indefinitely until terminated by an <literal>EXIT</> or
2119 <command>RETURN</command> statement. The optional
2120 <replaceable>label</replaceable> can be used by <literal>EXIT</>
2121 and <literal>CONTINUE</literal> statements within nested loops to
2122 specify which loop those statements refer to.
2127 <title><literal>EXIT</></title>
2130 <primary>EXIT</primary>
2131 <secondary>in PL/pgSQL</secondary>
2135 EXIT <optional> <replaceable>label</replaceable> </optional> <optional> WHEN <replaceable>boolean-expression</replaceable> </optional>;
2139 If no <replaceable>label</replaceable> is given, the innermost
2140 loop is terminated and the statement following <literal>END
2141 LOOP</> is executed next. If <replaceable>label</replaceable>
2142 is given, it must be the label of the current or some outer
2143 level of nested loop or block. Then the named loop or block is
2144 terminated and control continues with the statement after the
2145 loop's/block's corresponding <literal>END</>.
2149 If <literal>WHEN</> is specified, the loop exit occurs only if
2150 <replaceable>boolean-expression</> is true. Otherwise, control passes
2151 to the statement after <literal>EXIT</>.
2155 <literal>EXIT</> can be used with all types of loops; it is
2156 not limited to use with unconditional loops.
2161 <literal>BEGIN</literal> block, <literal>EXIT</literal> passes
2162 control to the next statement after the end of the block.
2163 Note that a label must be used for this purpose; an unlabeled
2164 <literal>EXIT</literal> is never considered to match a
2165 <literal>BEGIN</literal> block. (This is a change from
2166 pre-8.4 releases of <productname>PostgreSQL</productname>, which
2167 would allow an unlabeled <literal>EXIT</literal> to match
2168 a <literal>BEGIN</literal> block.)
2175 -- some computations
2176 IF count > 0 THEN
2182 -- some computations
2183 EXIT WHEN count > 0; -- same result as previous example
2186 <<ablock>>
2188 -- some computations
2189 IF stocks > 100000 THEN
2190 EXIT ablock; -- causes exit from the BEGIN block
2192 -- computations here will be skipped when stocks > 100000
2199 <title><literal>CONTINUE</></title>
2202 <primary>CONTINUE</primary>
2203 <secondary>in PL/pgSQL</secondary>
2207 CONTINUE <optional> <replaceable>label</replaceable> </optional> <optional> WHEN <replaceable>boolean-expression</replaceable> </optional>;
2211 If no <replaceable>label</> is given, the next iteration of
2212 the innermost loop is begun. That is, all statements remaining
2213 in the loop body are skipped, and control returns
2214 to the loop control expression (if any) to determine whether
2215 another loop iteration is needed.
2216 If <replaceable>label</> is present, it
2217 specifies the label of the loop whose execution will be
2222 If <literal>WHEN</> is specified, the next iteration of the
2223 loop is begun only if <replaceable>boolean-expression</> is
2224 true. Otherwise, control passes to the statement after
2225 <literal>CONTINUE</>.
2229 <literal>CONTINUE</> can be used with all types of loops; it
2230 is not limited to use with unconditional loops.
2237 -- some computations
2238 EXIT WHEN count > 100;
2239 CONTINUE WHEN count < 50;
2240 -- some computations for count IN [50 .. 100]
2248 <title><literal>WHILE</></title>
2251 <primary>WHILE</primary>
2252 <secondary>in PL/pgSQL</secondary>
2256 <optional> <<<replaceable>label</replaceable>>> </optional>
2257 WHILE <replaceable>boolean-expression</replaceable> LOOP
2258 <replaceable>statements</replaceable>
2259 END LOOP <optional> <replaceable>label</replaceable> </optional>;
2263 The <literal>WHILE</> statement repeats a
2264 sequence of statements so long as the
2265 <replaceable>boolean-expression</replaceable>
2266 evaluates to true. The expression is checked just before
2267 each entry to the loop body.
2273 WHILE amount_owed > 0 AND gift_certificate_balance > 0 LOOP
2274 -- some computations here
2278 -- some computations here
2284 <sect3 id="plpgsql-integer-for">
2285 <title><literal>FOR</> (Integer Variant)</title>
2288 <optional> <<<replaceable>label</replaceable>>> </optional>
2289 FOR <replaceable>name</replaceable> IN <optional> REVERSE </optional> <replaceable>expression</replaceable> .. <replaceable>expression</replaceable> <optional> BY <replaceable>expression</replaceable> </optional> LOOP
2290 <replaceable>statements</replaceable>
2291 END LOOP <optional> <replaceable>label</replaceable> </optional>;
2295 This form of <literal>FOR</> creates a loop that iterates over a range
2296 of integer values. The variable
2297 <replaceable>name</replaceable> is automatically defined as type
2298 <type>integer</> and exists only inside the loop (any existing
2299 definition of the variable name is ignored within the loop).
2300 The two expressions giving
2301 the lower and upper bound of the range are evaluated once when entering
2302 the loop. If the <literal>BY</> clause isn't specified the iteration
2303 step is 1, otherwise it's the value specified in the <literal>BY</>
2304 clause, which again is evaluated once on loop entry.
2305 If <literal>REVERSE</> is specified then the step value is
2306 subtracted, rather than added, after each iteration.
2310 Some examples of integer <literal>FOR</> loops:
2313 -- i will take on the values 1,2,3,4,5,6,7,8,9,10 within the loop
2316 FOR i IN REVERSE 10..1 LOOP
2317 -- i will take on the values 10,9,8,7,6,5,4,3,2,1 within the loop
2320 FOR i IN REVERSE 10..1 BY 2 LOOP
2321 -- i will take on the values 10,8,6,4,2 within the loop
2327 If the lower bound is greater than the upper bound (or less than,
2328 in the <literal>REVERSE</> case), the loop body is not
2329 executed at all. No error is raised.
2333 If a <replaceable>label</replaceable> is attached to the
2334 <literal>FOR</> loop then the integer loop variable can be
2335 referenced with a qualified name, using that
2336 <replaceable>label</replaceable>.
2341 <sect2 id="plpgsql-records-iterating">
2342 <title>Looping Through Query Results</title>
2345 Using a different type of <literal>FOR</> loop, you can iterate through
2346 the results of a query and manipulate that data
2347 accordingly. The syntax is:
2349 <optional> <<<replaceable>label</replaceable>>> </optional>
2350 FOR <replaceable>target</replaceable> IN <replaceable>query</replaceable> LOOP
2351 <replaceable>statements</replaceable>
2352 END LOOP <optional> <replaceable>label</replaceable> </optional>;
2354 The <replaceable>target</replaceable> is a record variable, row variable,
2355 or comma-separated list of scalar variables.
2356 The <replaceable>target</replaceable> is successively assigned each row
2357 resulting from the <replaceable>query</replaceable> and the loop body is
2358 executed for each row. Here is an example:
2360 CREATE FUNCTION cs_refresh_mviews() RETURNS integer AS $$
2364 RAISE NOTICE 'Refreshing materialized views...';
2366 FOR mviews IN SELECT * FROM cs_materialized_views ORDER BY sort_key LOOP
2368 -- Now "mviews" has one record from cs_materialized_views
2370 RAISE NOTICE 'Refreshing materialized view %s ...', quote_ident(mviews.mv_name);
2371 EXECUTE format('TRUNCATE TABLE %I', mviews.mv_name);
2372 EXECUTE format('INSERT INTO %I %s', mviews.mv_name, mviews.mv_query);
2375 RAISE NOTICE 'Done refreshing materialized views.';
2378 $$ LANGUAGE plpgsql;
2381 If the loop is terminated by an <literal>EXIT</> statement, the last
2382 assigned row value is still accessible after the loop.
2386 The <replaceable>query</replaceable> used in this type of <literal>FOR</>
2387 statement can be any SQL command that returns rows to the caller:
2388 <command>SELECT</> is the most common case,
2389 but you can also use <command>INSERT</>, <command>UPDATE</>, or
2390 <command>DELETE</> with a <literal>RETURNING</> clause. Some utility
2391 commands such as <command>EXPLAIN</> will work too.
2395 <application>PL/pgSQL</> variables are substituted into the query text,
2396 and the query plan is cached for possible re-use, as discussed in
2397 detail in <xref linkend="plpgsql-var-subst"> and
2398 <xref linkend="plpgsql-plan-caching">.
2402 The <literal>FOR-IN-EXECUTE</> statement is another way to iterate over
2405 <optional> <<<replaceable>label</replaceable>>> </optional>
2406 FOR <replaceable>target</replaceable> IN EXECUTE <replaceable>text_expression</replaceable> <optional> USING <replaceable>expression</replaceable> <optional>, ... </optional> </optional> LOOP
2407 <replaceable>statements</replaceable>
2408 END LOOP <optional> <replaceable>label</replaceable> </optional>;
2410 This is like the previous form, except that the source query
2411 is specified as a string expression, which is evaluated and replanned
2412 on each entry to the <literal>FOR</> loop. This allows the programmer to
2413 choose the speed of a preplanned query or the flexibility of a dynamic
2414 query, just as with a plain <command>EXECUTE</command> statement.
2415 As with <command>EXECUTE</command>, parameter values can be inserted
2416 into the dynamic command via <literal>USING</>.
2420 Another way to specify the query whose results should be iterated
2421 through is to declare it as a cursor. This is described in
2422 <xref linkend="plpgsql-cursor-for-loop">.
2426 <sect2 id="plpgsql-foreach-array">
2427 <title>Looping Through Arrays</title>
2430 The <literal>FOREACH</> loop is much like a <literal>FOR</> loop,
2431 but instead of iterating through the rows returned by a SQL query,
2432 it iterates through the elements of an array value.
2433 (In general, <literal>FOREACH</> is meant for looping through
2434 components of a composite-valued expression; variants for looping
2435 through composites besides arrays may be added in future.)
2436 The <literal>FOREACH</> statement to loop over an array is:
2439 <optional> <<<replaceable>label</replaceable>>> </optional>
2440 FOREACH <replaceable>target</replaceable> <optional> SLICE <replaceable>number</replaceable> </optional> IN ARRAY <replaceable>expression</replaceable> LOOP
2441 <replaceable>statements</replaceable>
2442 END LOOP <optional> <replaceable>label</replaceable> </optional>;
2447 Without <literal>SLICE</>, or if <literal>SLICE 0</> is specified,
2448 the loop iterates through individual elements of the array produced
2449 by evaluating the <replaceable>expression</replaceable>.
2450 The <replaceable>target</replaceable> variable is assigned each
2451 element value in sequence, and the loop body is executed for each element.
2452 Here is an example of looping through the elements of an integer
2456 CREATE FUNCTION sum(int[]) RETURNS int8 AS $$
2461 FOREACH x IN ARRAY $1
2467 $$ LANGUAGE plpgsql;
2470 The elements are visited in storage order, regardless of the number of
2471 array dimensions. Although the <replaceable>target</replaceable> is
2472 usually just a single variable, it can be a list of variables when
2473 looping through an array of composite values (records). In that case,
2474 for each array element, the variables are assigned from successive
2475 columns of the composite value.
2479 With a positive <literal>SLICE</> value, <literal>FOREACH</>
2480 iterates through slices of the array rather than single elements.
2481 The <literal>SLICE</> value must be an integer constant not larger
2482 than the number of dimensions of the array. The
2483 <replaceable>target</replaceable> variable must be an array,
2484 and it receives successive slices of the array value, where each slice
2485 is of the number of dimensions specified by <literal>SLICE</>.
2486 Here is an example of iterating through one-dimensional slices:
2489 CREATE FUNCTION scan_rows(int[]) RETURNS void AS $$
2493 FOREACH x SLICE 1 IN ARRAY $1
2495 RAISE NOTICE 'row = %', x;
2498 $$ LANGUAGE plpgsql;
2500 SELECT scan_rows(ARRAY[[1,2,3],[4,5,6],[7,8,9],[10,11,12]]);
2502 NOTICE: row = {1,2,3}
2503 NOTICE: row = {4,5,6}
2504 NOTICE: row = {7,8,9}
2505 NOTICE: row = {10,11,12}
2510 <sect2 id="plpgsql-error-trapping">
2511 <title>Trapping Errors</title>
2514 <primary>exceptions</primary>
2515 <secondary>in PL/pgSQL</secondary>
2519 By default, any error occurring in a <application>PL/pgSQL</>
2520 function aborts execution of the function, and indeed of the
2521 surrounding transaction as well. You can trap errors and recover
2522 from them by using a <command>BEGIN</> block with an
2523 <literal>EXCEPTION</> clause. The syntax is an extension of the
2524 normal syntax for a <command>BEGIN</> block:
2527 <optional> <<<replaceable>label</replaceable>>> </optional>
2529 <replaceable>declarations</replaceable> </optional>
2531 <replaceable>statements</replaceable>
2533 WHEN <replaceable>condition</replaceable> <optional> OR <replaceable>condition</replaceable> ... </optional> THEN
2534 <replaceable>handler_statements</replaceable>
2535 <optional> WHEN <replaceable>condition</replaceable> <optional> OR <replaceable>condition</replaceable> ... </optional> THEN
2536 <replaceable>handler_statements</replaceable>
2543 If no error occurs, this form of block simply executes all the
2544 <replaceable>statements</replaceable>, and then control passes
2545 to the next statement after <literal>END</>. But if an error
2546 occurs within the <replaceable>statements</replaceable>, further
2547 processing of the <replaceable>statements</replaceable> is
2548 abandoned, and control passes to the <literal>EXCEPTION</> list.
2549 The list is searched for the first <replaceable>condition</replaceable>
2550 matching the error that occurred. If a match is found, the
2551 corresponding <replaceable>handler_statements</replaceable> are
2552 executed, and then control passes to the next statement after
2553 <literal>END</>. If no match is found, the error propagates out
2554 as though the <literal>EXCEPTION</> clause were not there at all:
2555 the error can be caught by an enclosing block with
2556 <literal>EXCEPTION</>, or if there is none it aborts processing
2561 The <replaceable>condition</replaceable> names can be any of
2562 those shown in <xref linkend="errcodes-appendix">. A category
2563 name matches any error within its category. The special
2564 condition name <literal>OTHERS</> matches every error type except
2565 <literal>QUERY_CANCELED</> and <literal>ASSERT_FAILURE</>.
2566 (It is possible, but often unwise, to trap those two error types
2567 by name.) Condition names are
2568 not case-sensitive. Also, an error condition can be specified
2569 by <literal>SQLSTATE</> code; for example these are equivalent:
2571 WHEN division_by_zero THEN ...
2572 WHEN SQLSTATE '22012' THEN ...
2577 If a new error occurs within the selected
2578 <replaceable>handler_statements</replaceable>, it cannot be caught
2579 by this <literal>EXCEPTION</> clause, but is propagated out.
2580 A surrounding <literal>EXCEPTION</> clause could catch it.
2584 When an error is caught by an <literal>EXCEPTION</> clause,
2585 the local variables of the <application>PL/pgSQL</> function
2586 remain as they were when the error occurred, but all changes
2587 to persistent database state within the block are rolled back.
2588 As an example, consider this fragment:
2591 INSERT INTO mytab(firstname, lastname) VALUES('Tom', 'Jones');
2593 UPDATE mytab SET firstname = 'Joe' WHERE lastname = 'Jones';
2597 WHEN division_by_zero THEN
2598 RAISE NOTICE 'caught division_by_zero';
2603 When control reaches the assignment to <literal>y</>, it will
2604 fail with a <literal>division_by_zero</> error. This will be caught by
2605 the <literal>EXCEPTION</> clause. The value returned in the
2606 <command>RETURN</> statement will be the incremented value of
2607 <literal>x</>, but the effects of the <command>UPDATE</> command will
2608 have been rolled back. The <command>INSERT</> command preceding the
2609 block is not rolled back, however, so the end result is that the database
2610 contains <literal>Tom Jones</> not <literal>Joe Jones</>.
2615 A block containing an <literal>EXCEPTION</> clause is significantly
2616 more expensive to enter and exit than a block without one. Therefore,
2617 don't use <literal>EXCEPTION</> without need.
2621 <example id="plpgsql-upsert-example">
2622 <title>Exceptions with <command>UPDATE</>/<command>INSERT</></title>
2625 This example uses exception handling to perform either
2626 <command>UPDATE</> or <command>INSERT</>, as appropriate. It is
2627 recommended that applications use <command>INSERT</> with
2628 <literal>ON CONFLICT DO UPDATE</> rather than actually using
2629 this pattern. This example serves primarily to illustrate use of
2630 <application>PL/pgSQL</application> control flow structures:
2633 CREATE TABLE db (a INT PRIMARY KEY, b TEXT);
2635 CREATE FUNCTION merge_db(key INT, data TEXT) RETURNS VOID AS
2639 -- first try to update the key
2640 UPDATE db SET b = data WHERE a = key;
2644 -- not there, so try to insert the key
2645 -- if someone else inserts the same key concurrently,
2646 -- we could get a unique-key failure
2648 INSERT INTO db(a,b) VALUES (key, data);
2650 EXCEPTION WHEN unique_violation THEN
2651 -- Do nothing, and loop to try the UPDATE again.
2658 SELECT merge_db(1, 'david');
2659 SELECT merge_db(1, 'dennis');
2662 This coding assumes the <literal>unique_violation</> error is caused by
2663 the <command>INSERT</>, and not by, say, an <command>INSERT</> in a
2664 trigger function on the table. It might also misbehave if there is
2665 more than one unique index on the table, since it will retry the
2666 operation regardless of which index caused the error.
2667 More safety could be had by using the
2668 features discussed next to check that the trapped error was the one
2673 <sect3 id="plpgsql-exception-diagnostics">
2674 <title>Obtaining Information About an Error</title>
2677 Exception handlers frequently need to identify the specific error that
2678 occurred. There are two ways to get information about the current
2679 exception in <application>PL/pgSQL</>: special variables and the
2680 <command>GET STACKED DIAGNOSTICS</command> command.
2684 Within an exception handler, the special variable
2685 <varname>SQLSTATE</varname> contains the error code that corresponds to
2686 the exception that was raised (refer to <xref linkend="errcodes-table">
2687 for a list of possible error codes). The special variable
2688 <varname>SQLERRM</varname> contains the error message associated with the
2689 exception. These variables are undefined outside exception handlers.
2693 Within an exception handler, one may also retrieve
2694 information about the current exception by using the
2695 <command>GET STACKED DIAGNOSTICS</command> command, which has the form:
2698 GET STACKED DIAGNOSTICS <replaceable>variable</replaceable> { = | := } <replaceable>item</replaceable> <optional> , ... </optional>;
2701 Each <replaceable>item</replaceable> is a key word identifying a status
2702 value to be assigned to the specified variable (which should be
2703 of the right data type to receive it). The currently available
2704 status items are shown in <xref linkend="plpgsql-exception-diagnostics-values">.
2707 <table id="plpgsql-exception-diagnostics-values">
2708 <title>Error Diagnostics Values</title>
2714 <entry>Description</entry>
2719 <entry><literal>RETURNED_SQLSTATE</literal></entry>
2721 <entry>the SQLSTATE error code of the exception</entry>
2724 <entry><literal>COLUMN_NAME</literal></entry>
2726 <entry>the name of the column related to exception</entry>
2729 <entry><literal>CONSTRAINT_NAME</literal></entry>
2731 <entry>the name of the constraint related to exception</entry>
2734 <entry><literal>PG_DATATYPE_NAME</literal></entry>
2736 <entry>the name of the data type related to exception</entry>
2739 <entry><literal>MESSAGE_TEXT</literal></entry>
2741 <entry>the text of the exception's primary message</entry>
2744 <entry><literal>TABLE_NAME</literal></entry>
2746 <entry>the name of the table related to exception</entry>
2749 <entry><literal>SCHEMA_NAME</literal></entry>
2751 <entry>the name of the schema related to exception</entry>
2754 <entry><literal>PG_EXCEPTION_DETAIL</literal></entry>
2756 <entry>the text of the exception's detail message, if any</entry>
2759 <entry><literal>PG_EXCEPTION_HINT</literal></entry>
2761 <entry>the text of the exception's hint message, if any</entry>
2764 <entry><literal>PG_EXCEPTION_CONTEXT</literal></entry>
2766 <entry>line(s) of text describing the call stack</entry>
2773 If the exception did not set a value for an item, an empty string
2785 -- some processing which might cause an exception
2787 EXCEPTION WHEN OTHERS THEN
2788 GET STACKED DIAGNOSTICS text_var1 = MESSAGE_TEXT,
2789 text_var2 = PG_EXCEPTION_DETAIL,
2790 text_var3 = PG_EXCEPTION_HINT;
2797 <sect2 id="plpgsql-get-diagnostics-context">
2798 <title>Obtaining Current Execution Information</title>
2801 The <command>GET <optional> CURRENT </optional> DIAGNOSTICS</command>
2802 command retrieves information about current execution state (whereas
2803 the <command>GET STACKED DIAGNOSTICS</command> command discussed above
2804 reports information about the execution state as of a previous error).
2805 This command has the form:
2809 GET <optional> CURRENT </optional> DIAGNOSTICS <replaceable>variable</replaceable> { = | := } <replaceable>item</replaceable> <optional> , ... </optional>;
2813 Currently only one information item is supported. Status
2814 item <literal>PG_CONTEXT</> will return a text string with line(s) of
2815 text describing the call stack. The first line refers to the
2816 current function and currently executing <command>GET DIAGNOSTICS</command>
2817 command. The second and any subsequent lines refer to calling functions
2818 further up the call stack. For example:
2821 CREATE OR REPLACE FUNCTION outer_func() RETURNS integer AS $$
2823 RETURN inner_func();
2825 $$ LANGUAGE plpgsql;
2827 CREATE OR REPLACE FUNCTION inner_func() RETURNS integer AS $$
2831 GET DIAGNOSTICS stack = PG_CONTEXT;
2832 RAISE NOTICE E'--- Call Stack ---\n%', stack;
2835 $$ LANGUAGE plpgsql;
2837 SELECT outer_func();
2839 NOTICE: --- Call Stack ---
2840 PL/pgSQL function inner_func() line 5 at GET DIAGNOSTICS
2841 PL/pgSQL function outer_func() line 3 at RETURN
2842 CONTEXT: PL/pgSQL function outer_func() line 3 at RETURN
2853 <sect1 id="plpgsql-cursors">
2854 <title>Cursors</title>
2856 <indexterm zone="plpgsql-cursors">
2857 <primary>cursor</primary>
2858 <secondary>in PL/pgSQL</secondary>
2862 Rather than executing a whole query at once, it is possible to set
2863 up a <firstterm>cursor</> that encapsulates the query, and then read
2864 the query result a few rows at a time. One reason for doing this is
2865 to avoid memory overrun when the result contains a large number of
2866 rows. (However, <application>PL/pgSQL</> users do not normally need
2867 to worry about that, since <literal>FOR</> loops automatically use a cursor
2868 internally to avoid memory problems.) A more interesting usage is to
2869 return a reference to a cursor that a function has created, allowing the
2870 caller to read the rows. This provides an efficient way to return
2871 large row sets from functions.
2874 <sect2 id="plpgsql-cursor-declarations">
2875 <title>Declaring Cursor Variables</title>
2878 All access to cursors in <application>PL/pgSQL</> goes through
2879 cursor variables, which are always of the special data type
2880 <type>refcursor</>. One way to create a cursor variable
2881 is just to declare it as a variable of type <type>refcursor</>.
2882 Another way is to use the cursor declaration syntax,
2883 which in general is:
2885 <replaceable>name</replaceable> <optional> <optional> NO </optional> SCROLL </optional> CURSOR <optional> ( <replaceable>arguments</replaceable> ) </optional> FOR <replaceable>query</replaceable>;
2887 (<literal>FOR</> can be replaced by <literal>IS</> for
2888 <productname>Oracle</productname> compatibility.)
2889 If <literal>SCROLL</> is specified, the cursor will be capable of
2890 scrolling backward; if <literal>NO SCROLL</> is specified, backward
2891 fetches will be rejected; if neither specification appears, it is
2892 query-dependent whether backward fetches will be allowed.
2893 <replaceable>arguments</replaceable>, if specified, is a
2894 comma-separated list of pairs <literal><replaceable>name</replaceable>
2895 <replaceable>datatype</replaceable></literal> that define names to be
2896 replaced by parameter values in the given query. The actual
2897 values to substitute for these names will be specified later,
2898 when the cursor is opened.
2905 curs2 CURSOR FOR SELECT * FROM tenk1;
2906 curs3 CURSOR (key integer) FOR SELECT * FROM tenk1 WHERE unique1 = key;
2908 All three of these variables have the data type <type>refcursor</>,
2909 but the first can be used with any query, while the second has
2910 a fully specified query already <firstterm>bound</> to it, and the last
2911 has a parameterized query bound to it. (<literal>key</> will be
2912 replaced by an integer parameter value when the cursor is opened.)
2913 The variable <literal>curs1</>
2914 is said to be <firstterm>unbound</> since it is not bound to
2915 any particular query.
2919 <sect2 id="plpgsql-cursor-opening">
2920 <title>Opening Cursors</title>
2923 Before a cursor can be used to retrieve rows, it must be
2924 <firstterm>opened</>. (This is the equivalent action to the SQL
2925 command <command>DECLARE CURSOR</>.) <application>PL/pgSQL</> has
2926 three forms of the <command>OPEN</> statement, two of which use unbound
2927 cursor variables while the third uses a bound cursor variable.
2932 Bound cursor variables can also be used without explicitly opening the cursor,
2933 via the <command>FOR</> statement described in
2934 <xref linkend="plpgsql-cursor-for-loop">.
2939 <title><command>OPEN FOR</command> <replaceable>query</replaceable></title>
2942 OPEN <replaceable>unbound_cursorvar</replaceable> <optional> <optional> NO </optional> SCROLL </optional> FOR <replaceable>query</replaceable>;
2946 The cursor variable is opened and given the specified query to
2947 execute. The cursor cannot be open already, and it must have been
2948 declared as an unbound cursor variable (that is, as a simple
2949 <type>refcursor</> variable). The query must be a
2950 <command>SELECT</command>, or something else that returns rows
2951 (such as <command>EXPLAIN</>). The query
2952 is treated in the same way as other SQL commands in
2953 <application>PL/pgSQL</>: <application>PL/pgSQL</>
2954 variable names are substituted, and the query plan is cached for
2955 possible reuse. When a <application>PL/pgSQL</>
2956 variable is substituted into the cursor query, the value that is
2957 substituted is the one it has at the time of the <command>OPEN</>;
2958 subsequent changes to the variable will not affect the cursor's
2960 The <literal>SCROLL</> and <literal>NO SCROLL</>
2961 options have the same meanings as for a bound cursor.
2967 OPEN curs1 FOR SELECT * FROM foo WHERE key = mykey;
2973 <title><command>OPEN FOR EXECUTE</command></title>
2976 OPEN <replaceable>unbound_cursorvar</replaceable> <optional> <optional> NO </optional> SCROLL </optional> FOR EXECUTE <replaceable class="command">query_string</replaceable>
2977 <optional> USING <replaceable>expression</replaceable> <optional>, ... </optional> </optional>;
2981 The cursor variable is opened and given the specified query to
2982 execute. The cursor cannot be open already, and it must have been
2983 declared as an unbound cursor variable (that is, as a simple
2984 <type>refcursor</> variable). The query is specified as a string
2985 expression, in the same way as in the <command>EXECUTE</command>
2986 command. As usual, this gives flexibility so the query plan can vary
2987 from one run to the next (see <xref linkend="plpgsql-plan-caching">),
2988 and it also means that variable substitution is not done on the
2989 command string. As with <command>EXECUTE</command>, parameter values
2990 can be inserted into the dynamic command via
2991 <literal>format()</> and <literal>USING</>.
2992 The <literal>SCROLL</> and
2993 <literal>NO SCROLL</> options have the same meanings as for a bound
3000 OPEN curs1 FOR EXECUTE format('SELECT * FROM %I WHERE col1 = $1',tabname) USING keyvalue;
3002 In this example, the table name is inserted into the query via
3003 <function>format()</>. The comparison value for <literal>col1</>
3004 is inserted via a <literal>USING</> parameter, so it needs
3009 <sect3 id="plpgsql-open-bound-cursor">
3010 <title>Opening a Bound Cursor</title>
3013 OPEN <replaceable>bound_cursorvar</replaceable> <optional> ( <optional> <replaceable>argument_name</replaceable> := </optional> <replaceable>argument_value</replaceable> <optional>, ...</optional> ) </optional>;
3017 This form of <command>OPEN</command> is used to open a cursor
3018 variable whose query was bound to it when it was declared. The
3019 cursor cannot be open already. A list of actual argument value
3020 expressions must appear if and only if the cursor was declared to
3021 take arguments. These values will be substituted in the query.
3025 The query plan for a bound cursor is always considered cacheable;
3026 there is no equivalent of <command>EXECUTE</command> in this case.
3027 Notice that <literal>SCROLL</> and <literal>NO SCROLL</> cannot be
3028 specified in <command>OPEN</>, as the cursor's scrolling
3029 behavior was already determined.
3033 Argument values can be passed using either <firstterm>positional</firstterm>
3034 or <firstterm>named</firstterm> notation. In positional
3035 notation, all arguments are specified in order. In named notation,
3036 each argument's name is specified using <literal>:=</literal> to
3037 separate it from the argument expression. Similar to calling
3038 functions, described in <xref linkend="sql-syntax-calling-funcs">, it
3039 is also allowed to mix positional and named notation.
3043 Examples (these use the cursor declaration examples above):
3047 OPEN curs3(key := 42);
3052 Because variable substitution is done on a bound cursor's query,
3053 there are really two ways to pass values into the cursor: either
3054 with an explicit argument to <command>OPEN</>, or implicitly by
3055 referencing a <application>PL/pgSQL</> variable in the query.
3056 However, only variables declared before the bound cursor was
3057 declared will be substituted into it. In either case the value to
3058 be passed is determined at the time of the <command>OPEN</>.
3059 For example, another way to get the same effect as the
3060 <literal>curs3</> example above is
3064 curs4 CURSOR FOR SELECT * FROM tenk1 WHERE unique1 = key;
3073 <sect2 id="plpgsql-cursor-using">
3074 <title>Using Cursors</title>
3077 Once a cursor has been opened, it can be manipulated with the
3078 statements described here.
3082 These manipulations need not occur in the same function that
3083 opened the cursor to begin with. You can return a <type>refcursor</>
3084 value out of a function and let the caller operate on the cursor.
3085 (Internally, a <type>refcursor</> value is simply the string name
3086 of a so-called portal containing the active query for the cursor. This name
3087 can be passed around, assigned to other <type>refcursor</> variables,
3088 and so on, without disturbing the portal.)
3092 All portals are implicitly closed at transaction end. Therefore
3093 a <type>refcursor</> value is usable to reference an open cursor
3094 only until the end of the transaction.
3098 <title><literal>FETCH</></title>
3101 FETCH <optional> <replaceable>direction</replaceable> { FROM | IN } </optional> <replaceable>cursor</replaceable> INTO <replaceable>target</replaceable>;
3105 <command>FETCH</command> retrieves the next row from the
3106 cursor into a target, which might be a row variable, a record
3107 variable, or a comma-separated list of simple variables, just like
3108 <command>SELECT INTO</command>. If there is no next row, the
3109 target is set to NULL(s). As with <command>SELECT
3110 INTO</command>, the special variable <literal>FOUND</literal> can
3111 be checked to see whether a row was obtained or not.
3115 The <replaceable>direction</replaceable> clause can be any of the
3116 variants allowed in the SQL <xref linkend="sql-fetch">
3117 command except the ones that can fetch
3118 more than one row; namely, it can be
3123 <literal>ABSOLUTE</> <replaceable>count</replaceable>,
3124 <literal>RELATIVE</> <replaceable>count</replaceable>,
3125 <literal>FORWARD</>, or
3126 <literal>BACKWARD</>.
3127 Omitting <replaceable>direction</replaceable> is the same
3128 as specifying <literal>NEXT</>.
3129 <replaceable>direction</replaceable> values that require moving
3130 backward are likely to fail unless the cursor was declared or opened
3131 with the <literal>SCROLL</> option.
3135 <replaceable>cursor</replaceable> must be the name of a <type>refcursor</>
3136 variable that references an open cursor portal.
3142 FETCH curs1 INTO rowvar;
3143 FETCH curs2 INTO foo, bar, baz;
3144 FETCH LAST FROM curs3 INTO x, y;
3145 FETCH RELATIVE -2 FROM curs4 INTO x;
3151 <title><literal>MOVE</></title>
3154 MOVE <optional> <replaceable>direction</replaceable> { FROM | IN } </optional> <replaceable>cursor</replaceable>;
3158 <command>MOVE</command> repositions a cursor without retrieving
3159 any data. <command>MOVE</command> works exactly like the
3160 <command>FETCH</command> command, except it only repositions the
3161 cursor and does not return the row moved to. As with <command>SELECT
3162 INTO</command>, the special variable <literal>FOUND</literal> can
3163 be checked to see whether there was a next row to move to.
3167 The <replaceable>direction</replaceable> clause can be any of the
3168 variants allowed in the SQL <xref linkend="sql-fetch">
3174 <literal>ABSOLUTE</> <replaceable>count</replaceable>,
3175 <literal>RELATIVE</> <replaceable>count</replaceable>,
3177 <literal>FORWARD</> <optional> <replaceable>count</replaceable> | <literal>ALL</> </optional>, or
3178 <literal>BACKWARD</> <optional> <replaceable>count</replaceable> | <literal>ALL</> </optional>.
3179 Omitting <replaceable>direction</replaceable> is the same
3180 as specifying <literal>NEXT</>.
3181 <replaceable>direction</replaceable> values that require moving
3182 backward are likely to fail unless the cursor was declared or opened
3183 with the <literal>SCROLL</> option.
3190 MOVE LAST FROM curs3;
3191 MOVE RELATIVE -2 FROM curs4;
3192 MOVE FORWARD 2 FROM curs4;
3198 <title><literal>UPDATE/DELETE WHERE CURRENT OF</></title>
3201 UPDATE <replaceable>table</replaceable> SET ... WHERE CURRENT OF <replaceable>cursor</replaceable>;
3202 DELETE FROM <replaceable>table</replaceable> WHERE CURRENT OF <replaceable>cursor</replaceable>;
3206 When a cursor is positioned on a table row, that row can be updated
3207 or deleted using the cursor to identify the row. There are
3208 restrictions on what the cursor's query can be (in particular,
3209 no grouping) and it's best to use <literal>FOR UPDATE</> in the
3210 cursor. For more information see the
3211 <xref linkend="sql-declare">
3218 UPDATE foo SET dataval = myval WHERE CURRENT OF curs1;
3224 <title><literal>CLOSE</></title>
3227 CLOSE <replaceable>cursor</replaceable>;
3231 <command>CLOSE</command> closes the portal underlying an open
3232 cursor. This can be used to release resources earlier than end of
3233 transaction, or to free up the cursor variable to be opened again.
3245 <title>Returning Cursors</title>
3248 <application>PL/pgSQL</> functions can return cursors to the
3249 caller. This is useful to return multiple rows or columns,
3250 especially with very large result sets. To do this, the function
3251 opens the cursor and returns the cursor name to the caller (or simply
3252 opens the cursor using a portal name specified by or otherwise known
3253 to the caller). The caller can then fetch rows from the cursor. The
3254 cursor can be closed by the caller, or it will be closed automatically
3255 when the transaction closes.
3259 The portal name used for a cursor can be specified by the
3260 programmer or automatically generated. To specify a portal name,
3261 simply assign a string to the <type>refcursor</> variable before
3262 opening it. The string value of the <type>refcursor</> variable
3263 will be used by <command>OPEN</> as the name of the underlying portal.
3264 However, if the <type>refcursor</> variable is null,
3265 <command>OPEN</> automatically generates a name that does not
3266 conflict with any existing portal, and assigns it to the
3267 <type>refcursor</> variable.
3272 A bound cursor variable is initialized to the string value
3273 representing its name, so that the portal name is the same as
3274 the cursor variable name, unless the programmer overrides it
3275 by assignment before opening the cursor. But an unbound cursor
3276 variable defaults to the null value initially, so it will receive
3277 an automatically-generated unique name, unless overridden.
3282 The following example shows one way a cursor name can be supplied by
3286 CREATE TABLE test (col text);
3287 INSERT INTO test VALUES ('123');
3289 CREATE FUNCTION reffunc(refcursor) RETURNS refcursor AS '
3291 OPEN $1 FOR SELECT col FROM test;
3297 SELECT reffunc('funccursor');
3298 FETCH ALL IN funccursor;
3304 The following example uses automatic cursor name generation:
3307 CREATE FUNCTION reffunc2() RETURNS refcursor AS '
3311 OPEN ref FOR SELECT col FROM test;
3316 -- need to be in a transaction to use cursors.
3321 --------------------
3322 <unnamed cursor 1>
3325 FETCH ALL IN "<unnamed cursor 1>";
3331 The following example shows one way to return multiple cursors
3332 from a single function:
3335 CREATE FUNCTION myfunc(refcursor, refcursor) RETURNS SETOF refcursor AS $$
3337 OPEN $1 FOR SELECT * FROM table_1;
3339 OPEN $2 FOR SELECT * FROM table_2;
3342 $$ LANGUAGE plpgsql;
3344 -- need to be in a transaction to use cursors.
3347 SELECT * FROM myfunc('a', 'b');
3357 <sect2 id="plpgsql-cursor-for-loop">
3358 <title>Looping Through a Cursor's Result</title>
3361 There is a variant of the <command>FOR</> statement that allows
3362 iterating through the rows returned by a cursor. The syntax is:
3365 <optional> <<<replaceable>label</replaceable>>> </optional>
3366 FOR <replaceable>recordvar</replaceable> IN <replaceable>bound_cursorvar</replaceable> <optional> ( <optional> <replaceable>argument_name</replaceable> := </optional> <replaceable>argument_value</replaceable> <optional>, ...</optional> ) </optional> LOOP
3367 <replaceable>statements</replaceable>
3368 END LOOP <optional> <replaceable>label</replaceable> </optional>;
3371 The cursor variable must have been bound to some query when it was
3372 declared, and it <emphasis>cannot</> be open already. The
3373 <command>FOR</> statement automatically opens the cursor, and it closes
3374 the cursor again when the loop exits. A list of actual argument value
3375 expressions must appear if and only if the cursor was declared to take
3376 arguments. These values will be substituted in the query, in just
3377 the same way as during an <command>OPEN</> (see <xref
3378 linkend="plpgsql-open-bound-cursor">).
3382 The variable <replaceable>recordvar</replaceable> is automatically
3383 defined as type <type>record</> and exists only inside the loop (any
3384 existing definition of the variable name is ignored within the loop).
3385 Each row returned by the cursor is successively assigned to this
3386 record variable and the loop body is executed.
3392 <sect1 id="plpgsql-errors-and-messages">
3393 <title>Errors and Messages</title>
3395 <sect2 id="plpgsql-statements-raise">
3396 <title>Reporting Errors and Messages</title>
3399 <primary>RAISE</primary>
3400 <secondary>in PL/pgSQL</secondary>
3404 <primary>reporting errors</primary>
3405 <secondary>in PL/pgSQL</secondary>
3409 Use the <command>RAISE</command> statement to report messages and
3413 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>;
3414 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>;
3415 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>;
3416 RAISE <optional> <replaceable class="parameter">level</replaceable> </optional> USING <replaceable class="parameter">option</replaceable> = <replaceable class="parameter">expression</replaceable> <optional>, ... </optional>;
3420 The <replaceable class="parameter">level</replaceable> option specifies
3421 the error severity. Allowed levels are <literal>DEBUG</literal>,
3422 <literal>LOG</literal>, <literal>INFO</literal>,
3423 <literal>NOTICE</literal>, <literal>WARNING</literal>,
3424 and <literal>EXCEPTION</literal>, with <literal>EXCEPTION</literal>
3426 <literal>EXCEPTION</literal> raises an error (which normally aborts the
3427 current transaction); the other levels only generate messages of different
3429 Whether messages of a particular priority are reported to the client,
3430 written to the server log, or both is controlled by the
3431 <xref linkend="guc-log-min-messages"> and
3432 <xref linkend="guc-client-min-messages"> configuration
3433 variables. See <xref linkend="runtime-config"> for more
3438 After <replaceable class="parameter">level</replaceable> if any,
3439 you can write a <replaceable class="parameter">format</replaceable>
3440 (which must be a simple string literal, not an expression). The
3441 format string specifies the error message text to be reported.
3442 The format string can be followed
3443 by optional argument expressions to be inserted into the message.
3444 Inside the format string, <literal>%</literal> is replaced by the
3445 string representation of the next optional argument's value. Write
3446 <literal>%%</literal> to emit a literal <literal>%</literal>.
3447 The number of arguments must match the number of <literal>%</>
3448 placeholders in the format string, or an error is raised during
3449 the compilation of the function.
3453 In this example, the value of <literal>v_job_id</> will replace the
3454 <literal>%</literal> in the string:
3456 RAISE NOTICE 'Calling cs_create_job(%)', v_job_id;
3461 You can attach additional information to the error report by writing
3462 <literal>USING</> followed by <replaceable
3463 class="parameter">option</replaceable> = <replaceable
3464 class="parameter">expression</replaceable> items. Each
3465 <replaceable class="parameter">expression</replaceable> can be any
3466 string-valued expression. The allowed <replaceable
3467 class="parameter">option</replaceable> key words are:
3469 <variablelist id="raise-using-options">
3471 <term><literal>MESSAGE</literal></term>
3473 <para>Sets the error message text. This option can't be used in the
3474 form of <command>RAISE</> that includes a format string
3475 before <literal>USING</>.</para>
3480 <term><literal>DETAIL</literal></term>
3482 <para>Supplies an error detail message.</para>
3487 <term><literal>HINT</literal></term>
3489 <para>Supplies a hint message.</para>
3494 <term><literal>ERRCODE</literal></term>
3496 <para>Specifies the error code (SQLSTATE) to report, either by condition
3497 name, as shown in <xref linkend="errcodes-appendix">, or directly as a
3498 five-character SQLSTATE code.</para>
3503 <term><literal>COLUMN</literal></term>
3504 <term><literal>CONSTRAINT</literal></term>
3505 <term><literal>DATATYPE</literal></term>
3506 <term><literal>TABLE</literal></term>
3507 <term><literal>SCHEMA</literal></term>
3509 <para>Supplies the name of a related object.</para>
3516 This example will abort the transaction with the given error message
3519 RAISE EXCEPTION 'Nonexistent ID --> %', user_id
3520 USING HINT = 'Please check your user ID';
3525 These two examples show equivalent ways of setting the SQLSTATE:
3527 RAISE 'Duplicate user ID: %', user_id USING ERRCODE = 'unique_violation';
3528 RAISE 'Duplicate user ID: %', user_id USING ERRCODE = '23505';
3533 There is a second <command>RAISE</> syntax in which the main argument
3534 is the condition name or SQLSTATE to be reported, for example:
3536 RAISE division_by_zero;
3537 RAISE SQLSTATE '22012';
3539 In this syntax, <literal>USING</> can be used to supply a custom
3540 error message, detail, or hint. Another way to do the earlier
3543 RAISE unique_violation USING MESSAGE = 'Duplicate user ID: ' || user_id;
3548 Still another variant is to write <literal>RAISE USING</> or <literal>RAISE
3549 <replaceable class="parameter">level</replaceable> USING</> and put
3550 everything else into the <literal>USING</> list.
3554 The last variant of <command>RAISE</> has no parameters at all.
3555 This form can only be used inside a <literal>BEGIN</> block's
3556 <literal>EXCEPTION</> clause;
3557 it causes the error currently being handled to be re-thrown.
3562 Before <productname>PostgreSQL</> 9.1, <command>RAISE</> without
3563 parameters was interpreted as re-throwing the error from the block
3564 containing the active exception handler. Thus an <literal>EXCEPTION</>
3565 clause nested within that handler could not catch it, even if the
3566 <command>RAISE</> was within the nested <literal>EXCEPTION</> clause's
3567 block. This was deemed surprising as well as being incompatible with
3573 If no condition name nor SQLSTATE is specified in a
3574 <command>RAISE EXCEPTION</command> command, the default is to use
3575 <literal>RAISE_EXCEPTION</> (<literal>P0001</>). If no message
3576 text is specified, the default is to use the condition name or
3577 SQLSTATE as message text.
3582 When specifying an error code by SQLSTATE code, you are not
3583 limited to the predefined error codes, but can select any
3584 error code consisting of five digits and/or upper-case ASCII
3585 letters, other than <literal>00000</>. It is recommended that
3586 you avoid throwing error codes that end in three zeroes, because
3587 these are category codes and can only be trapped by trapping
3594 <sect2 id="plpgsql-statements-assert">
3595 <title>Checking Assertions</title>
3598 <primary>ASSERT</primary>
3599 <secondary>in PL/pgSQL</secondary>
3603 <primary>assertions</primary>
3604 <secondary>in PL/pgSQL</secondary>
3608 <primary><varname>plpgsql.check_asserts</> configuration parameter</primary>
3612 The <command>ASSERT</command> statement is a convenient shorthand for
3613 inserting debugging checks into <application>PL/pgSQL</application>
3617 ASSERT <replaceable class="parameter">condition</replaceable> <optional> , <replaceable class="parameter">message</replaceable> </optional>;
3620 The <replaceable class="parameter">condition</replaceable> is a Boolean
3621 expression that is expected to always evaluate to true; if it does,
3622 the <command>ASSERT</command> statement does nothing further. If the
3623 result is false or null, then an <literal>ASSERT_FAILURE</> exception
3624 is raised. (If an error occurs while evaluating
3625 the <replaceable class="parameter">condition</replaceable>, it is
3626 reported as a normal error.)
3630 If the optional <replaceable class="parameter">message</replaceable> is
3631 provided, it is an expression whose result (if not null) replaces the
3632 default error message text <quote>assertion failed</>, should
3633 the <replaceable class="parameter">condition</replaceable> fail.
3634 The <replaceable class="parameter">message</replaceable> expression is
3635 not evaluated in the normal case where the assertion succeeds.
3639 Testing of assertions can be enabled or disabled via the configuration
3640 parameter <literal>plpgsql.check_asserts</>, which takes a Boolean
3641 value; the default is <literal>on</>. If this parameter
3642 is <literal>off</> then <command>ASSERT</> statements do nothing.
3646 Note that <command>ASSERT</command> is meant for detecting program
3647 bugs, not for reporting ordinary error conditions. Use
3648 the <command>RAISE</> statement, described above, for that.
3655 <sect1 id="plpgsql-trigger">
3656 <title>Trigger Procedures</title>
3658 <indexterm zone="plpgsql-trigger">
3659 <primary>trigger</primary>
3660 <secondary>in PL/pgSQL</secondary>
3663 <sect2 id="plpgsql-dml-trigger">
3664 <title>Triggers on Data Changes</title>
3667 <application>PL/pgSQL</application> can be used to define trigger
3668 procedures. A trigger procedure is created with the
3669 <command>CREATE FUNCTION</> command, declaring it as a function with
3670 no arguments and a return type of <type>trigger</type>. Note that
3671 the function must be declared with no arguments even if it expects
3672 to receive arguments specified in <command>CREATE TRIGGER</> —
3673 trigger arguments are passed via <varname>TG_ARGV</>, as described
3678 When a <application>PL/pgSQL</application> function is called as a
3679 trigger, several special variables are created automatically in the
3680 top-level block. They are:
3684 <term><varname>NEW</varname></term>
3687 Data type <type>RECORD</type>; variable holding the new
3688 database row for <command>INSERT</>/<command>UPDATE</> operations in row-level
3689 triggers. This variable is unassigned in statement-level triggers
3690 and for <command>DELETE</command> operations.
3696 <term><varname>OLD</varname></term>
3699 Data type <type>RECORD</type>; variable holding the old
3700 database row for <command>UPDATE</>/<command>DELETE</> operations in row-level
3701 triggers. This variable is unassigned in statement-level triggers
3702 and for <command>INSERT</command> operations.
3708 <term><varname>TG_NAME</varname></term>
3711 Data type <type>name</type>; variable that contains the name of the trigger actually
3718 <term><varname>TG_WHEN</varname></term>
3721 Data type <type>text</type>; a string of
3722 <literal>BEFORE</literal>, <literal>AFTER</literal>, or
3723 <literal>INSTEAD OF</literal>, depending on the trigger's definition.
3729 <term><varname>TG_LEVEL</varname></term>
3732 Data type <type>text</type>; a string of either
3733 <literal>ROW</literal> or <literal>STATEMENT</literal>
3734 depending on the trigger's definition.
3740 <term><varname>TG_OP</varname></term>
3743 Data type <type>text</type>; a string of
3744 <literal>INSERT</literal>, <literal>UPDATE</literal>,
3745 <literal>DELETE</literal>, or <literal>TRUNCATE</>
3746 telling for which operation the trigger was fired.
3752 <term><varname>TG_RELID</varname></term>
3755 Data type <type>oid</type>; the object ID of the table that caused the
3762 <term><varname>TG_RELNAME</varname></term>
3765 Data type <type>name</type>; the name of the table that caused the trigger
3766 invocation. This is now deprecated, and could disappear in a future
3767 release. Use <literal>TG_TABLE_NAME</> instead.
3773 <term><varname>TG_TABLE_NAME</varname></term>
3776 Data type <type>name</type>; the name of the table that
3777 caused the trigger invocation.
3783 <term><varname>TG_TABLE_SCHEMA</varname></term>
3786 Data type <type>name</type>; the name of the schema of the
3787 table that caused the trigger invocation.
3793 <term><varname>TG_NARGS</varname></term>
3796 Data type <type>integer</type>; the number of arguments given to the trigger
3797 procedure in the <command>CREATE TRIGGER</command> statement.
3803 <term><varname>TG_ARGV[]</varname></term>
3806 Data type array of <type>text</type>; the arguments from
3807 the <command>CREATE TRIGGER</command> statement.
3808 The index counts from 0. Invalid
3809 indexes (less than 0 or greater than or equal to <varname>tg_nargs</>)
3810 result in a null value.
3818 A trigger function must return either <symbol>NULL</symbol> or a
3819 record/row value having exactly the structure of the table the
3820 trigger was fired for.
3824 Row-level triggers fired <literal>BEFORE</> can return null to signal the
3825 trigger manager to skip the rest of the operation for this row
3826 (i.e., subsequent triggers are not fired, and the
3827 <command>INSERT</>/<command>UPDATE</>/<command>DELETE</> does not occur
3828 for this row). If a nonnull
3829 value is returned then the operation proceeds with that row value.
3830 Returning a row value different from the original value
3831 of <varname>NEW</> alters the row that will be inserted or
3832 updated. Thus, if the trigger function wants the triggering
3833 action to succeed normally without altering the row
3834 value, <varname>NEW</varname> (or a value equal thereto) has to be
3835 returned. To alter the row to be stored, it is possible to
3836 replace single values directly in <varname>NEW</> and return the
3837 modified <varname>NEW</>, or to build a complete new record/row to
3838 return. In the case of a before-trigger
3839 on <command>DELETE</command>, the returned value has no direct
3840 effect, but it has to be nonnull to allow the trigger action to
3841 proceed. Note that <varname>NEW</varname> is null
3842 in <command>DELETE</command> triggers, so returning that is
3843 usually not sensible. The usual idiom in <command>DELETE</command>
3844 triggers is to return <varname>OLD</varname>.
3848 <literal>INSTEAD OF</> triggers (which are always row-level triggers,
3849 and may only be used on views) can return null to signal that they did
3850 not perform any updates, and that the rest of the operation for this
3851 row should be skipped (i.e., subsequent triggers are not fired, and the
3852 row is not counted in the rows-affected status for the surrounding
3853 <command>INSERT</>/<command>UPDATE</>/<command>DELETE</>).
3854 Otherwise a nonnull value should be returned, to signal
3855 that the trigger performed the requested operation. For
3856 <command>INSERT</> and <command>UPDATE</> operations, the return value
3857 should be <varname>NEW</>, which the trigger function may modify to
3858 support <command>INSERT RETURNING</> and <command>UPDATE RETURNING</>
3859 (this will also affect the row value passed to any subsequent triggers,
3860 or passed to a special <varname>EXCLUDED</> alias reference within
3861 an <command>INSERT</> statement with an <literal>ON CONFLICT DO
3862 UPDATE</> clause). For <command>DELETE</> operations, the return
3863 value should be <varname>OLD</>.
3867 The return value of a row-level trigger
3868 fired <literal>AFTER</literal> or a statement-level trigger
3869 fired <literal>BEFORE</> or <literal>AFTER</> is
3870 always ignored; it might as well be null. However, any of these types of
3871 triggers might still abort the entire operation by raising an error.
3875 <xref linkend="plpgsql-trigger-example"> shows an example of a
3876 trigger procedure in <application>PL/pgSQL</application>.
3879 <example id="plpgsql-trigger-example">
3880 <title>A <application>PL/pgSQL</application> Trigger Procedure</title>
3883 This example trigger ensures that any time a row is inserted or updated
3884 in the table, the current user name and time are stamped into the
3885 row. And it checks that an employee's name is given and that the
3886 salary is a positive value.
3893 last_date timestamp,
3897 CREATE FUNCTION emp_stamp() RETURNS trigger AS $emp_stamp$
3899 -- Check that empname and salary are given
3900 IF NEW.empname IS NULL THEN
3901 RAISE EXCEPTION 'empname cannot be null';
3903 IF NEW.salary IS NULL THEN
3904 RAISE EXCEPTION '% cannot have null salary', NEW.empname;
3907 -- Who works for us when they must pay for it?
3908 IF NEW.salary < 0 THEN
3909 RAISE EXCEPTION '% cannot have a negative salary', NEW.empname;
3912 -- Remember who changed the payroll when
3913 NEW.last_date := current_timestamp;
3914 NEW.last_user := current_user;
3917 $emp_stamp$ LANGUAGE plpgsql;
3919 CREATE TRIGGER emp_stamp BEFORE INSERT OR UPDATE ON emp
3920 FOR EACH ROW EXECUTE PROCEDURE emp_stamp();
3925 Another way to log changes to a table involves creating a new table that
3926 holds a row for each insert, update, or delete that occurs. This approach
3927 can be thought of as auditing changes to a table.
3928 <xref linkend="plpgsql-trigger-audit-example"> shows an example of an
3929 audit trigger procedure in <application>PL/pgSQL</application>.
3932 <example id="plpgsql-trigger-audit-example">
3933 <title>A <application>PL/pgSQL</application> Trigger Procedure For Auditing</title>
3936 This example trigger ensures that any insert, update or delete of a row
3937 in the <literal>emp</literal> table is recorded (i.e., audited) in the <literal>emp_audit</literal> table.
3938 The current time and user name are stamped into the row, together with
3939 the type of operation performed on it.
3944 empname text NOT NULL,
3948 CREATE TABLE emp_audit(
3949 operation char(1) NOT NULL,
3950 stamp timestamp NOT NULL,
3951 userid text NOT NULL,
3952 empname text NOT NULL,
3956 CREATE OR REPLACE FUNCTION process_emp_audit() RETURNS TRIGGER AS $emp_audit$
3959 -- Create a row in emp_audit to reflect the operation performed on emp,
3960 -- make use of the special variable TG_OP to work out the operation.
3962 IF (TG_OP = 'DELETE') THEN
3963 INSERT INTO emp_audit SELECT 'D', now(), user, OLD.*;
3965 ELSIF (TG_OP = 'UPDATE') THEN
3966 INSERT INTO emp_audit SELECT 'U', now(), user, NEW.*;
3968 ELSIF (TG_OP = 'INSERT') THEN
3969 INSERT INTO emp_audit SELECT 'I', now(), user, NEW.*;
3972 RETURN NULL; -- result is ignored since this is an AFTER trigger
3974 $emp_audit$ LANGUAGE plpgsql;
3976 CREATE TRIGGER emp_audit
3977 AFTER INSERT OR UPDATE OR DELETE ON emp
3978 FOR EACH ROW EXECUTE PROCEDURE process_emp_audit();
3983 A variation of the previous example uses a view joining the main table
3984 to the audit table, to show when each entry was last modified. This
3985 approach still records the full audit trail of changes to the table,
3986 but also presents a simplified view of the audit trail, showing just
3987 the last modified timestamp derived from the audit trail for each entry.
3988 <xref linkend="plpgsql-view-trigger-audit-example"> shows an example
3989 of an audit trigger on a view in <application>PL/pgSQL</application>.
3992 <example id="plpgsql-view-trigger-audit-example">
3993 <title>A <application>PL/pgSQL</application> View Trigger Procedure For Auditing</title>
3996 This example uses a trigger on the view to make it updatable, and
3997 ensure that any insert, update or delete of a row in the view is
3998 recorded (i.e., audited) in the <literal>emp_audit</literal> table. The current time
3999 and user name are recorded, together with the type of operation
4000 performed, and the view displays the last modified time of each row.
4005 empname text PRIMARY KEY,
4009 CREATE TABLE emp_audit(
4010 operation char(1) NOT NULL,
4011 userid text NOT NULL,
4012 empname text NOT NULL,
4014 stamp timestamp NOT NULL
4017 CREATE VIEW emp_view AS
4020 max(ea.stamp) AS last_updated
4022 LEFT JOIN emp_audit ea ON ea.empname = e.empname
4025 CREATE OR REPLACE FUNCTION update_emp_view() RETURNS TRIGGER AS $$
4028 -- Perform the required operation on emp, and create a row in emp_audit
4029 -- to reflect the change made to emp.
4031 IF (TG_OP = 'DELETE') THEN
4032 DELETE FROM emp WHERE empname = OLD.empname;
4033 IF NOT FOUND THEN RETURN NULL; END IF;
4035 OLD.last_updated = now();
4036 INSERT INTO emp_audit VALUES('D', user, OLD.*);
4038 ELSIF (TG_OP = 'UPDATE') THEN
4039 UPDATE emp SET salary = NEW.salary WHERE empname = OLD.empname;
4040 IF NOT FOUND THEN RETURN NULL; END IF;
4042 NEW.last_updated = now();
4043 INSERT INTO emp_audit VALUES('U', user, NEW.*);
4045 ELSIF (TG_OP = 'INSERT') THEN
4046 INSERT INTO emp VALUES(NEW.empname, NEW.salary);
4048 NEW.last_updated = now();
4049 INSERT INTO emp_audit VALUES('I', user, NEW.*);
4053 $$ LANGUAGE plpgsql;
4055 CREATE TRIGGER emp_audit
4056 INSTEAD OF INSERT OR UPDATE OR DELETE ON emp_view
4057 FOR EACH ROW EXECUTE PROCEDURE update_emp_view();
4062 One use of triggers is to maintain a summary table
4063 of another table. The resulting summary can be used in place of the
4064 original table for certain queries — often with vastly reduced run
4066 This technique is commonly used in Data Warehousing, where the tables
4067 of measured or observed data (called fact tables) might be extremely large.
4068 <xref linkend="plpgsql-trigger-summary-example"> shows an example of a
4069 trigger procedure in <application>PL/pgSQL</application> that maintains
4070 a summary table for a fact table in a data warehouse.
4074 <example id="plpgsql-trigger-summary-example">
4075 <title>A <application>PL/pgSQL</application> Trigger Procedure For Maintaining A Summary Table</title>
4078 The schema detailed here is partly based on the <emphasis>Grocery Store
4079 </emphasis> example from <emphasis>The Data Warehouse Toolkit</emphasis>
4085 -- Main tables - time dimension and sales fact.
4087 CREATE TABLE time_dimension (
4088 time_key integer NOT NULL,
4089 day_of_week integer NOT NULL,
4090 day_of_month integer NOT NULL,
4091 month integer NOT NULL,
4092 quarter integer NOT NULL,
4093 year integer NOT NULL
4095 CREATE UNIQUE INDEX time_dimension_key ON time_dimension(time_key);
4097 CREATE TABLE sales_fact (
4098 time_key integer NOT NULL,
4099 product_key integer NOT NULL,
4100 store_key integer NOT NULL,
4101 amount_sold numeric(12,2) NOT NULL,
4102 units_sold integer NOT NULL,
4103 amount_cost numeric(12,2) NOT NULL
4105 CREATE INDEX sales_fact_time ON sales_fact(time_key);
4108 -- Summary table - sales by time.
4110 CREATE TABLE sales_summary_bytime (
4111 time_key integer NOT NULL,
4112 amount_sold numeric(15,2) NOT NULL,
4113 units_sold numeric(12) NOT NULL,
4114 amount_cost numeric(15,2) NOT NULL
4116 CREATE UNIQUE INDEX sales_summary_bytime_key ON sales_summary_bytime(time_key);
4119 -- Function and trigger to amend summarized column(s) on UPDATE, INSERT, DELETE.
4121 CREATE OR REPLACE FUNCTION maint_sales_summary_bytime() RETURNS TRIGGER
4122 AS $maint_sales_summary_bytime$
4124 delta_time_key integer;
4125 delta_amount_sold numeric(15,2);
4126 delta_units_sold numeric(12);
4127 delta_amount_cost numeric(15,2);
4130 -- Work out the increment/decrement amount(s).
4131 IF (TG_OP = 'DELETE') THEN
4133 delta_time_key = OLD.time_key;
4134 delta_amount_sold = -1 * OLD.amount_sold;
4135 delta_units_sold = -1 * OLD.units_sold;
4136 delta_amount_cost = -1 * OLD.amount_cost;
4138 ELSIF (TG_OP = 'UPDATE') THEN
4140 -- forbid updates that change the time_key -
4141 -- (probably not too onerous, as DELETE + INSERT is how most
4142 -- changes will be made).
4143 IF ( OLD.time_key != NEW.time_key) THEN
4144 RAISE EXCEPTION 'Update of time_key : % -> % not allowed',
4145 OLD.time_key, NEW.time_key;
4148 delta_time_key = OLD.time_key;
4149 delta_amount_sold = NEW.amount_sold - OLD.amount_sold;
4150 delta_units_sold = NEW.units_sold - OLD.units_sold;
4151 delta_amount_cost = NEW.amount_cost - OLD.amount_cost;
4153 ELSIF (TG_OP = 'INSERT') THEN
4155 delta_time_key = NEW.time_key;
4156 delta_amount_sold = NEW.amount_sold;
4157 delta_units_sold = NEW.units_sold;
4158 delta_amount_cost = NEW.amount_cost;
4163 -- Insert or update the summary row with the new values.
4164 <<insert_update>>
4166 UPDATE sales_summary_bytime
4167 SET amount_sold = amount_sold + delta_amount_sold,
4168 units_sold = units_sold + delta_units_sold,
4169 amount_cost = amount_cost + delta_amount_cost
4170 WHERE time_key = delta_time_key;
4172 EXIT insert_update WHEN found;
4175 INSERT INTO sales_summary_bytime (
4190 WHEN UNIQUE_VIOLATION THEN
4193 END LOOP insert_update;
4198 $maint_sales_summary_bytime$ LANGUAGE plpgsql;
4200 CREATE TRIGGER maint_sales_summary_bytime
4201 AFTER INSERT OR UPDATE OR DELETE ON sales_fact
4202 FOR EACH ROW EXECUTE PROCEDURE maint_sales_summary_bytime();
4204 INSERT INTO sales_fact VALUES(1,1,1,10,3,15);
4205 INSERT INTO sales_fact VALUES(1,2,1,20,5,35);
4206 INSERT INTO sales_fact VALUES(2,2,1,40,15,135);
4207 INSERT INTO sales_fact VALUES(2,3,1,10,1,13);
4208 SELECT * FROM sales_summary_bytime;
4209 DELETE FROM sales_fact WHERE product_key = 1;
4210 SELECT * FROM sales_summary_bytime;
4211 UPDATE sales_fact SET units_sold = units_sold * 2;
4212 SELECT * FROM sales_summary_bytime;
4217 <sect2 id="plpgsql-event-trigger">
4218 <title>Triggers on Events</title>
4221 <application>PL/pgSQL</application> can be used to define event
4222 triggers. <productname>PostgreSQL</> requires that a procedure that
4223 is to be called as an event trigger must be declared as a function with
4224 no arguments and a return type of <literal>event_trigger</>.
4228 When a <application>PL/pgSQL</application> function is called as a
4229 event trigger, several special variables are created automatically
4230 in the top-level block. They are:
4234 <term><varname>TG_EVENT</varname></term>
4237 Data type <type>text</type>; a string representing the event the
4238 trigger is fired for.
4244 <term><varname>TG_TAG</varname></term>
4247 Data type <type>text</type>; variable that contains the command tag
4248 for which the trigger is fired.
4256 <xref linkend="plpgsql-event-trigger-example"> shows an example of a
4257 event trigger procedure in <application>PL/pgSQL</application>.
4260 <example id="plpgsql-event-trigger-example">
4261 <title>A <application>PL/pgSQL</application> Event Trigger Procedure</title>
4264 This example trigger simply raises a <literal>NOTICE</literal> message
4265 each time a supported command is executed.
4269 CREATE OR REPLACE FUNCTION snitch() RETURNS event_trigger AS $$
4271 RAISE NOTICE 'snitch: % %', tg_event, tg_tag;
4273 $$ LANGUAGE plpgsql;
4275 CREATE EVENT TRIGGER snitch ON ddl_command_start EXECUTE PROCEDURE snitch();
4282 <sect1 id="plpgsql-implementation">
4283 <title><application>PL/pgSQL</> Under the Hood</title>
4286 This section discusses some implementation details that are
4287 frequently important for <application>PL/pgSQL</> users to know.
4290 <sect2 id="plpgsql-var-subst">
4291 <title>Variable Substitution</title>
4294 SQL statements and expressions within a <application>PL/pgSQL</> function
4295 can refer to variables and parameters of the function. Behind the scenes,
4296 <application>PL/pgSQL</> substitutes query parameters for such references.
4297 Parameters will only be substituted in places where a parameter or
4298 column reference is syntactically allowed. As an extreme case, consider
4299 this example of poor programming style:
4301 INSERT INTO foo (foo) VALUES (foo);
4303 The first occurrence of <literal>foo</> must syntactically be a table
4304 name, so it will not be substituted, even if the function has a variable
4305 named <literal>foo</>. The second occurrence must be the name of a
4306 column of the table, so it will not be substituted either. Only the
4307 third occurrence is a candidate to be a reference to the function's
4313 <productname>PostgreSQL</productname> versions before 9.0 would try
4314 to substitute the variable in all three cases, leading to syntax errors.
4319 Since the names of variables are syntactically no different from the names
4320 of table columns, there can be ambiguity in statements that also refer to
4321 tables: is a given name meant to refer to a table column, or a variable?
4322 Let's change the previous example to
4324 INSERT INTO dest (col) SELECT foo + bar FROM src;
4326 Here, <literal>dest</> and <literal>src</> must be table names, and
4327 <literal>col</> must be a column of <literal>dest</>, but <literal>foo</>
4328 and <literal>bar</> might reasonably be either variables of the function
4329 or columns of <literal>src</>.
4333 By default, <application>PL/pgSQL</> will report an error if a name
4334 in a SQL statement could refer to either a variable or a table column.
4335 You can fix such a problem by renaming the variable or column,
4336 or by qualifying the ambiguous reference, or by telling
4337 <application>PL/pgSQL</> which interpretation to prefer.
4341 The simplest solution is to rename the variable or column.
4342 A common coding rule is to use a
4343 different naming convention for <application>PL/pgSQL</application>
4344 variables than you use for column names. For example,
4345 if you consistently name function variables
4346 <literal>v_<replaceable>something</></literal> while none of your
4347 column names start with <literal>v_</>, no conflicts will occur.
4351 Alternatively you can qualify ambiguous references to make them clear.
4352 In the above example, <literal>src.foo</> would be an unambiguous reference
4353 to the table column. To create an unambiguous reference to a variable,
4354 declare it in a labeled block and use the block's label
4355 (see <xref linkend="plpgsql-structure">). For example,
4357 <<block>>
4362 INSERT INTO dest (col) SELECT block.foo + bar FROM src;
4364 Here <literal>block.foo</> means the variable even if there is a column
4365 <literal>foo</> in <literal>src</>. Function parameters, as well as
4366 special variables such as <literal>FOUND</>, can be qualified by the
4367 function's name, because they are implicitly declared in an outer block
4368 labeled with the function's name.
4372 Sometimes it is impractical to fix all the ambiguous references in a
4373 large body of <application>PL/pgSQL</> code. In such cases you can
4374 specify that <application>PL/pgSQL</> should resolve ambiguous references
4375 as the variable (which is compatible with <application>PL/pgSQL</>'s
4376 behavior before <productname>PostgreSQL</productname> 9.0), or as the
4377 table column (which is compatible with some other systems such as
4378 <productname>Oracle</productname>).
4382 <primary><varname>plpgsql.variable_conflict</> configuration parameter</primary>
4386 To change this behavior on a system-wide basis, set the configuration
4387 parameter <literal>plpgsql.variable_conflict</> to one of
4388 <literal>error</>, <literal>use_variable</>, or
4389 <literal>use_column</> (where <literal>error</> is the factory default).
4390 This parameter affects subsequent compilations
4391 of statements in <application>PL/pgSQL</> functions, but not statements
4392 already compiled in the current session.
4393 Because changing this setting
4394 can cause unexpected changes in the behavior of <application>PL/pgSQL</>
4395 functions, it can only be changed by a superuser.
4399 You can also set the behavior on a function-by-function basis, by
4400 inserting one of these special commands at the start of the function
4403 #variable_conflict error
4404 #variable_conflict use_variable
4405 #variable_conflict use_column
4407 These commands affect only the function they are written in, and override
4408 the setting of <literal>plpgsql.variable_conflict</>. An example is
4410 CREATE FUNCTION stamp_user(id int, comment text) RETURNS void AS $$
4411 #variable_conflict use_variable
4413 curtime timestamp := now();
4415 UPDATE users SET last_modified = curtime, comment = comment
4416 WHERE users.id = id;
4418 $$ LANGUAGE plpgsql;
4420 In the <literal>UPDATE</> command, <literal>curtime</>, <literal>comment</>,
4421 and <literal>id</> will refer to the function's variable and parameters
4422 whether or not <literal>users</> has columns of those names. Notice
4423 that we had to qualify the reference to <literal>users.id</> in the
4424 <literal>WHERE</> clause to make it refer to the table column.
4425 But we did not have to qualify the reference to <literal>comment</>
4426 as a target in the <literal>UPDATE</> list, because syntactically
4427 that must be a column of <literal>users</>. We could write the same
4428 function without depending on the <literal>variable_conflict</> setting
4431 CREATE FUNCTION stamp_user(id int, comment text) RETURNS void AS $$
4434 curtime timestamp := now();
4436 UPDATE users SET last_modified = fn.curtime, comment = stamp_user.comment
4437 WHERE users.id = stamp_user.id;
4439 $$ LANGUAGE plpgsql;
4444 Variable substitution does not happen in the command string given
4445 to <command>EXECUTE</> or one of its variants. If you need to
4446 insert a varying value into such a command, do so as part of
4447 constructing the string value, or use <literal>USING</>, as illustrated in
4448 <xref linkend="plpgsql-statements-executing-dyn">.
4452 Variable substitution currently works only in <command>SELECT</>,
4453 <command>INSERT</>, <command>UPDATE</>, and <command>DELETE</> commands,
4454 because the main SQL engine allows query parameters only in these
4455 commands. To use a non-constant name or value in other statement
4456 types (generically called utility statements), you must construct
4457 the utility statement as a string and <command>EXECUTE</> it.
4462 <sect2 id="plpgsql-plan-caching">
4463 <title>Plan Caching</title>
4466 The <application>PL/pgSQL</> interpreter parses the function's source
4467 text and produces an internal binary instruction tree the first time the
4468 function is called (within each session). The instruction tree
4469 fully translates the
4470 <application>PL/pgSQL</> statement structure, but individual
4471 <acronym>SQL</acronym> expressions and <acronym>SQL</acronym> commands
4472 used in the function are not translated immediately.
4477 <primary>preparing a query</>
4478 <secondary>in PL/pgSQL</>
4480 As each expression and <acronym>SQL</acronym> command is first
4481 executed in the function, the <application>PL/pgSQL</> interpreter
4482 parses and analyzes the command to create a prepared statement,
4483 using the <acronym>SPI</acronym> manager's
4484 <function>SPI_prepare</function> function.
4485 Subsequent visits to that expression or command
4486 reuse the prepared statement. Thus, a function with conditional code
4487 paths that are seldom visited will never incur the overhead of
4488 analyzing those commands that are never executed within the current
4489 session. A disadvantage is that errors
4490 in a specific expression or command cannot be detected until that
4491 part of the function is reached in execution. (Trivial syntax
4492 errors will be detected during the initial parsing pass, but
4493 anything deeper will not be detected until execution.)
4497 <application>PL/pgSQL</> (or more precisely, the SPI manager) can
4498 furthermore attempt to cache the execution plan associated with any
4499 particular prepared statement. If a cached plan is not used, then
4500 a fresh execution plan is generated on each visit to the statement,
4501 and the current parameter values (that is, <application>PL/pgSQL</>
4502 variable values) can be used to optimize the selected plan. If the
4503 statement has no parameters, or is executed many times, the SPI manager
4504 will consider creating a <firstterm>generic</> plan that is not dependent
4505 on specific parameter values, and caching that for re-use. Typically
4506 this will happen only if the execution plan is not very sensitive to
4507 the values of the <application>PL/pgSQL</> variables referenced in it.
4508 If it is, generating a plan each time is a net win. See <xref
4509 linkend="sql-prepare"> for more information about the behavior of
4510 prepared statements.
4514 Because <application>PL/pgSQL</application> saves prepared statements
4515 and sometimes execution plans in this way,
4516 SQL commands that appear directly in a
4517 <application>PL/pgSQL</application> function must refer to the
4518 same tables and columns on every execution; that is, you cannot use
4519 a parameter as the name of a table or column in an SQL command. To get
4520 around this restriction, you can construct dynamic commands using
4521 the <application>PL/pgSQL</application> <command>EXECUTE</command>
4522 statement — at the price of performing new parse analysis and
4523 constructing a new execution plan on every execution.
4527 The mutable nature of record variables presents another problem in this
4528 connection. When fields of a record variable are used in
4529 expressions or statements, the data types of the fields must not
4530 change from one call of the function to the next, since each
4531 expression will be analyzed using the data type that is present
4532 when the expression is first reached. <command>EXECUTE</command> can be
4533 used to get around this problem when necessary.
4537 If the same function is used as a trigger for more than one table,
4538 <application>PL/pgSQL</application> prepares and caches statements
4539 independently for each such table — that is, there is a cache
4540 for each trigger function and table combination, not just for each
4541 function. This alleviates some of the problems with varying
4542 data types; for instance, a trigger function will be able to work
4543 successfully with a column named <literal>key</> even if it happens
4544 to have different types in different tables.
4548 Likewise, functions having polymorphic argument types have a separate
4549 statement cache for each combination of actual argument types they have
4550 been invoked for, so that data type differences do not cause unexpected
4555 Statement caching can sometimes have surprising effects on the
4556 interpretation of time-sensitive values. For example there
4557 is a difference between what these two functions do:
4560 CREATE FUNCTION logfunc1(logtxt text) RETURNS void AS $$
4562 INSERT INTO logtable VALUES (logtxt, 'now');
4564 $$ LANGUAGE plpgsql;
4570 CREATE FUNCTION logfunc2(logtxt text) RETURNS void AS $$
4575 INSERT INTO logtable VALUES (logtxt, curtime);
4577 $$ LANGUAGE plpgsql;
4582 In the case of <function>logfunc1</function>, the
4583 <productname>PostgreSQL</productname> main parser knows when
4584 analyzing the <command>INSERT</command> that the
4585 string <literal>'now'</literal> should be interpreted as
4586 <type>timestamp</type>, because the target column of
4587 <classname>logtable</classname> is of that type. Thus,
4588 <literal>'now'</literal> will be converted to a <type>timestamp</type>
4590 <command>INSERT</command> is analyzed, and then used in all
4591 invocations of <function>logfunc1</function> during the lifetime
4592 of the session. Needless to say, this isn't what the programmer
4593 wanted. A better idea is to use the <literal>now()</> or
4594 <literal>current_timestamp</> function.
4598 In the case of <function>logfunc2</function>, the
4599 <productname>PostgreSQL</productname> main parser does not know
4600 what type <literal>'now'</literal> should become and therefore
4601 it returns a data value of type <type>text</type> containing the string
4602 <literal>now</literal>. During the ensuing assignment
4603 to the local variable <varname>curtime</varname>, the
4604 <application>PL/pgSQL</application> interpreter casts this
4605 string to the <type>timestamp</type> type by calling the
4606 <function>text_out</function> and <function>timestamp_in</function>
4607 functions for the conversion. So, the computed time stamp is updated
4608 on each execution as the programmer expects. Even though this
4609 happens to work as expected, it's not terribly efficient, so
4610 use of the <literal>now()</> function would still be a better idea.
4617 <sect1 id="plpgsql-development-tips">
4618 <title>Tips for Developing in <application>PL/pgSQL</application></title>
4621 One good way to develop in
4622 <application>PL/pgSQL</> is to use the text editor of your
4623 choice to create your functions, and in another window, use
4624 <application>psql</application> to load and test those functions.
4625 If you are doing it this way, it
4626 is a good idea to write the function using <command>CREATE OR
4627 REPLACE FUNCTION</>. That way you can just reload the file to update
4628 the function definition. For example:
4630 CREATE OR REPLACE FUNCTION testfunc(integer) RETURNS integer AS $$
4632 $$ LANGUAGE plpgsql;
4637 While running <application>psql</application>, you can load or reload such
4638 a function definition file with:
4642 and then immediately issue SQL commands to test the function.
4646 Another good way to develop in <application>PL/pgSQL</> is with a
4647 GUI database access tool that facilitates development in a
4648 procedural language. One example of such a tool is
4649 <application>pgAdmin</>, although others exist. These tools often
4650 provide convenient features such as escaping single quotes and
4651 making it easier to recreate and debug functions.
4654 <sect2 id="plpgsql-quote-tips">
4655 <title>Handling of Quotation Marks</title>
4658 The code of a <application>PL/pgSQL</> function is specified in
4659 <command>CREATE FUNCTION</command> as a string literal. If you
4660 write the string literal in the ordinary way with surrounding
4661 single quotes, then any single quotes inside the function body
4662 must be doubled; likewise any backslashes must be doubled (assuming
4663 escape string syntax is used).
4664 Doubling quotes is at best tedious, and in more complicated cases
4665 the code can become downright incomprehensible, because you can
4666 easily find yourself needing half a dozen or more adjacent quote marks.
4667 It's recommended that you instead write the function body as a
4668 <quote>dollar-quoted</> string literal (see <xref
4669 linkend="sql-syntax-dollar-quoting">). In the dollar-quoting
4670 approach, you never double any quote marks, but instead take care to
4671 choose a different dollar-quoting delimiter for each level of
4672 nesting you need. For example, you might write the <command>CREATE
4673 FUNCTION</command> command as:
4675 CREATE OR REPLACE FUNCTION testfunc(integer) RETURNS integer AS $PROC$
4677 $PROC$ LANGUAGE plpgsql;
4679 Within this, you might use quote marks for simple literal strings in
4680 SQL commands and <literal>$$</> to delimit fragments of SQL commands
4681 that you are assembling as strings. If you need to quote text that
4682 includes <literal>$$</>, you could use <literal>$Q$</>, and so on.
4686 The following chart shows what you have to do when writing quote
4687 marks without dollar quoting. It might be useful when translating
4688 pre-dollar quoting code into something more comprehensible.
4693 <term>1 quotation mark</term>
4696 To begin and end the function body, for example:
4698 CREATE FUNCTION foo() RETURNS integer AS '
4702 Anywhere within a single-quoted function body, quote marks
4703 <emphasis>must</> appear in pairs.
4709 <term>2 quotation marks</term>
4712 For string literals inside the function body, for example:
4714 a_output := ''Blah'';
4715 SELECT * FROM users WHERE f_name=''foobar'';
4717 In the dollar-quoting approach, you'd just write:
4720 SELECT * FROM users WHERE f_name='foobar';
4722 which is exactly what the <application>PL/pgSQL</> parser would see
4729 <term>4 quotation marks</term>
4732 When you need a single quotation mark in a string constant inside the
4733 function body, for example:
4735 a_output := a_output || '' AND name LIKE ''''foobar'''' AND xyz''
4737 The value actually appended to <literal>a_output</literal> would be:
4738 <literal> AND name LIKE 'foobar' AND xyz</literal>.
4741 In the dollar-quoting approach, you'd write:
4743 a_output := a_output || $$ AND name LIKE 'foobar' AND xyz$$
4745 being careful that any dollar-quote delimiters around this are not
4746 just <literal>$$</>.
4752 <term>6 quotation marks</term>
4755 When a single quotation mark in a string inside the function body is
4756 adjacent to the end of that string constant, for example:
4758 a_output := a_output || '' AND name LIKE ''''foobar''''''
4760 The value appended to <literal>a_output</literal> would then be:
4761 <literal> AND name LIKE 'foobar'</literal>.
4764 In the dollar-quoting approach, this becomes:
4766 a_output := a_output || $$ AND name LIKE 'foobar'$$
4773 <term>10 quotation marks</term>
4776 When you want two single quotation marks in a string constant (which
4777 accounts for 8 quotation marks) and this is adjacent to the end of that
4778 string constant (2 more). You will probably only need that if
4779 you are writing a function that generates other functions, as in
4780 <xref linkend="plpgsql-porting-ex2">.
4783 a_output := a_output || '' if v_'' ||
4784 referrer_keys.kind || '' like ''''''''''
4785 || referrer_keys.key_string || ''''''''''
4786 then return '''''' || referrer_keys.referrer_type
4787 || ''''''; end if;'';
4789 The value of <literal>a_output</literal> would then be:
4791 if v_... like ''...'' then return ''...''; end if;
4795 In the dollar-quoting approach, this becomes:
4797 a_output := a_output || $$ if v_$$ || referrer_keys.kind || $$ like '$$
4798 || referrer_keys.key_string || $$'
4799 then return '$$ || referrer_keys.referrer_type
4802 where we assume we only need to put single quote marks into
4803 <literal>a_output</literal>, because it will be re-quoted before use.
4810 <sect2 id="plpgsql-extra-checks">
4811 <title>Additional Compile-time Checks</title>
4814 To aid the user in finding instances of simple but common problems before
4815 they cause harm, <application>PL/PgSQL</> provides additional
4816 <replaceable>checks</>. When enabled, depending on the configuration, they
4817 can be used to emit either a <literal>WARNING</> or an <literal>ERROR</>
4818 during the compilation of a function. A function which has received
4819 a <literal>WARNING</> can be executed without producing further messages,
4820 so you are advised to test in a separate development environment.
4824 These additional checks are enabled through the configuration variables
4825 <varname>plpgsql.extra_warnings</> for warnings and
4826 <varname>plpgsql.extra_errors</> for errors. Both can be set either to
4827 a comma-separated list of checks, <literal>"none"</> or <literal>"all"</>.
4828 The default is <literal>"none"</>. Currently the list of available checks
4832 <term><varname>shadowed_variables</varname></term>
4835 Checks if a declaration shadows a previously defined variable.
4841 The following example shows the effect of <varname>plpgsql.extra_warnings</>
4842 set to <varname>shadowed_variables</>:
4844 SET plpgsql.extra_warnings TO 'shadowed_variables';
4846 CREATE FUNCTION foo(f1 int) RETURNS int AS $$
4852 $$ LANGUAGE plpgsql;
4853 WARNING: variable "f1" shadows a previously defined variable
4862 <!-- **** Porting from Oracle PL/SQL **** -->
4864 <sect1 id="plpgsql-porting">
4865 <title>Porting from <productname>Oracle</productname> PL/SQL</title>
4867 <indexterm zone="plpgsql-porting">
4868 <primary>Oracle</primary>
4869 <secondary>porting from PL/SQL to PL/pgSQL</secondary>
4872 <indexterm zone="plpgsql-porting">
4873 <primary>PL/SQL (Oracle)</primary>
4874 <secondary>porting to PL/pgSQL</secondary>
4878 This section explains differences between
4879 <productname>PostgreSQL</>'s <application>PL/pgSQL</application>
4880 language and Oracle's <application>PL/SQL</application> language,
4881 to help developers who port applications from
4882 <trademark class="registered">Oracle</> to <productname>PostgreSQL</>.
4886 <application>PL/pgSQL</application> is similar to PL/SQL in many
4887 aspects. It is a block-structured, imperative language, and all
4888 variables have to be declared. Assignments, loops, conditionals
4889 are similar. The main differences you should keep in mind when
4890 porting from <application>PL/SQL</> to
4891 <application>PL/pgSQL</application> are:
4896 If a name used in a SQL command could be either a column name of a
4897 table or a reference to a variable of the function,
4898 <application>PL/SQL</> treats it as a column name. This corresponds
4899 to <application>PL/pgSQL</>'s
4900 <literal>plpgsql.variable_conflict</> = <literal>use_column</>
4901 behavior, which is not the default,
4902 as explained in <xref linkend="plpgsql-var-subst">.
4903 It's often best to avoid such ambiguities in the first place,
4904 but if you have to port a large amount of code that depends on
4905 this behavior, setting <literal>variable_conflict</> may be the
4912 In <productname>PostgreSQL</> the function body must be written as
4913 a string literal. Therefore you need to use dollar quoting or escape
4914 single quotes in the function body. (See <xref
4915 linkend="plpgsql-quote-tips">.)
4921 Instead of packages, use schemas to organize your functions
4928 Since there are no packages, there are no package-level variables
4929 either. This is somewhat annoying. You can keep per-session state
4930 in temporary tables instead.
4936 Integer <command>FOR</> loops with <literal>REVERSE</> work
4937 differently: <application>PL/SQL</> counts down from the second
4938 number to the first, while <application>PL/pgSQL</> counts down
4939 from the first number to the second, requiring the loop bounds
4940 to be swapped when porting. This incompatibility is unfortunate
4941 but is unlikely to be changed. (See <xref
4942 linkend="plpgsql-integer-for">.)
4948 <command>FOR</> loops over queries (other than cursors) also work
4949 differently: the target variable(s) must have been declared,
4950 whereas <application>PL/SQL</> always declares them implicitly.
4951 An advantage of this is that the variable values are still accessible
4952 after the loop exits.
4958 There are various notational differences for the use of cursor
4967 <title>Porting Examples</title>
4970 <xref linkend="pgsql-porting-ex1"> shows how to port a simple
4971 function from <application>PL/SQL</> to <application>PL/pgSQL</>.
4974 <example id="pgsql-porting-ex1">
4975 <title>Porting a Simple Function from <application>PL/SQL</> to <application>PL/pgSQL</></title>
4978 Here is an <productname>Oracle</productname> <application>PL/SQL</> function:
4980 CREATE OR REPLACE FUNCTION cs_fmt_browser_version(v_name varchar,
4984 IF v_version IS NULL THEN
4987 RETURN v_name || '/' || v_version;
4995 Let's go through this function and see the differences compared to
4996 <application>PL/pgSQL</>:
5001 The <literal>RETURN</literal> key word in the function
5002 prototype (not the function body) becomes
5003 <literal>RETURNS</literal> in
5004 <productname>PostgreSQL</productname>.
5005 Also, <literal>IS</> becomes <literal>AS</>, and you need to
5006 add a <literal>LANGUAGE</> clause because <application>PL/pgSQL</>
5007 is not the only possible function language.
5013 In <productname>PostgreSQL</>, the function body is considered
5014 to be a string literal, so you need to use quote marks or dollar
5015 quotes around it. This substitutes for the terminating <literal>/</>
5016 in the Oracle approach.
5022 The <literal>show errors</literal> command does not exist in
5023 <productname>PostgreSQL</>, and is not needed since errors are
5024 reported automatically.
5031 This is how this function would look when ported to
5032 <productname>PostgreSQL</>:
5035 CREATE OR REPLACE FUNCTION cs_fmt_browser_version(v_name varchar,
5037 RETURNS varchar AS $$
5039 IF v_version IS NULL THEN
5042 RETURN v_name || '/' || v_version;
5044 $$ LANGUAGE plpgsql;
5050 <xref linkend="plpgsql-porting-ex2"> shows how to port a
5051 function that creates another function and how to handle the
5052 ensuing quoting problems.
5055 <example id="plpgsql-porting-ex2">
5056 <title>Porting a Function that Creates Another Function from <application>PL/SQL</> to <application>PL/pgSQL</></title>
5059 The following procedure grabs rows from a
5060 <command>SELECT</command> statement and builds a large function
5061 with the results in <literal>IF</literal> statements, for the
5066 This is the Oracle version:
5068 CREATE OR REPLACE PROCEDURE cs_update_referrer_type_proc IS
5069 CURSOR referrer_keys IS
5070 SELECT * FROM cs_referrer_keys
5072 func_cmd VARCHAR(4000);
5074 func_cmd := 'CREATE OR REPLACE FUNCTION cs_find_referrer_type(v_host IN VARCHAR,
5075 v_domain IN VARCHAR, v_url IN VARCHAR) RETURN VARCHAR IS BEGIN';
5077 FOR referrer_key IN referrer_keys LOOP
5078 func_cmd := func_cmd ||
5079 ' IF v_' || referrer_key.kind
5080 || ' LIKE ''' || referrer_key.key_string
5081 || ''' THEN RETURN ''' || referrer_key.referrer_type
5085 func_cmd := func_cmd || ' RETURN NULL; END;';
5087 EXECUTE IMMEDIATE func_cmd;
5095 Here is how this function would end up in <productname>PostgreSQL</>:
5097 CREATE OR REPLACE FUNCTION cs_update_referrer_type_proc() RETURNS void AS $func$
5099 referrer_keys CURSOR IS
5100 SELECT * FROM cs_referrer_keys
5105 func_body := 'BEGIN';
5107 FOR referrer_key IN referrer_keys LOOP
5108 func_body := func_body ||
5109 ' IF v_' || referrer_key.kind
5110 || ' LIKE ' || quote_literal(referrer_key.key_string)
5111 || ' THEN RETURN ' || quote_literal(referrer_key.referrer_type)
5115 func_body := func_body || ' RETURN NULL; END;';
5118 'CREATE OR REPLACE FUNCTION cs_find_referrer_type(v_host varchar,
5121 RETURNS varchar AS '
5122 || quote_literal(func_body)
5123 || ' LANGUAGE plpgsql;' ;
5127 $func$ LANGUAGE plpgsql;
5129 Notice how the body of the function is built separately and passed
5130 through <literal>quote_literal</> to double any quote marks in it. This
5131 technique is needed because we cannot safely use dollar quoting for
5132 defining the new function: we do not know for sure what strings will
5133 be interpolated from the <structfield>referrer_key.key_string</> field.
5134 (We are assuming here that <structfield>referrer_key.kind</> can be
5135 trusted to always be <literal>host</>, <literal>domain</>, or
5136 <literal>url</>, but <structfield>referrer_key.key_string</> might be
5137 anything, in particular it might contain dollar signs.) This function
5138 is actually an improvement on the Oracle original, because it will
5139 not generate broken code when <structfield>referrer_key.key_string</> or
5140 <structfield>referrer_key.referrer_type</> contain quote marks.
5145 <xref linkend="plpgsql-porting-ex3"> shows how to port a function
5146 with <literal>OUT</> parameters and string manipulation.
5147 <productname>PostgreSQL</> does not have a built-in
5148 <function>instr</function> function, but you can create one
5149 using a combination of other
5150 functions. In <xref linkend="plpgsql-porting-appendix"> there is a
5151 <application>PL/pgSQL</application> implementation of
5152 <function>instr</function> that you can use to make your porting
5156 <example id="plpgsql-porting-ex3">
5157 <title>Porting a Procedure With String Manipulation and
5158 <literal>OUT</> Parameters from <application>PL/SQL</> to
5159 <application>PL/pgSQL</></title>
5162 The following <productname>Oracle</productname> PL/SQL procedure is used
5163 to parse a URL and return several elements (host, path, and query).
5167 This is the Oracle version:
5169 CREATE OR REPLACE PROCEDURE cs_parse_url(
5171 v_host OUT VARCHAR, -- This will be passed back
5172 v_path OUT VARCHAR, -- This one too
5173 v_query OUT VARCHAR) -- And this one
5181 a_pos1 := instr(v_url, '//');
5186 a_pos2 := instr(v_url, '/', a_pos1 + 2);
5188 v_host := substr(v_url, a_pos1 + 2);
5193 v_host := substr(v_url, a_pos1 + 2, a_pos2 - a_pos1 - 2);
5194 a_pos1 := instr(v_url, '?', a_pos2 + 1);
5197 v_path := substr(v_url, a_pos2);
5201 v_path := substr(v_url, a_pos2, a_pos1 - a_pos2);
5202 v_query := substr(v_url, a_pos1 + 1);
5210 Here is a possible translation into <application>PL/pgSQL</>:
5212 CREATE OR REPLACE FUNCTION cs_parse_url(
5214 v_host OUT VARCHAR, -- This will be passed back
5215 v_path OUT VARCHAR, -- This one too
5216 v_query OUT VARCHAR) -- And this one
5225 a_pos1 := instr(v_url, '//');
5230 a_pos2 := instr(v_url, '/', a_pos1 + 2);
5232 v_host := substr(v_url, a_pos1 + 2);
5237 v_host := substr(v_url, a_pos1 + 2, a_pos2 - a_pos1 - 2);
5238 a_pos1 := instr(v_url, '?', a_pos2 + 1);
5241 v_path := substr(v_url, a_pos2);
5245 v_path := substr(v_url, a_pos2, a_pos1 - a_pos2);
5246 v_query := substr(v_url, a_pos1 + 1);
5248 $$ LANGUAGE plpgsql;
5251 This function could be used like this:
5253 SELECT * FROM cs_parse_url('http://foobar.com/query.cgi?baz');
5259 <xref linkend="plpgsql-porting-ex4"> shows how to port a procedure
5260 that uses numerous features that are specific to Oracle.
5263 <example id="plpgsql-porting-ex4">
5264 <title>Porting a Procedure from <application>PL/SQL</> to <application>PL/pgSQL</></title>
5270 CREATE OR REPLACE PROCEDURE cs_create_job(v_job_id IN INTEGER) IS
5271 a_running_job_count INTEGER;
5272 PRAGMA AUTONOMOUS_TRANSACTION;<co id="co.plpgsql-porting-pragma">
5274 LOCK TABLE cs_jobs IN EXCLUSIVE MODE;<co id="co.plpgsql-porting-locktable">
5276 SELECT count(*) INTO a_running_job_count FROM cs_jobs WHERE end_stamp IS NULL;
5278 IF a_running_job_count > 0 THEN
5279 COMMIT; -- free lock<co id="co.plpgsql-porting-commit">
5280 raise_application_error(-20000,
5281 'Unable to create a new job: a job is currently running.');
5284 DELETE FROM cs_active_job;
5285 INSERT INTO cs_active_job(job_id) VALUES (v_job_id);
5288 INSERT INTO cs_jobs (job_id, start_stamp) VALUES (v_job_id, sysdate);
5290 WHEN dup_val_on_index THEN NULL; -- don't worry if it already exists
5300 Procedures like this can easily be converted into <productname>PostgreSQL</>
5301 functions returning <type>void</type>. This procedure in
5302 particular is interesting because it can teach us some things:
5305 <callout arearefs="co.plpgsql-porting-pragma">
5307 There is no <literal>PRAGMA</literal> statement in <productname>PostgreSQL</>.
5311 <callout arearefs="co.plpgsql-porting-locktable">
5313 If you do a <command>LOCK TABLE</command> in <application>PL/pgSQL</>,
5314 the lock will not be released until the calling transaction is
5319 <callout arearefs="co.plpgsql-porting-commit">
5321 You cannot issue <command>COMMIT</> in a
5322 <application>PL/pgSQL</application> function. The function is
5323 running within some outer transaction and so <command>COMMIT</>
5324 would imply terminating the function's execution. However, in
5325 this particular case it is not necessary anyway, because the lock
5326 obtained by the <command>LOCK TABLE</command> will be released when
5334 This is how we could port this procedure to <application>PL/pgSQL</>:
5337 CREATE OR REPLACE FUNCTION cs_create_job(v_job_id integer) RETURNS void AS $$
5339 a_running_job_count integer;
5341 LOCK TABLE cs_jobs IN EXCLUSIVE MODE;
5343 SELECT count(*) INTO a_running_job_count FROM cs_jobs WHERE end_stamp IS NULL;
5345 IF a_running_job_count > 0 THEN
5346 RAISE EXCEPTION 'Unable to create a new job: a job is currently running';<co id="co.plpgsql-porting-raise">
5349 DELETE FROM cs_active_job;
5350 INSERT INTO cs_active_job(job_id) VALUES (v_job_id);
5353 INSERT INTO cs_jobs (job_id, start_stamp) VALUES (v_job_id, now());
5355 WHEN unique_violation THEN <co id="co.plpgsql-porting-exception">
5356 -- don't worry if it already exists
5359 $$ LANGUAGE plpgsql;
5363 <callout arearefs="co.plpgsql-porting-raise">
5365 The syntax of <literal>RAISE</> is considerably different from
5366 Oracle's statement, although the basic case <literal>RAISE</>
5367 <replaceable class="parameter">exception_name</replaceable> works
5371 <callout arearefs="co.plpgsql-porting-exception">
5373 The exception names supported by <application>PL/pgSQL</> are
5374 different from Oracle's. The set of built-in exception names
5375 is much larger (see <xref linkend="errcodes-appendix">). There
5376 is not currently a way to declare user-defined exception names,
5377 although you can throw user-chosen SQLSTATE values instead.
5382 The main functional difference between this procedure and the
5383 Oracle equivalent is that the exclusive lock on the <literal>cs_jobs</>
5384 table will be held until the calling transaction completes. Also, if
5385 the caller later aborts (for example due to an error), the effects of
5386 this procedure will be rolled back.
5391 <sect2 id="plpgsql-porting-other">
5392 <title>Other Things to Watch For</title>
5395 This section explains a few other things to watch for when porting
5396 Oracle <application>PL/SQL</> functions to
5397 <productname>PostgreSQL</productname>.
5400 <sect3 id="plpgsql-porting-exceptions">
5401 <title>Implicit Rollback after Exceptions</title>
5404 In <application>PL/pgSQL</>, when an exception is caught by an
5405 <literal>EXCEPTION</> clause, all database changes since the block's
5406 <literal>BEGIN</> are automatically rolled back. That is, the behavior
5407 is equivalent to what you'd get in Oracle with:
5423 If you are translating an Oracle procedure that uses
5424 <command>SAVEPOINT</> and <command>ROLLBACK TO</> in this style,
5425 your task is easy: just omit the <command>SAVEPOINT</> and
5426 <command>ROLLBACK TO</>. If you have a procedure that uses
5427 <command>SAVEPOINT</> and <command>ROLLBACK TO</> in a different way
5428 then some actual thought will be required.
5433 <title><command>EXECUTE</command></title>
5436 The <application>PL/pgSQL</> version of
5437 <command>EXECUTE</command> works similarly to the
5438 <application>PL/SQL</> version, but you have to remember to use
5439 <function>quote_literal</function> and
5440 <function>quote_ident</function> as described in <xref
5441 linkend="plpgsql-statements-executing-dyn">. Constructs of the
5442 type <literal>EXECUTE 'SELECT * FROM $1';</literal> will not work
5443 reliably unless you use these functions.
5447 <sect3 id="plpgsql-porting-optimization">
5448 <title>Optimizing <application>PL/pgSQL</application> Functions</title>
5451 <productname>PostgreSQL</> gives you two function creation
5452 modifiers to optimize execution: <quote>volatility</> (whether
5453 the function always returns the same result when given the same
5454 arguments) and <quote>strictness</quote> (whether the function
5455 returns null if any argument is null). Consult the <xref
5456 linkend="sql-createfunction">
5457 reference page for details.
5461 When making use of these optimization attributes, your
5462 <command>CREATE FUNCTION</command> statement might look something
5466 CREATE FUNCTION foo(...) RETURNS integer AS $$
5468 $$ LANGUAGE plpgsql STRICT IMMUTABLE;
5474 <sect2 id="plpgsql-porting-appendix">
5475 <title>Appendix</title>
5478 This section contains the code for a set of Oracle-compatible
5479 <function>instr</function> functions that you can use to simplify
5480 your porting efforts.
5484 <primary><function>instr</> function</primary>
5489 -- instr functions that mimic Oracle's counterpart
5490 -- Syntax: instr(string1, string2, [n], [m]) where [] denotes optional parameters.
5492 -- Searches string1 beginning at the nth character for the mth occurrence
5493 -- of string2. If n is negative, search backwards. If m is not passed,
5494 -- assume 1 (search starts at first character).
5497 CREATE FUNCTION instr(varchar, varchar) RETURNS integer AS $$
5501 pos:= instr($1, $2, 1);
5504 $$ LANGUAGE plpgsql STRICT IMMUTABLE;
5507 CREATE FUNCTION instr(string varchar, string_to_search varchar, beg_index integer)
5508 RETURNS integer AS $$
5510 pos integer NOT NULL DEFAULT 0;
5516 IF beg_index > 0 THEN
5517 temp_str := substring(string FROM beg_index);
5518 pos := position(string_to_search IN temp_str);
5523 RETURN pos + beg_index - 1;
5525 ELSIF beg_index < 0 THEN
5526 ss_length := char_length(string_to_search);
5527 length := char_length(string);
5528 beg := length + beg_index - ss_length + 2;
5530 WHILE beg > 0 LOOP
5531 temp_str := substring(string FROM beg FOR ss_length);
5532 pos := position(string_to_search IN temp_str);
5546 $$ LANGUAGE plpgsql STRICT IMMUTABLE;
5549 CREATE FUNCTION instr(string varchar, string_to_search varchar,
5550 beg_index integer, occur_index integer)
5551 RETURNS integer AS $$
5553 pos integer NOT NULL DEFAULT 0;
5554 occur_number integer NOT NULL DEFAULT 0;
5561 IF beg_index > 0 THEN
5563 temp_str := substring(string FROM beg_index);
5565 FOR i IN 1..occur_index LOOP
5566 pos := position(string_to_search IN temp_str);
5569 beg := beg + pos - 1;
5574 temp_str := substring(string FROM beg + 1);
5582 ELSIF beg_index < 0 THEN
5583 ss_length := char_length(string_to_search);
5584 length := char_length(string);
5585 beg := length + beg_index - ss_length + 2;
5587 WHILE beg > 0 LOOP
5588 temp_str := substring(string FROM beg FOR ss_length);
5589 pos := position(string_to_search IN temp_str);
5592 occur_number := occur_number + 1;
5594 IF occur_number = occur_index THEN
5607 $$ LANGUAGE plpgsql STRICT IMMUTABLE;