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 quantity, quantity * price FROM sales
491 WHERE 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 had 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, or the variable has a specific size/precision
885 (like <type>char(20)</type>), the result value will be implicitly
886 converted by the <application>PL/pgSQL</application> interpreter using
887 the result type's output-function and
888 the variable type's input-function. Note that this could potentially
889 result in run-time errors generated by the input function, if the
890 string form of the result value is not acceptable to the input function.
896 tax := subtotal * 0.06;
897 my_record.user_id := 20;
902 <sect2 id="plpgsql-statements-sql-noresult">
903 <title>Executing a Command With No Result</title>
906 For any SQL command that does not return rows, for example
907 <command>INSERT</> without a <literal>RETURNING</> clause, you can
908 execute the command within a <application>PL/pgSQL</application> function
909 just by writing the command.
913 Any <application>PL/pgSQL</application> variable name appearing
914 in the command text is treated as a parameter, and then the
915 current value of the variable is provided as the parameter value
916 at run time. This is exactly like the processing described earlier
917 for expressions; for details see <xref linkend="plpgsql-var-subst">.
921 When executing a SQL command in this way,
922 <application>PL/pgSQL</application> may cache and re-use the execution
923 plan for the command, as discussed in
924 <xref linkend="plpgsql-plan-caching">.
928 Sometimes it is useful to evaluate an expression or <command>SELECT</>
929 query but discard the result, for example when calling a function
930 that has side-effects but no useful result value. To do
931 this in <application>PL/pgSQL</application>, use the
932 <command>PERFORM</command> statement:
935 PERFORM <replaceable>query</replaceable>;
938 This executes <replaceable>query</replaceable> and discards the
939 result. Write the <replaceable>query</replaceable> the same
940 way you would write an SQL <command>SELECT</> command, but replace the
941 initial keyword <command>SELECT</> with <command>PERFORM</command>.
942 For <command>WITH</> queries, use <command>PERFORM</> and then
943 place the query in parentheses. (In this case, the query can only
945 <application>PL/pgSQL</application> variables will be
946 substituted into the query just as for commands that return no result,
947 and the plan is cached in the same way. Also, the special variable
948 <literal>FOUND</literal> is set to true if the query produced at
949 least one row, or false if it produced no rows (see
950 <xref linkend="plpgsql-statements-diagnostics">).
955 One might expect that writing <command>SELECT</command> directly
956 would accomplish this result, but at
957 present the only accepted way to do it is
958 <command>PERFORM</command>. A SQL command that can return rows,
959 such as <command>SELECT</command>, will be rejected as an error
960 unless it has an <literal>INTO</> clause as discussed in the
968 PERFORM create_mv('cs_session_page_requests_mv', my_query);
973 <sect2 id="plpgsql-statements-sql-onerow">
974 <title>Executing a Query with a Single-row Result</title>
976 <indexterm zone="plpgsql-statements-sql-onerow">
977 <primary>SELECT INTO</primary>
978 <secondary>in PL/pgSQL</secondary>
981 <indexterm zone="plpgsql-statements-sql-onerow">
982 <primary>RETURNING INTO</primary>
983 <secondary>in PL/pgSQL</secondary>
987 The result of a SQL command yielding a single row (possibly of multiple
988 columns) can be assigned to a record variable, row-type variable, or list
989 of scalar variables. This is done by writing the base SQL command and
990 adding an <literal>INTO</> clause. For example,
993 SELECT <replaceable>select_expressions</replaceable> INTO <optional>STRICT</optional> <replaceable>target</replaceable> FROM ...;
994 INSERT ... RETURNING <replaceable>expressions</replaceable> INTO <optional>STRICT</optional> <replaceable>target</replaceable>;
995 UPDATE ... RETURNING <replaceable>expressions</replaceable> INTO <optional>STRICT</optional> <replaceable>target</replaceable>;
996 DELETE ... RETURNING <replaceable>expressions</replaceable> INTO <optional>STRICT</optional> <replaceable>target</replaceable>;
999 where <replaceable>target</replaceable> can be a record variable, a row
1000 variable, or a comma-separated list of simple variables and
1002 <application>PL/pgSQL</application> variables will be
1003 substituted into the rest of the query, and the plan is cached,
1004 just as described above for commands that do not return rows.
1005 This works for <command>SELECT</>,
1006 <command>INSERT</>/<command>UPDATE</>/<command>DELETE</> with
1007 <literal>RETURNING</>, and utility commands that return row-set
1008 results (such as <command>EXPLAIN</>).
1009 Except for the <literal>INTO</> clause, the SQL command is the same
1010 as it would be written outside <application>PL/pgSQL</application>.
1015 Note that this interpretation of <command>SELECT</> with <literal>INTO</>
1016 is quite different from <productname>PostgreSQL</>'s regular
1017 <command>SELECT INTO</command> command, wherein the <literal>INTO</>
1018 target is a newly created table. If you want to create a table from a
1019 <command>SELECT</> result inside a
1020 <application>PL/pgSQL</application> function, use the syntax
1021 <command>CREATE TABLE ... AS SELECT</command>.
1026 If a row or a variable list is used as target, the query's result columns
1027 must exactly match the structure of the target as to number and data
1028 types, or else a run-time error
1029 occurs. When a record variable is the target, it automatically
1030 configures itself to the row type of the query result columns.
1034 The <literal>INTO</> clause can appear almost anywhere in the SQL
1035 command. Customarily it is written either just before or just after
1036 the list of <replaceable>select_expressions</replaceable> in a
1037 <command>SELECT</> command, or at the end of the command for other
1038 command types. It is recommended that you follow this convention
1039 in case the <application>PL/pgSQL</application> parser becomes
1040 stricter in future versions.
1044 If <literal>STRICT</literal> is not specified in the <literal>INTO</>
1045 clause, then <replaceable>target</replaceable> will be set to the first
1046 row returned by the query, or to nulls if the query returned no rows.
1047 (Note that <quote>the first row</> is not
1048 well-defined unless you've used <literal>ORDER BY</>.) Any result rows
1049 after the first row are discarded.
1050 You can check the special <literal>FOUND</literal> variable (see
1051 <xref linkend="plpgsql-statements-diagnostics">) to
1052 determine whether a row was returned:
1055 SELECT * INTO myrec FROM emp WHERE empname = myname;
1057 RAISE EXCEPTION 'employee % not found', myname;
1061 If the <literal>STRICT</literal> option is specified, the query must
1062 return exactly one row or a run-time error will be reported, either
1063 <literal>NO_DATA_FOUND</> (no rows) or <literal>TOO_MANY_ROWS</>
1064 (more than one row). You can use an exception block if you wish
1065 to catch the error, for example:
1069 SELECT * INTO STRICT myrec FROM emp WHERE empname = myname;
1071 WHEN NO_DATA_FOUND THEN
1072 RAISE EXCEPTION 'employee % not found', myname;
1073 WHEN TOO_MANY_ROWS THEN
1074 RAISE EXCEPTION 'employee % not unique', myname;
1077 Successful execution of a command with <literal>STRICT</>
1078 always sets <literal>FOUND</literal> to true.
1082 If <literal>print_strict_params</> is enabled for the function,
1083 you will get information about the parameters passed to the
1084 query in the <literal>DETAIL</> part of the error message produced
1085 when the requirements of STRICT are not met. You can change this
1086 setting on a system-wide basis by setting
1087 <varname>plpgsql.print_strict_params</>, though only subsequent
1088 function compilations will be affected. You can also enable it
1089 on a per-function basis by using a compiler option:
1091 CREATE FUNCTION get_userid(username text) RETURNS int
1093 #print_strict_params on
1097 SELECT users.userid INTO STRICT userid
1098 FROM users WHERE users.username = get_userid.username;
1101 $$ LANGUAGE plpgsql;
1106 For <command>INSERT</>/<command>UPDATE</>/<command>DELETE</> with
1107 <literal>RETURNING</>, <application>PL/pgSQL</application> reports
1108 an error for more than one returned row, even when
1109 <literal>STRICT</literal> is not specified. This is because there
1110 is no option such as <literal>ORDER BY</> with which to determine
1111 which affected row should be returned.
1116 The <literal>STRICT</> option matches the behavior of
1117 Oracle PL/SQL's <command>SELECT INTO</command> and related statements.
1122 To handle cases where you need to process multiple result rows
1123 from a SQL query, see <xref linkend="plpgsql-records-iterating">.
1128 <sect2 id="plpgsql-statements-executing-dyn">
1129 <title>Executing Dynamic Commands</title>
1132 Oftentimes you will want to generate dynamic commands inside your
1133 <application>PL/pgSQL</application> functions, that is, commands
1134 that will involve different tables or different data types each
1135 time they are executed. <application>PL/pgSQL</application>'s
1136 normal attempts to cache plans for commands (as discussed in
1137 <xref linkend="plpgsql-plan-caching">) will not work in such
1138 scenarios. To handle this sort of problem, the
1139 <command>EXECUTE</command> statement is provided:
1142 EXECUTE <replaceable class="command">command-string</replaceable> <optional> INTO <optional>STRICT</optional> <replaceable>target</replaceable> </optional> <optional> USING <replaceable>expression</replaceable> <optional>, ... </optional> </optional>;
1145 where <replaceable>command-string</replaceable> is an expression
1146 yielding a string (of type <type>text</type>) containing the
1147 command to be executed. The optional <replaceable>target</replaceable>
1148 is a record variable, a row variable, or a comma-separated list of
1149 simple variables and record/row fields, into which the results of
1150 the command will be stored. The optional <literal>USING</> expressions
1151 supply values to be inserted into the command.
1155 No substitution of <application>PL/pgSQL</> variables is done on the
1156 computed command string. Any required variable values must be inserted
1157 in the command string as it is constructed; or you can use parameters
1162 Also, there is no plan caching for commands executed via
1163 <command>EXECUTE</command>. Instead, the command is always planned
1164 each time the statement is run. Thus the command
1165 string can be dynamically created within the function to perform
1166 actions on different tables and columns.
1170 The <literal>INTO</literal> clause specifies where the results of
1171 a SQL command returning rows should be assigned. If a row
1172 or variable list is provided, it must exactly match the structure
1173 of the query's results (when a
1174 record variable is used, it will configure itself to match the
1175 result structure automatically). If multiple rows are returned,
1176 only the first will be assigned to the <literal>INTO</literal>
1177 variable. If no rows are returned, NULL is assigned to the
1178 <literal>INTO</literal> variable(s). If no <literal>INTO</literal>
1179 clause is specified, the query results are discarded.
1183 If the <literal>STRICT</> option is given, an error is reported
1184 unless the query produces exactly one row.
1188 The command string can use parameter values, which are referenced
1189 in the command as <literal>$1</>, <literal>$2</>, etc.
1190 These symbols refer to values supplied in the <literal>USING</>
1191 clause. This method is often preferable to inserting data values
1192 into the command string as text: it avoids run-time overhead of
1193 converting the values to text and back, and it is much less prone
1194 to SQL-injection attacks since there is no need for quoting or escaping.
1197 EXECUTE 'SELECT count(*) FROM mytable WHERE inserted_by = $1 AND inserted <= $2'
1199 USING checked_user, checked_date;
1204 Note that parameter symbols can only be used for data values
1205 — if you want to use dynamically determined table or column
1206 names, you must insert them into the command string textually.
1207 For example, if the preceding query needed to be done against a
1208 dynamically selected table, you could do this:
1210 EXECUTE 'SELECT count(*) FROM '
1211 || tabname::regclass
1212 || ' WHERE inserted_by = $1 AND inserted <= $2'
1214 USING checked_user, checked_date;
1216 Another restriction on parameter symbols is that they only work in
1217 <command>SELECT</>, <command>INSERT</>, <command>UPDATE</>, and
1218 <command>DELETE</> commands. In other statement
1219 types (generically called utility statements), you must insert
1220 values textually even if they are just data values.
1224 An <command>EXECUTE</> with a simple constant command string and some
1225 <literal>USING</> parameters, as in the first example above, is
1226 functionally equivalent to just writing the command directly in
1227 <application>PL/pgSQL</application> and allowing replacement of
1228 <application>PL/pgSQL</application> variables to happen automatically.
1229 The important difference is that <command>EXECUTE</> will re-plan
1230 the command on each execution, generating a plan that is specific
1231 to the current parameter values; whereas
1232 <application>PL/pgSQL</application> may otherwise create a generic plan
1233 and cache it for re-use. In situations where the best plan depends
1234 strongly on the parameter values, it can be helpful to use
1235 <command>EXECUTE</> to positively ensure that a generic plan is not
1240 <command>SELECT INTO</command> is not currently supported within
1241 <command>EXECUTE</command>; instead, execute a plain <command>SELECT</>
1242 command and specify <literal>INTO</> as part of the <command>EXECUTE</>
1248 The <application>PL/pgSQL</application>
1249 <command>EXECUTE</command> statement is not related to the
1250 <xref linkend="sql-execute"> SQL
1251 statement supported by the
1252 <productname>PostgreSQL</productname> server. The server's
1253 <command>EXECUTE</command> statement cannot be used directly within
1254 <application>PL/pgSQL</> functions (and is not needed).
1258 <example id="plpgsql-quote-literal-example">
1259 <title>Quoting Values In Dynamic Queries</title>
1262 <primary>quote_ident</primary>
1263 <secondary>use in PL/pgSQL</secondary>
1267 <primary>quote_literal</primary>
1268 <secondary>use in PL/pgSQL</secondary>
1272 <primary>quote_nullable</primary>
1273 <secondary>use in PL/pgSQL</secondary>
1277 <primary>format</primary>
1278 <secondary>use in PL/pgSQL</secondary>
1282 When working with dynamic commands you will often have to handle escaping
1283 of single quotes. The recommended method for quoting fixed text in your
1284 function body is dollar quoting. (If you have legacy code that does
1285 not use dollar quoting, please refer to the
1286 overview in <xref linkend="plpgsql-quote-tips">, which can save you
1287 some effort when translating said code to a more reasonable scheme.)
1291 Dynamic values that are to be inserted into the constructed
1292 query require careful handling since they might themselves contain
1294 An example (this assumes that you are using dollar quoting for the
1295 function as a whole, so the quote marks need not be doubled):
1297 EXECUTE 'UPDATE tbl SET '
1298 || quote_ident(colname)
1300 || quote_literal(newvalue)
1302 || quote_literal(keyvalue);
1307 This example demonstrates the use of the
1308 <function>quote_ident</function> and
1309 <function>quote_literal</function> functions (see <xref
1310 linkend="functions-string">). For safety, expressions containing column
1311 or table identifiers should be passed through
1312 <function>quote_ident</function> before insertion in a dynamic query.
1313 Expressions containing values that should be literal strings in the
1314 constructed command should be passed through <function>quote_literal</>.
1315 These functions take the appropriate steps to return the input text
1316 enclosed in double or single quotes respectively, with any embedded
1317 special characters properly escaped.
1321 Because <function>quote_literal</function> is labeled
1322 <literal>STRICT</literal>, it will always return null when called with a
1323 null argument. In the above example, if <literal>newvalue</> or
1324 <literal>keyvalue</> were null, the entire dynamic query string would
1325 become null, leading to an error from <command>EXECUTE</command>.
1326 You can avoid this problem by using the <function>quote_nullable</>
1327 function, which works the same as <function>quote_literal</> except that
1328 when called with a null argument it returns the string <literal>NULL</>.
1331 EXECUTE 'UPDATE tbl SET '
1332 || quote_ident(colname)
1334 || quote_nullable(newvalue)
1336 || quote_nullable(keyvalue);
1338 If you are dealing with values that might be null, you should usually
1339 use <function>quote_nullable</> in place of <function>quote_literal</>.
1343 As always, care must be taken to ensure that null values in a query do
1344 not deliver unintended results. For example the <literal>WHERE</> clause
1346 'WHERE key = ' || quote_nullable(keyvalue)
1348 will never succeed if <literal>keyvalue</> is null, because the
1349 result of using the equality operator <literal>=</> with a null operand
1350 is always null. If you wish null to work like an ordinary key value,
1351 you would need to rewrite the above as
1353 'WHERE key IS NOT DISTINCT FROM ' || quote_nullable(keyvalue)
1355 (At present, <literal>IS NOT DISTINCT FROM</> is handled much less
1356 efficiently than <literal>=</>, so don't do this unless you must.
1357 See <xref linkend="functions-comparison"> for
1358 more information on nulls and <literal>IS DISTINCT</>.)
1362 Note that dollar quoting is only useful for quoting fixed text.
1363 It would be a very bad idea to try to write this example as:
1365 EXECUTE 'UPDATE tbl SET '
1366 || quote_ident(colname)
1369 || '$$ WHERE key = '
1370 || quote_literal(keyvalue);
1372 because it would break if the contents of <literal>newvalue</>
1373 happened to contain <literal>$$</>. The same objection would
1374 apply to any other dollar-quoting delimiter you might pick.
1375 So, to safely quote text that is not known in advance, you
1376 <emphasis>must</> use <function>quote_literal</>,
1377 <function>quote_nullable</>, or <function>quote_ident</>, as appropriate.
1381 Dynamic SQL statements can also be safely constructed using the
1382 <function>format</function> function (see <xref
1383 linkend="functions-string">). For example:
1385 EXECUTE format('UPDATE tbl SET %I = %L WHERE key = %L', colname, newvalue, keyvalue);
1387 The <function>format</function> function can be used in conjunction with
1388 the <literal>USING</literal> clause:
1390 EXECUTE format('UPDATE tbl SET %I = $1 WHERE key = $2', colname)
1391 USING newvalue, keyvalue;
1393 This form is more efficient, because the parameters
1394 <literal>newvalue</literal> and <literal>keyvalue</literal> are not
1400 A much larger example of a dynamic command and
1401 <command>EXECUTE</command> can be seen in <xref
1402 linkend="plpgsql-porting-ex2">, which builds and executes a
1403 <command>CREATE FUNCTION</> command to define a new function.
1407 <sect2 id="plpgsql-statements-diagnostics">
1408 <title>Obtaining the Result Status</title>
1411 There are several ways to determine the effect of a command. The
1412 first method is to use the <command>GET DIAGNOSTICS</command>
1413 command, which has the form:
1416 GET <optional> CURRENT </optional> DIAGNOSTICS <replaceable>variable</replaceable> { = | := } <replaceable>item</replaceable> <optional> , ... </optional>;
1419 This command allows retrieval of system status indicators. Each
1420 <replaceable>item</replaceable> is a key word identifying a status
1421 value to be assigned to the specified variable (which should be
1422 of the right data type to receive it). The currently available
1423 status items are <varname>ROW_COUNT</>, the number of rows
1424 processed by the last <acronym>SQL</acronym> command sent to
1425 the <acronym>SQL</acronym> engine, and <varname>RESULT_OID</>,
1426 the OID of the last row inserted by the most recent
1427 <acronym>SQL</acronym> command. Note that <varname>RESULT_OID</>
1428 is only useful after an <command>INSERT</command> command into a
1429 table containing OIDs.
1430 Colon-equal (<literal>:=</>) can be used instead of SQL-standard
1431 <literal>=</> for <command>GET DIAGNOSTICS</>.
1437 GET DIAGNOSTICS integer_var = ROW_COUNT;
1442 The second method to determine the effects of a command is to check the
1443 special variable named <literal>FOUND</literal>, which is of
1444 type <type>boolean</type>. <literal>FOUND</literal> starts out
1445 false within each <application>PL/pgSQL</application> function call.
1446 It is set by each of the following types of statements:
1451 A <command>SELECT INTO</command> statement sets
1452 <literal>FOUND</literal> true if a row is assigned, false if no
1458 A <command>PERFORM</> statement sets <literal>FOUND</literal>
1459 true if it produces (and discards) one or more rows, false if
1465 <command>UPDATE</>, <command>INSERT</>, and <command>DELETE</>
1466 statements set <literal>FOUND</literal> true if at least one
1467 row is affected, false if no row is affected.
1472 A <command>FETCH</> statement sets <literal>FOUND</literal>
1473 true if it returns a row, false if no row is returned.
1478 A <command>MOVE</> statement sets <literal>FOUND</literal>
1479 true if it successfully repositions the cursor, false otherwise.
1484 A <command>FOR</> or <command>FOREACH</> statement sets
1485 <literal>FOUND</literal> true
1486 if it iterates one or more times, else false.
1487 <literal>FOUND</literal> is set this way when the
1488 loop exits; inside the execution of the loop,
1489 <literal>FOUND</literal> is not modified by the
1490 loop statement, although it might be changed by the
1491 execution of other statements within the loop body.
1496 <command>RETURN QUERY</command> and <command>RETURN QUERY
1497 EXECUTE</command> statements set <literal>FOUND</literal>
1498 true if the query returns at least one row, false if no row
1504 Other <application>PL/pgSQL</application> statements do not change
1505 the state of <literal>FOUND</literal>.
1506 Note in particular that <command>EXECUTE</command>
1507 changes the output of <command>GET DIAGNOSTICS</command>, but
1508 does not change <literal>FOUND</literal>.
1512 <literal>FOUND</literal> is a local variable within each
1513 <application>PL/pgSQL</application> function; any changes to it
1514 affect only the current function.
1519 <sect2 id="plpgsql-statements-null">
1520 <title>Doing Nothing At All</title>
1523 Sometimes a placeholder statement that does nothing is useful.
1524 For example, it can indicate that one arm of an if/then/else
1525 chain is deliberately empty. For this purpose, use the
1526 <command>NULL</command> statement:
1534 For example, the following two fragments of code are equivalent:
1539 WHEN division_by_zero THEN
1540 NULL; -- ignore the error
1548 WHEN division_by_zero THEN -- ignore the error
1551 Which is preferable is a matter of taste.
1556 In Oracle's PL/SQL, empty statement lists are not allowed, and so
1557 <command>NULL</> statements are <emphasis>required</> for situations
1558 such as this. <application>PL/pgSQL</application> allows you to
1559 just write nothing, instead.
1566 <sect1 id="plpgsql-control-structures">
1567 <title>Control Structures</title>
1570 Control structures are probably the most useful (and
1571 important) part of <application>PL/pgSQL</>. With
1572 <application>PL/pgSQL</>'s control structures,
1573 you can manipulate <productname>PostgreSQL</> data in a very
1574 flexible and powerful way.
1577 <sect2 id="plpgsql-statements-returning">
1578 <title>Returning From a Function</title>
1581 There are two commands available that allow you to return data
1582 from a function: <command>RETURN</command> and <command>RETURN
1587 <title><command>RETURN</></title>
1590 RETURN <replaceable>expression</replaceable>;
1594 <command>RETURN</command> with an expression terminates the
1595 function and returns the value of
1596 <replaceable>expression</replaceable> to the caller. This form
1597 is used for <application>PL/pgSQL</> functions that do
1602 In a function that returns a scalar type, the expression's result will
1603 automatically be cast into the function's return type as described for
1604 assignments. But to return a composite (row) value, you must write an
1605 expression delivering exactly the requested column set. This may
1606 require use of explicit casting.
1610 If you declared the function with output parameters, write just
1611 <command>RETURN</command> with no expression. The current values
1612 of the output parameter variables will be returned.
1616 If you declared the function to return <type>void</type>, a
1617 <command>RETURN</command> statement can be used to exit the function
1618 early; but do not write an expression following
1619 <command>RETURN</command>.
1623 The return value of a function cannot be left undefined. If
1624 control reaches the end of the top-level block of the function
1625 without hitting a <command>RETURN</command> statement, a run-time
1626 error will occur. This restriction does not apply to functions
1627 with output parameters and functions returning <type>void</type>,
1628 however. In those cases a <command>RETURN</command> statement is
1629 automatically executed if the top-level block finishes.
1636 -- functions returning a scalar type
1640 -- functions returning a composite type
1641 RETURN composite_type_var;
1642 RETURN (1, 2, 'three'::text); -- must cast columns to correct types
1648 <title><command>RETURN NEXT</> and <command>RETURN QUERY</command></title>
1650 <primary>RETURN NEXT</primary>
1651 <secondary>in PL/pgSQL</secondary>
1654 <primary>RETURN QUERY</primary>
1655 <secondary>in PL/pgSQL</secondary>
1659 RETURN NEXT <replaceable>expression</replaceable>;
1660 RETURN QUERY <replaceable>query</replaceable>;
1661 RETURN QUERY EXECUTE <replaceable class="command">command-string</replaceable> <optional> USING <replaceable>expression</replaceable> <optional>, ... </optional> </optional>;
1665 When a <application>PL/pgSQL</> function is declared to return
1666 <literal>SETOF <replaceable>sometype</></literal>, the procedure
1667 to follow is slightly different. In that case, the individual
1668 items to return are specified by a sequence of <command>RETURN
1669 NEXT</command> or <command>RETURN QUERY</command> commands, and
1670 then a final <command>RETURN</command> command with no argument
1671 is used to indicate that the function has finished executing.
1672 <command>RETURN NEXT</command> can be used with both scalar and
1673 composite data types; with a composite result type, an entire
1674 <quote>table</quote> of results will be returned.
1675 <command>RETURN QUERY</command> appends the results of executing
1676 a query to the function's result set. <command>RETURN
1677 NEXT</command> and <command>RETURN QUERY</command> can be freely
1678 intermixed in a single set-returning function, in which case
1679 their results will be concatenated.
1683 <command>RETURN NEXT</command> and <command>RETURN
1684 QUERY</command> do not actually return from the function —
1685 they simply append zero or more rows to the function's result
1686 set. Execution then continues with the next statement in the
1687 <application>PL/pgSQL</> function. As successive
1688 <command>RETURN NEXT</command> or <command>RETURN
1689 QUERY</command> commands are executed, the result set is built
1690 up. A final <command>RETURN</command>, which should have no
1691 argument, causes control to exit the function (or you can just
1692 let control reach the end of the function).
1696 <command>RETURN QUERY</command> has a variant
1697 <command>RETURN QUERY EXECUTE</command>, which specifies the
1698 query to be executed dynamically. Parameter expressions can
1699 be inserted into the computed query string via <literal>USING</>,
1700 in just the same way as in the <command>EXECUTE</> command.
1704 If you declared the function with output parameters, write just
1705 <command>RETURN NEXT</command> with no expression. On each
1706 execution, the current values of the output parameter
1707 variable(s) will be saved for eventual return as a row of the
1708 result. Note that you must declare the function as returning
1709 <literal>SETOF record</literal> when there are multiple output
1710 parameters, or <literal>SETOF <replaceable>sometype</></literal>
1711 when there is just one output parameter of type
1712 <replaceable>sometype</>, in order to create a set-returning
1713 function with output parameters.
1717 Here is an example of a function using <command>RETURN
1721 CREATE TABLE foo (fooid INT, foosubid INT, fooname TEXT);
1722 INSERT INTO foo VALUES (1, 2, 'three');
1723 INSERT INTO foo VALUES (4, 5, 'six');
1725 CREATE OR REPLACE FUNCTION get_all_foo() RETURNS SETOF foo AS
1731 SELECT * FROM foo WHERE fooid > 0
1733 -- can do some processing here
1734 RETURN NEXT r; -- return current row of SELECT
1741 SELECT * FROM get_all_foo();
1746 Here is an example of a function using <command>RETURN
1750 CREATE FUNCTION get_available_flightid(date) RETURNS SETOF integer AS
1753 RETURN QUERY SELECT flightid
1755 WHERE flightdate >= $1
1756 AND flightdate < ($1 + 1);
1758 -- Since execution is not finished, we can check whether rows were returned
1759 -- and raise exception if not.
1761 RAISE EXCEPTION 'No flight at %.', $1;
1769 -- Returns available flights or raises exception if there are no
1770 -- available flights.
1771 SELECT * FROM get_available_flightid(CURRENT_DATE);
1777 The current implementation of <command>RETURN NEXT</command>
1778 and <command>RETURN QUERY</command> stores the entire result set
1779 before returning from the function, as discussed above. That
1780 means that if a <application>PL/pgSQL</> function produces a
1781 very large result set, performance might be poor: data will be
1782 written to disk to avoid memory exhaustion, but the function
1783 itself will not return until the entire result set has been
1784 generated. A future version of <application>PL/pgSQL</> might
1785 allow users to define set-returning functions
1786 that do not have this limitation. Currently, the point at
1787 which data begins being written to disk is controlled by the
1788 <xref linkend="guc-work-mem">
1789 configuration variable. Administrators who have sufficient
1790 memory to store larger result sets in memory should consider
1791 increasing this parameter.
1797 <sect2 id="plpgsql-conditionals">
1798 <title>Conditionals</title>
1801 <command>IF</> and <command>CASE</> statements let you execute
1802 alternative commands based on certain conditions.
1803 <application>PL/pgSQL</> has three forms of <command>IF</>:
1806 <para><literal>IF ... THEN</></>
1809 <para><literal>IF ... THEN ... ELSE</></>
1812 <para><literal>IF ... THEN ... ELSIF ... THEN ... ELSE</></>
1816 and two forms of <command>CASE</>:
1819 <para><literal>CASE ... WHEN ... THEN ... ELSE ... END CASE</></>
1822 <para><literal>CASE WHEN ... THEN ... ELSE ... END CASE</></>
1828 <title><literal>IF-THEN</></title>
1831 IF <replaceable>boolean-expression</replaceable> THEN
1832 <replaceable>statements</replaceable>
1837 <literal>IF-THEN</literal> statements are the simplest form of
1838 <literal>IF</literal>. The statements between
1839 <literal>THEN</literal> and <literal>END IF</literal> will be
1840 executed if the condition is true. Otherwise, they are
1847 IF v_user_id <> 0 THEN
1848 UPDATE users SET email = v_email WHERE user_id = v_user_id;
1855 <title><literal>IF-THEN-ELSE</></title>
1858 IF <replaceable>boolean-expression</replaceable> THEN
1859 <replaceable>statements</replaceable>
1861 <replaceable>statements</replaceable>
1866 <literal>IF-THEN-ELSE</literal> statements add to
1867 <literal>IF-THEN</literal> by letting you specify an
1868 alternative set of statements that should be executed if the
1869 condition is not true. (Note this includes the case where the
1870 condition evaluates to NULL.)
1876 IF parentid IS NULL OR parentid = ''
1880 RETURN hp_true_filename(parentid) || '/' || fullname;
1885 IF v_count > 0 THEN
1886 INSERT INTO users_count (count) VALUES (v_count);
1896 <title><literal>IF-THEN-ELSIF</></title>
1899 IF <replaceable>boolean-expression</replaceable> THEN
1900 <replaceable>statements</replaceable>
1901 <optional> ELSIF <replaceable>boolean-expression</replaceable> THEN
1902 <replaceable>statements</replaceable>
1903 <optional> ELSIF <replaceable>boolean-expression</replaceable> THEN
1904 <replaceable>statements</replaceable>
1909 <replaceable>statements</replaceable> </optional>
1914 Sometimes there are more than just two alternatives.
1915 <literal>IF-THEN-ELSIF</> provides a convenient
1916 method of checking several alternatives in turn.
1917 The <literal>IF</> conditions are tested successively
1918 until the first one that is true is found. Then the
1919 associated statement(s) are executed, after which control
1920 passes to the next statement after <literal>END IF</>.
1921 (Any subsequent <literal>IF</> conditions are <emphasis>not</>
1922 tested.) If none of the <literal>IF</> conditions is true,
1923 then the <literal>ELSE</> block (if any) is executed.
1932 ELSIF number > 0 THEN
1933 result := 'positive';
1934 ELSIF number < 0 THEN
1935 result := 'negative';
1937 -- hmm, the only other possibility is that number is null
1944 The key word <literal>ELSIF</> can also be spelled
1949 An alternative way of accomplishing the same task is to nest
1950 <literal>IF-THEN-ELSE</literal> statements, as in the
1954 IF demo_row.sex = 'm' THEN
1955 pretty_sex := 'man';
1957 IF demo_row.sex = 'f' THEN
1958 pretty_sex := 'woman';
1965 However, this method requires writing a matching <literal>END IF</>
1966 for each <literal>IF</>, so it is much more cumbersome than
1967 using <literal>ELSIF</> when there are many alternatives.
1972 <title>Simple <literal>CASE</></title>
1975 CASE <replaceable>search-expression</replaceable>
1976 WHEN <replaceable>expression</replaceable> <optional>, <replaceable>expression</replaceable> <optional> ... </optional></optional> THEN
1977 <replaceable>statements</replaceable>
1978 <optional> WHEN <replaceable>expression</replaceable> <optional>, <replaceable>expression</replaceable> <optional> ... </optional></optional> THEN
1979 <replaceable>statements</replaceable>
1982 <replaceable>statements</replaceable> </optional>
1987 The simple form of <command>CASE</> provides conditional execution
1988 based on equality of operands. The <replaceable>search-expression</>
1989 is evaluated (once) and successively compared to each
1990 <replaceable>expression</> in the <literal>WHEN</> clauses.
1991 If a match is found, then the corresponding
1992 <replaceable>statements</replaceable> are executed, and then control
1993 passes to the next statement after <literal>END CASE</>. (Subsequent
1994 <literal>WHEN</> expressions are not evaluated.) If no match is
1995 found, the <literal>ELSE</> <replaceable>statements</replaceable> are
1996 executed; but if <literal>ELSE</> is not present, then a
1997 <literal>CASE_NOT_FOUND</literal> exception is raised.
2001 Here is a simple example:
2006 msg := 'one or two';
2008 msg := 'other value than one or two';
2015 <title>Searched <literal>CASE</></title>
2019 WHEN <replaceable>boolean-expression</replaceable> THEN
2020 <replaceable>statements</replaceable>
2021 <optional> WHEN <replaceable>boolean-expression</replaceable> THEN
2022 <replaceable>statements</replaceable>
2025 <replaceable>statements</replaceable> </optional>
2030 The searched form of <command>CASE</> provides conditional execution
2031 based on truth of Boolean expressions. Each <literal>WHEN</> clause's
2032 <replaceable>boolean-expression</replaceable> is evaluated in turn,
2033 until one is found that yields <literal>true</>. Then the
2034 corresponding <replaceable>statements</replaceable> are executed, and
2035 then control passes to the next statement after <literal>END CASE</>.
2036 (Subsequent <literal>WHEN</> expressions are not evaluated.)
2037 If no true result is found, the <literal>ELSE</>
2038 <replaceable>statements</replaceable> are executed;
2039 but if <literal>ELSE</> is not present, then a
2040 <literal>CASE_NOT_FOUND</literal> exception is raised.
2048 WHEN x BETWEEN 0 AND 10 THEN
2049 msg := 'value is between zero and ten';
2050 WHEN x BETWEEN 11 AND 20 THEN
2051 msg := 'value is between eleven and twenty';
2057 This form of <command>CASE</> is entirely equivalent to
2058 <literal>IF-THEN-ELSIF</>, except for the rule that reaching
2059 an omitted <literal>ELSE</> clause results in an error rather
2066 <sect2 id="plpgsql-control-structures-loops">
2067 <title>Simple Loops</title>
2069 <indexterm zone="plpgsql-control-structures-loops">
2070 <primary>loop</primary>
2071 <secondary>in PL/pgSQL</secondary>
2075 With the <literal>LOOP</>, <literal>EXIT</>,
2076 <literal>CONTINUE</>, <literal>WHILE</>, <literal>FOR</>,
2077 and <literal>FOREACH</> statements, you can arrange for your
2078 <application>PL/pgSQL</> function to repeat a series of commands.
2082 <title><literal>LOOP</></title>
2085 <optional> <<<replaceable>label</replaceable>>> </optional>
2087 <replaceable>statements</replaceable>
2088 END LOOP <optional> <replaceable>label</replaceable> </optional>;
2092 <literal>LOOP</> defines an unconditional loop that is repeated
2093 indefinitely until terminated by an <literal>EXIT</> or
2094 <command>RETURN</command> statement. The optional
2095 <replaceable>label</replaceable> can be used by <literal>EXIT</>
2096 and <literal>CONTINUE</literal> statements within nested loops to
2097 specify which loop those statements refer to.
2102 <title><literal>EXIT</></title>
2105 <primary>EXIT</primary>
2106 <secondary>in PL/pgSQL</secondary>
2110 EXIT <optional> <replaceable>label</replaceable> </optional> <optional> WHEN <replaceable>boolean-expression</replaceable> </optional>;
2114 If no <replaceable>label</replaceable> is given, the innermost
2115 loop is terminated and the statement following <literal>END
2116 LOOP</> is executed next. If <replaceable>label</replaceable>
2117 is given, it must be the label of the current or some outer
2118 level of nested loop or block. Then the named loop or block is
2119 terminated and control continues with the statement after the
2120 loop's/block's corresponding <literal>END</>.
2124 If <literal>WHEN</> is specified, the loop exit occurs only if
2125 <replaceable>boolean-expression</> is true. Otherwise, control passes
2126 to the statement after <literal>EXIT</>.
2130 <literal>EXIT</> can be used with all types of loops; it is
2131 not limited to use with unconditional loops.
2136 <literal>BEGIN</literal> block, <literal>EXIT</literal> passes
2137 control to the next statement after the end of the block.
2138 Note that a label must be used for this purpose; an unlabeled
2139 <literal>EXIT</literal> is never considered to match a
2140 <literal>BEGIN</literal> block. (This is a change from
2141 pre-8.4 releases of <productname>PostgreSQL</productname>, which
2142 would allow an unlabeled <literal>EXIT</literal> to match
2143 a <literal>BEGIN</literal> block.)
2150 -- some computations
2151 IF count > 0 THEN
2157 -- some computations
2158 EXIT WHEN count > 0; -- same result as previous example
2161 <<ablock>>
2163 -- some computations
2164 IF stocks > 100000 THEN
2165 EXIT ablock; -- causes exit from the BEGIN block
2167 -- computations here will be skipped when stocks > 100000
2174 <title><literal>CONTINUE</></title>
2177 <primary>CONTINUE</primary>
2178 <secondary>in PL/pgSQL</secondary>
2182 CONTINUE <optional> <replaceable>label</replaceable> </optional> <optional> WHEN <replaceable>boolean-expression</replaceable> </optional>;
2186 If no <replaceable>label</> is given, the next iteration of
2187 the innermost loop is begun. That is, all statements remaining
2188 in the loop body are skipped, and control returns
2189 to the loop control expression (if any) to determine whether
2190 another loop iteration is needed.
2191 If <replaceable>label</> is present, it
2192 specifies the label of the loop whose execution will be
2197 If <literal>WHEN</> is specified, the next iteration of the
2198 loop is begun only if <replaceable>boolean-expression</> is
2199 true. Otherwise, control passes to the statement after
2200 <literal>CONTINUE</>.
2204 <literal>CONTINUE</> can be used with all types of loops; it
2205 is not limited to use with unconditional loops.
2212 -- some computations
2213 EXIT WHEN count > 100;
2214 CONTINUE WHEN count < 50;
2215 -- some computations for count IN [50 .. 100]
2223 <title><literal>WHILE</></title>
2226 <primary>WHILE</primary>
2227 <secondary>in PL/pgSQL</secondary>
2231 <optional> <<<replaceable>label</replaceable>>> </optional>
2232 WHILE <replaceable>boolean-expression</replaceable> LOOP
2233 <replaceable>statements</replaceable>
2234 END LOOP <optional> <replaceable>label</replaceable> </optional>;
2238 The <literal>WHILE</> statement repeats a
2239 sequence of statements so long as the
2240 <replaceable>boolean-expression</replaceable>
2241 evaluates to true. The expression is checked just before
2242 each entry to the loop body.
2248 WHILE amount_owed > 0 AND gift_certificate_balance > 0 LOOP
2249 -- some computations here
2253 -- some computations here
2259 <sect3 id="plpgsql-integer-for">
2260 <title><literal>FOR</> (Integer Variant)</title>
2263 <optional> <<<replaceable>label</replaceable>>> </optional>
2264 FOR <replaceable>name</replaceable> IN <optional> REVERSE </optional> <replaceable>expression</replaceable> .. <replaceable>expression</replaceable> <optional> BY <replaceable>expression</replaceable> </optional> LOOP
2265 <replaceable>statements</replaceable>
2266 END LOOP <optional> <replaceable>label</replaceable> </optional>;
2270 This form of <literal>FOR</> creates a loop that iterates over a range
2271 of integer values. The variable
2272 <replaceable>name</replaceable> is automatically defined as type
2273 <type>integer</> and exists only inside the loop (any existing
2274 definition of the variable name is ignored within the loop).
2275 The two expressions giving
2276 the lower and upper bound of the range are evaluated once when entering
2277 the loop. If the <literal>BY</> clause isn't specified the iteration
2278 step is 1, otherwise it's the value specified in the <literal>BY</>
2279 clause, which again is evaluated once on loop entry.
2280 If <literal>REVERSE</> is specified then the step value is
2281 subtracted, rather than added, after each iteration.
2285 Some examples of integer <literal>FOR</> loops:
2288 -- i will take on the values 1,2,3,4,5,6,7,8,9,10 within the loop
2291 FOR i IN REVERSE 10..1 LOOP
2292 -- i will take on the values 10,9,8,7,6,5,4,3,2,1 within the loop
2295 FOR i IN REVERSE 10..1 BY 2 LOOP
2296 -- i will take on the values 10,8,6,4,2 within the loop
2302 If the lower bound is greater than the upper bound (or less than,
2303 in the <literal>REVERSE</> case), the loop body is not
2304 executed at all. No error is raised.
2308 If a <replaceable>label</replaceable> is attached to the
2309 <literal>FOR</> loop then the integer loop variable can be
2310 referenced with a qualified name, using that
2311 <replaceable>label</replaceable>.
2316 <sect2 id="plpgsql-records-iterating">
2317 <title>Looping Through Query Results</title>
2320 Using a different type of <literal>FOR</> loop, you can iterate through
2321 the results of a query and manipulate that data
2322 accordingly. The syntax is:
2324 <optional> <<<replaceable>label</replaceable>>> </optional>
2325 FOR <replaceable>target</replaceable> IN <replaceable>query</replaceable> LOOP
2326 <replaceable>statements</replaceable>
2327 END LOOP <optional> <replaceable>label</replaceable> </optional>;
2329 The <replaceable>target</replaceable> is a record variable, row variable,
2330 or comma-separated list of scalar variables.
2331 The <replaceable>target</replaceable> is successively assigned each row
2332 resulting from the <replaceable>query</replaceable> and the loop body is
2333 executed for each row. Here is an example:
2335 CREATE FUNCTION cs_refresh_mviews() RETURNS integer AS $$
2339 RAISE NOTICE 'Refreshing materialized views...';
2341 FOR mviews IN SELECT * FROM cs_materialized_views ORDER BY sort_key LOOP
2343 -- Now "mviews" has one record from cs_materialized_views
2345 RAISE NOTICE 'Refreshing materialized view %s ...', quote_ident(mviews.mv_name);
2346 EXECUTE 'TRUNCATE TABLE ' || quote_ident(mviews.mv_name);
2347 EXECUTE 'INSERT INTO '
2348 || quote_ident(mviews.mv_name) || ' '
2352 RAISE NOTICE 'Done refreshing materialized views.';
2355 $$ LANGUAGE plpgsql;
2358 If the loop is terminated by an <literal>EXIT</> statement, the last
2359 assigned row value is still accessible after the loop.
2363 The <replaceable>query</replaceable> used in this type of <literal>FOR</>
2364 statement can be any SQL command that returns rows to the caller:
2365 <command>SELECT</> is the most common case,
2366 but you can also use <command>INSERT</>, <command>UPDATE</>, or
2367 <command>DELETE</> with a <literal>RETURNING</> clause. Some utility
2368 commands such as <command>EXPLAIN</> will work too.
2372 <application>PL/pgSQL</> variables are substituted into the query text,
2373 and the query plan is cached for possible re-use, as discussed in
2374 detail in <xref linkend="plpgsql-var-subst"> and
2375 <xref linkend="plpgsql-plan-caching">.
2379 The <literal>FOR-IN-EXECUTE</> statement is another way to iterate over
2382 <optional> <<<replaceable>label</replaceable>>> </optional>
2383 FOR <replaceable>target</replaceable> IN EXECUTE <replaceable>text_expression</replaceable> <optional> USING <replaceable>expression</replaceable> <optional>, ... </optional> </optional> LOOP
2384 <replaceable>statements</replaceable>
2385 END LOOP <optional> <replaceable>label</replaceable> </optional>;
2387 This is like the previous form, except that the source query
2388 is specified as a string expression, which is evaluated and replanned
2389 on each entry to the <literal>FOR</> loop. This allows the programmer to
2390 choose the speed of a preplanned query or the flexibility of a dynamic
2391 query, just as with a plain <command>EXECUTE</command> statement.
2392 As with <command>EXECUTE</command>, parameter values can be inserted
2393 into the dynamic command via <literal>USING</>.
2397 Another way to specify the query whose results should be iterated
2398 through is to declare it as a cursor. This is described in
2399 <xref linkend="plpgsql-cursor-for-loop">.
2403 <sect2 id="plpgsql-foreach-array">
2404 <title>Looping Through Arrays</title>
2407 The <literal>FOREACH</> loop is much like a <literal>FOR</> loop,
2408 but instead of iterating through the rows returned by a SQL query,
2409 it iterates through the elements of an array value.
2410 (In general, <literal>FOREACH</> is meant for looping through
2411 components of a composite-valued expression; variants for looping
2412 through composites besides arrays may be added in future.)
2413 The <literal>FOREACH</> statement to loop over an array is:
2416 <optional> <<<replaceable>label</replaceable>>> </optional>
2417 FOREACH <replaceable>target</replaceable> <optional> SLICE <replaceable>number</replaceable> </optional> IN ARRAY <replaceable>expression</replaceable> LOOP
2418 <replaceable>statements</replaceable>
2419 END LOOP <optional> <replaceable>label</replaceable> </optional>;
2424 Without <literal>SLICE</>, or if <literal>SLICE 0</> is specified,
2425 the loop iterates through individual elements of the array produced
2426 by evaluating the <replaceable>expression</replaceable>.
2427 The <replaceable>target</replaceable> variable is assigned each
2428 element value in sequence, and the loop body is executed for each element.
2429 Here is an example of looping through the elements of an integer
2433 CREATE FUNCTION sum(int[]) RETURNS int8 AS $$
2438 FOREACH x IN ARRAY $1
2444 $$ LANGUAGE plpgsql;
2447 The elements are visited in storage order, regardless of the number of
2448 array dimensions. Although the <replaceable>target</replaceable> is
2449 usually just a single variable, it can be a list of variables when
2450 looping through an array of composite values (records). In that case,
2451 for each array element, the variables are assigned from successive
2452 columns of the composite value.
2456 With a positive <literal>SLICE</> value, <literal>FOREACH</>
2457 iterates through slices of the array rather than single elements.
2458 The <literal>SLICE</> value must be an integer constant not larger
2459 than the number of dimensions of the array. The
2460 <replaceable>target</replaceable> variable must be an array,
2461 and it receives successive slices of the array value, where each slice
2462 is of the number of dimensions specified by <literal>SLICE</>.
2463 Here is an example of iterating through one-dimensional slices:
2466 CREATE FUNCTION scan_rows(int[]) RETURNS void AS $$
2470 FOREACH x SLICE 1 IN ARRAY $1
2472 RAISE NOTICE 'row = %', x;
2475 $$ LANGUAGE plpgsql;
2477 SELECT scan_rows(ARRAY[[1,2,3],[4,5,6],[7,8,9],[10,11,12]]);
2479 NOTICE: row = {1,2,3}
2480 NOTICE: row = {4,5,6}
2481 NOTICE: row = {7,8,9}
2482 NOTICE: row = {10,11,12}
2487 <sect2 id="plpgsql-error-trapping">
2488 <title>Trapping Errors</title>
2491 <primary>exceptions</primary>
2492 <secondary>in PL/pgSQL</secondary>
2496 By default, any error occurring in a <application>PL/pgSQL</>
2497 function aborts execution of the function, and indeed of the
2498 surrounding transaction as well. You can trap errors and recover
2499 from them by using a <command>BEGIN</> block with an
2500 <literal>EXCEPTION</> clause. The syntax is an extension of the
2501 normal syntax for a <command>BEGIN</> block:
2504 <optional> <<<replaceable>label</replaceable>>> </optional>
2506 <replaceable>declarations</replaceable> </optional>
2508 <replaceable>statements</replaceable>
2510 WHEN <replaceable>condition</replaceable> <optional> OR <replaceable>condition</replaceable> ... </optional> THEN
2511 <replaceable>handler_statements</replaceable>
2512 <optional> WHEN <replaceable>condition</replaceable> <optional> OR <replaceable>condition</replaceable> ... </optional> THEN
2513 <replaceable>handler_statements</replaceable>
2520 If no error occurs, this form of block simply executes all the
2521 <replaceable>statements</replaceable>, and then control passes
2522 to the next statement after <literal>END</>. But if an error
2523 occurs within the <replaceable>statements</replaceable>, further
2524 processing of the <replaceable>statements</replaceable> is
2525 abandoned, and control passes to the <literal>EXCEPTION</> list.
2526 The list is searched for the first <replaceable>condition</replaceable>
2527 matching the error that occurred. If a match is found, the
2528 corresponding <replaceable>handler_statements</replaceable> are
2529 executed, and then control passes to the next statement after
2530 <literal>END</>. If no match is found, the error propagates out
2531 as though the <literal>EXCEPTION</> clause were not there at all:
2532 the error can be caught by an enclosing block with
2533 <literal>EXCEPTION</>, or if there is none it aborts processing
2538 The <replaceable>condition</replaceable> names can be any of
2539 those shown in <xref linkend="errcodes-appendix">. A category
2540 name matches any error within its category. The special
2541 condition name <literal>OTHERS</> matches every error type except
2542 <literal>QUERY_CANCELED</>. (It is possible, but often unwise,
2543 to trap <literal>QUERY_CANCELED</> by name.) Condition names are
2544 not case-sensitive. Also, an error condition can be specified
2545 by <literal>SQLSTATE</> code; for example these are equivalent:
2547 WHEN division_by_zero THEN ...
2548 WHEN SQLSTATE '22012' THEN ...
2553 If a new error occurs within the selected
2554 <replaceable>handler_statements</replaceable>, it cannot be caught
2555 by this <literal>EXCEPTION</> clause, but is propagated out.
2556 A surrounding <literal>EXCEPTION</> clause could catch it.
2560 When an error is caught by an <literal>EXCEPTION</> clause,
2561 the local variables of the <application>PL/pgSQL</> function
2562 remain as they were when the error occurred, but all changes
2563 to persistent database state within the block are rolled back.
2564 As an example, consider this fragment:
2567 INSERT INTO mytab(firstname, lastname) VALUES('Tom', 'Jones');
2569 UPDATE mytab SET firstname = 'Joe' WHERE lastname = 'Jones';
2573 WHEN division_by_zero THEN
2574 RAISE NOTICE 'caught division_by_zero';
2579 When control reaches the assignment to <literal>y</>, it will
2580 fail with a <literal>division_by_zero</> error. This will be caught by
2581 the <literal>EXCEPTION</> clause. The value returned in the
2582 <command>RETURN</> statement will be the incremented value of
2583 <literal>x</>, but the effects of the <command>UPDATE</> command will
2584 have been rolled back. The <command>INSERT</> command preceding the
2585 block is not rolled back, however, so the end result is that the database
2586 contains <literal>Tom Jones</> not <literal>Joe Jones</>.
2591 A block containing an <literal>EXCEPTION</> clause is significantly
2592 more expensive to enter and exit than a block without one. Therefore,
2593 don't use <literal>EXCEPTION</> without need.
2597 <example id="plpgsql-upsert-example">
2598 <title>Exceptions with <command>UPDATE</>/<command>INSERT</></title>
2601 This example uses exception handling to perform either
2602 <command>UPDATE</> or <command>INSERT</>, as appropriate:
2605 CREATE TABLE db (a INT PRIMARY KEY, b TEXT);
2607 CREATE FUNCTION merge_db(key INT, data TEXT) RETURNS VOID AS
2611 -- first try to update the key
2612 UPDATE db SET b = data WHERE a = key;
2616 -- not there, so try to insert the key
2617 -- if someone else inserts the same key concurrently,
2618 -- we could get a unique-key failure
2620 INSERT INTO db(a,b) VALUES (key, data);
2622 EXCEPTION WHEN unique_violation THEN
2623 -- Do nothing, and loop to try the UPDATE again.
2630 SELECT merge_db(1, 'david');
2631 SELECT merge_db(1, 'dennis');
2634 This coding assumes the <literal>unique_violation</> error is caused by
2635 the <command>INSERT</>, and not by, say, an <command>INSERT</> in a
2636 trigger function on the table. It might also misbehave if there is
2637 more than one unique index on the table, since it will retry the
2638 operation regardless of which index caused the error.
2639 More safety could be had by using the
2640 features discussed next to check that the trapped error was the one
2646 <sect2 id="plpgsql-diagnostics">
2647 <title>Getting Diagnostics Information</title>
2650 <primary>diagnostics</primary>
2651 <secondary>in PL/pgSQL</secondary>
2654 <sect3 id="plpgsql-exception-diagnostics">
2655 <title>Obtaining information about an error</title>
2658 Exception handlers frequently need to identify the specific error that
2659 occurred. There are two ways to get information about the current
2660 exception in <application>PL/pgSQL</>: special variables and the
2661 <command>GET STACKED DIAGNOSTICS</command> command.
2665 Within an exception handler, the special variable
2666 <varname>SQLSTATE</varname> contains the error code that corresponds to
2667 the exception that was raised (refer to <xref linkend="errcodes-table">
2668 for a list of possible error codes). The special variable
2669 <varname>SQLERRM</varname> contains the error message associated with the
2670 exception. These variables are undefined outside exception handlers.
2674 Within an exception handler, one may also retrieve
2675 information about the current exception by using the
2676 <command>GET STACKED DIAGNOSTICS</command> command, which has the form:
2679 GET STACKED DIAGNOSTICS <replaceable>variable</replaceable> { = | := } <replaceable>item</replaceable> <optional> , ... </optional>;
2682 Each <replaceable>item</replaceable> is a key word identifying a status
2683 value to be assigned to the specified variable (which should be
2684 of the right data type to receive it). The currently available
2685 status items are shown in <xref linkend="plpgsql-exception-diagnostics-values">.
2688 <table id="plpgsql-exception-diagnostics-values">
2689 <title>Error diagnostics values</title>
2695 <entry>Description</entry>
2700 <entry><literal>RETURNED_SQLSTATE</literal></entry>
2702 <entry>the SQLSTATE error code of the exception</entry>
2705 <entry><literal>COLUMN_NAME</literal></entry>
2707 <entry>the name of column related to exception</entry>
2710 <entry><literal>CONSTRAINT_NAME</literal></entry>
2712 <entry>the name of constraint related to exception</entry>
2715 <entry><literal>PG_DATATYPE_NAME</literal></entry>
2717 <entry>the name of datatype related to exception</entry>
2720 <entry><literal>MESSAGE_TEXT</literal></entry>
2722 <entry>the text of the exception's primary message</entry>
2725 <entry><literal>TABLE_NAME</literal></entry>
2727 <entry>the name of table related to exception</entry>
2730 <entry><literal>SCHEMA_NAME</literal></entry>
2732 <entry>the name of schema related to exception</entry>
2735 <entry><literal>PG_EXCEPTION_DETAIL</literal></entry>
2737 <entry>the text of the exception's detail message, if any</entry>
2740 <entry><literal>PG_EXCEPTION_HINT</literal></entry>
2742 <entry>the text of the exception's hint message, if any</entry>
2745 <entry><literal>PG_EXCEPTION_CONTEXT</literal></entry>
2747 <entry>line(s) of text describing the call stack</entry>
2754 If the exception did not set a value for an item, an empty string
2766 -- some processing which might cause an exception
2768 EXCEPTION WHEN OTHERS THEN
2769 GET STACKED DIAGNOSTICS text_var1 = MESSAGE_TEXT,
2770 text_var2 = PG_EXCEPTION_DETAIL,
2771 text_var3 = PG_EXCEPTION_HINT;
2777 <sect3 id="plpgsql-get-diagnostics-context">
2778 <title>Obtaining the call stack context information</title>
2783 GET <optional> CURRENT </optional> DIAGNOSTICS <replaceable>variable</replaceable> { = | := } <replaceable>PG_CONTEXT</replaceable> <optional> , ... </optional>;
2787 Calling <command>GET DIAGNOSTICS</command> with status
2788 item <varname>PG_CONTEXT</> will return a text string with line(s) of
2789 text describing the call stack. The first row refers to the
2790 current function and currently executing <command>GET DIAGNOSTICS</command>
2791 command. The second and any subsequent rows refer to the calling functions
2795 CREATE OR REPLACE FUNCTION public.outer_func() RETURNS integer AS $$
2797 RETURN inner_func();
2799 $$ LANGUAGE plpgsql;
2801 CREATE OR REPLACE FUNCTION public.inner_func() RETURNS integer AS $$
2805 GET DIAGNOSTICS stack = PG_CONTEXT;
2806 RAISE NOTICE E'--- Call Stack ---\n%', stack;
2809 $$ LANGUAGE plpgsql;
2811 SELECT outer_func();
2813 NOTICE: --- Call Stack ---
2814 PL/pgSQL function inner_func() line 4 at GET DIAGNOSTICS
2815 PL/pgSQL function outer_func() line 3 at RETURN
2827 <sect1 id="plpgsql-cursors">
2828 <title>Cursors</title>
2830 <indexterm zone="plpgsql-cursors">
2831 <primary>cursor</primary>
2832 <secondary>in PL/pgSQL</secondary>
2836 Rather than executing a whole query at once, it is possible to set
2837 up a <firstterm>cursor</> that encapsulates the query, and then read
2838 the query result a few rows at a time. One reason for doing this is
2839 to avoid memory overrun when the result contains a large number of
2840 rows. (However, <application>PL/pgSQL</> users do not normally need
2841 to worry about that, since <literal>FOR</> loops automatically use a cursor
2842 internally to avoid memory problems.) A more interesting usage is to
2843 return a reference to a cursor that a function has created, allowing the
2844 caller to read the rows. This provides an efficient way to return
2845 large row sets from functions.
2848 <sect2 id="plpgsql-cursor-declarations">
2849 <title>Declaring Cursor Variables</title>
2852 All access to cursors in <application>PL/pgSQL</> goes through
2853 cursor variables, which are always of the special data type
2854 <type>refcursor</>. One way to create a cursor variable
2855 is just to declare it as a variable of type <type>refcursor</>.
2856 Another way is to use the cursor declaration syntax,
2857 which in general is:
2859 <replaceable>name</replaceable> <optional> <optional> NO </optional> SCROLL </optional> CURSOR <optional> ( <replaceable>arguments</replaceable> ) </optional> FOR <replaceable>query</replaceable>;
2861 (<literal>FOR</> can be replaced by <literal>IS</> for
2862 <productname>Oracle</productname> compatibility.)
2863 If <literal>SCROLL</> is specified, the cursor will be capable of
2864 scrolling backward; if <literal>NO SCROLL</> is specified, backward
2865 fetches will be rejected; if neither specification appears, it is
2866 query-dependent whether backward fetches will be allowed.
2867 <replaceable>arguments</replaceable>, if specified, is a
2868 comma-separated list of pairs <literal><replaceable>name</replaceable>
2869 <replaceable>datatype</replaceable></literal> that define names to be
2870 replaced by parameter values in the given query. The actual
2871 values to substitute for these names will be specified later,
2872 when the cursor is opened.
2879 curs2 CURSOR FOR SELECT * FROM tenk1;
2880 curs3 CURSOR (key integer) FOR SELECT * FROM tenk1 WHERE unique1 = key;
2882 All three of these variables have the data type <type>refcursor</>,
2883 but the first can be used with any query, while the second has
2884 a fully specified query already <firstterm>bound</> to it, and the last
2885 has a parameterized query bound to it. (<literal>key</> will be
2886 replaced by an integer parameter value when the cursor is opened.)
2887 The variable <literal>curs1</>
2888 is said to be <firstterm>unbound</> since it is not bound to
2889 any particular query.
2893 <sect2 id="plpgsql-cursor-opening">
2894 <title>Opening Cursors</title>
2897 Before a cursor can be used to retrieve rows, it must be
2898 <firstterm>opened</>. (This is the equivalent action to the SQL
2899 command <command>DECLARE CURSOR</>.) <application>PL/pgSQL</> has
2900 three forms of the <command>OPEN</> statement, two of which use unbound
2901 cursor variables while the third uses a bound cursor variable.
2906 Bound cursor variables can also be used without explicitly opening the cursor,
2907 via the <command>FOR</> statement described in
2908 <xref linkend="plpgsql-cursor-for-loop">.
2913 <title><command>OPEN FOR</command> <replaceable>query</replaceable></title>
2916 OPEN <replaceable>unbound_cursorvar</replaceable> <optional> <optional> NO </optional> SCROLL </optional> FOR <replaceable>query</replaceable>;
2920 The cursor variable is opened and given the specified query to
2921 execute. The cursor cannot be open already, and it must have been
2922 declared as an unbound cursor variable (that is, as a simple
2923 <type>refcursor</> variable). The query must be a
2924 <command>SELECT</command>, or something else that returns rows
2925 (such as <command>EXPLAIN</>). The query
2926 is treated in the same way as other SQL commands in
2927 <application>PL/pgSQL</>: <application>PL/pgSQL</>
2928 variable names are substituted, and the query plan is cached for
2929 possible reuse. When a <application>PL/pgSQL</>
2930 variable is substituted into the cursor query, the value that is
2931 substituted is the one it has at the time of the <command>OPEN</>;
2932 subsequent changes to the variable will not affect the cursor's
2934 The <literal>SCROLL</> and <literal>NO SCROLL</>
2935 options have the same meanings as for a bound cursor.
2941 OPEN curs1 FOR SELECT * FROM foo WHERE key = mykey;
2947 <title><command>OPEN FOR EXECUTE</command></title>
2950 OPEN <replaceable>unbound_cursorvar</replaceable> <optional> <optional> NO </optional> SCROLL </optional> FOR EXECUTE <replaceable class="command">query_string</replaceable>
2951 <optional> USING <replaceable>expression</replaceable> <optional>, ... </optional> </optional>;
2955 The cursor variable is opened and given the specified query to
2956 execute. The cursor cannot be open already, and it must have been
2957 declared as an unbound cursor variable (that is, as a simple
2958 <type>refcursor</> variable). The query is specified as a string
2959 expression, in the same way as in the <command>EXECUTE</command>
2960 command. As usual, this gives flexibility so the query plan can vary
2961 from one run to the next (see <xref linkend="plpgsql-plan-caching">),
2962 and it also means that variable substitution is not done on the
2963 command string. As with <command>EXECUTE</command>, parameter values
2964 can be inserted into the dynamic command via <literal>USING</>.
2965 The <literal>SCROLL</> and
2966 <literal>NO SCROLL</> options have the same meanings as for a bound
2973 OPEN curs1 FOR EXECUTE 'SELECT * FROM ' || quote_ident(tabname)
2974 || ' WHERE col1 = $1' USING keyvalue;
2976 In this example, the table name is inserted into the query textually,
2977 so use of <function>quote_ident()</> is recommended to guard against
2978 SQL injection. The comparison value for <literal>col1</> is inserted
2979 via a <literal>USING</> parameter, so it needs no quoting.
2983 <sect3 id="plpgsql-open-bound-cursor">
2984 <title>Opening a Bound Cursor</title>
2987 OPEN <replaceable>bound_cursorvar</replaceable> <optional> ( <optional> <replaceable>argument_name</replaceable> := </optional> <replaceable>argument_value</replaceable> <optional>, ...</optional> ) </optional>;
2991 This form of <command>OPEN</command> is used to open a cursor
2992 variable whose query was bound to it when it was declared. The
2993 cursor cannot be open already. A list of actual argument value
2994 expressions must appear if and only if the cursor was declared to
2995 take arguments. These values will be substituted in the query.
2999 The query plan for a bound cursor is always considered cacheable;
3000 there is no equivalent of <command>EXECUTE</command> in this case.
3001 Notice that <literal>SCROLL</> and <literal>NO SCROLL</> cannot be
3002 specified in <command>OPEN</>, as the cursor's scrolling
3003 behavior was already determined.
3007 Argument values can be passed using either <firstterm>positional</firstterm>
3008 or <firstterm>named</firstterm> notation. In positional
3009 notation, all arguments are specified in order. In named notation,
3010 each argument's name is specified using <literal>:=</literal> to
3011 separate it from the argument expression. Similar to calling
3012 functions, described in <xref linkend="sql-syntax-calling-funcs">, it
3013 is also allowed to mix positional and named notation.
3017 Examples (these use the cursor declaration examples above):
3021 OPEN curs3(key := 42);
3026 Because variable substitution is done on a bound cursor's query,
3027 there are really two ways to pass values into the cursor: either
3028 with an explicit argument to <command>OPEN</>, or implicitly by
3029 referencing a <application>PL/pgSQL</> variable in the query.
3030 However, only variables declared before the bound cursor was
3031 declared will be substituted into it. In either case the value to
3032 be passed is determined at the time of the <command>OPEN</>.
3033 For example, another way to get the same effect as the
3034 <literal>curs3</> example above is
3038 curs4 CURSOR FOR SELECT * FROM tenk1 WHERE unique1 = key;
3047 <sect2 id="plpgsql-cursor-using">
3048 <title>Using Cursors</title>
3051 Once a cursor has been opened, it can be manipulated with the
3052 statements described here.
3056 These manipulations need not occur in the same function that
3057 opened the cursor to begin with. You can return a <type>refcursor</>
3058 value out of a function and let the caller operate on the cursor.
3059 (Internally, a <type>refcursor</> value is simply the string name
3060 of a so-called portal containing the active query for the cursor. This name
3061 can be passed around, assigned to other <type>refcursor</> variables,
3062 and so on, without disturbing the portal.)
3066 All portals are implicitly closed at transaction end. Therefore
3067 a <type>refcursor</> value is usable to reference an open cursor
3068 only until the end of the transaction.
3072 <title><literal>FETCH</></title>
3075 FETCH <optional> <replaceable>direction</replaceable> { FROM | IN } </optional> <replaceable>cursor</replaceable> INTO <replaceable>target</replaceable>;
3079 <command>FETCH</command> retrieves the next row from the
3080 cursor into a target, which might be a row variable, a record
3081 variable, or a comma-separated list of simple variables, just like
3082 <command>SELECT INTO</command>. If there is no next row, the
3083 target is set to NULL(s). As with <command>SELECT
3084 INTO</command>, the special variable <literal>FOUND</literal> can
3085 be checked to see whether a row was obtained or not.
3089 The <replaceable>direction</replaceable> clause can be any of the
3090 variants allowed in the SQL <xref linkend="sql-fetch">
3091 command except the ones that can fetch
3092 more than one row; namely, it can be
3097 <literal>ABSOLUTE</> <replaceable>count</replaceable>,
3098 <literal>RELATIVE</> <replaceable>count</replaceable>,
3099 <literal>FORWARD</>, or
3100 <literal>BACKWARD</>.
3101 Omitting <replaceable>direction</replaceable> is the same
3102 as specifying <literal>NEXT</>.
3103 <replaceable>direction</replaceable> values that require moving
3104 backward are likely to fail unless the cursor was declared or opened
3105 with the <literal>SCROLL</> option.
3109 <replaceable>cursor</replaceable> must be the name of a <type>refcursor</>
3110 variable that references an open cursor portal.
3116 FETCH curs1 INTO rowvar;
3117 FETCH curs2 INTO foo, bar, baz;
3118 FETCH LAST FROM curs3 INTO x, y;
3119 FETCH RELATIVE -2 FROM curs4 INTO x;
3125 <title><literal>MOVE</></title>
3128 MOVE <optional> <replaceable>direction</replaceable> { FROM | IN } </optional> <replaceable>cursor</replaceable>;
3132 <command>MOVE</command> repositions a cursor without retrieving
3133 any data. <command>MOVE</command> works exactly like the
3134 <command>FETCH</command> command, except it only repositions the
3135 cursor and does not return the row moved to. As with <command>SELECT
3136 INTO</command>, the special variable <literal>FOUND</literal> can
3137 be checked to see whether there was a next row to move to.
3141 The <replaceable>direction</replaceable> clause can be any of the
3142 variants allowed in the SQL <xref linkend="sql-fetch">
3148 <literal>ABSOLUTE</> <replaceable>count</replaceable>,
3149 <literal>RELATIVE</> <replaceable>count</replaceable>,
3151 <literal>FORWARD</> <optional> <replaceable>count</replaceable> | <literal>ALL</> </optional>, or
3152 <literal>BACKWARD</> <optional> <replaceable>count</replaceable> | <literal>ALL</> </optional>.
3153 Omitting <replaceable>direction</replaceable> is the same
3154 as specifying <literal>NEXT</>.
3155 <replaceable>direction</replaceable> values that require moving
3156 backward are likely to fail unless the cursor was declared or opened
3157 with the <literal>SCROLL</> option.
3164 MOVE LAST FROM curs3;
3165 MOVE RELATIVE -2 FROM curs4;
3166 MOVE FORWARD 2 FROM curs4;
3172 <title><literal>UPDATE/DELETE WHERE CURRENT OF</></title>
3175 UPDATE <replaceable>table</replaceable> SET ... WHERE CURRENT OF <replaceable>cursor</replaceable>;
3176 DELETE FROM <replaceable>table</replaceable> WHERE CURRENT OF <replaceable>cursor</replaceable>;
3180 When a cursor is positioned on a table row, that row can be updated
3181 or deleted using the cursor to identify the row. There are
3182 restrictions on what the cursor's query can be (in particular,
3183 no grouping) and it's best to use <literal>FOR UPDATE</> in the
3184 cursor. For more information see the
3185 <xref linkend="sql-declare">
3192 UPDATE foo SET dataval = myval WHERE CURRENT OF curs1;
3198 <title><literal>CLOSE</></title>
3201 CLOSE <replaceable>cursor</replaceable>;
3205 <command>CLOSE</command> closes the portal underlying an open
3206 cursor. This can be used to release resources earlier than end of
3207 transaction, or to free up the cursor variable to be opened again.
3219 <title>Returning Cursors</title>
3222 <application>PL/pgSQL</> functions can return cursors to the
3223 caller. This is useful to return multiple rows or columns,
3224 especially with very large result sets. To do this, the function
3225 opens the cursor and returns the cursor name to the caller (or simply
3226 opens the cursor using a portal name specified by or otherwise known
3227 to the caller). The caller can then fetch rows from the cursor. The
3228 cursor can be closed by the caller, or it will be closed automatically
3229 when the transaction closes.
3233 The portal name used for a cursor can be specified by the
3234 programmer or automatically generated. To specify a portal name,
3235 simply assign a string to the <type>refcursor</> variable before
3236 opening it. The string value of the <type>refcursor</> variable
3237 will be used by <command>OPEN</> as the name of the underlying portal.
3238 However, if the <type>refcursor</> variable is null,
3239 <command>OPEN</> automatically generates a name that does not
3240 conflict with any existing portal, and assigns it to the
3241 <type>refcursor</> variable.
3246 A bound cursor variable is initialized to the string value
3247 representing its name, so that the portal name is the same as
3248 the cursor variable name, unless the programmer overrides it
3249 by assignment before opening the cursor. But an unbound cursor
3250 variable defaults to the null value initially, so it will receive
3251 an automatically-generated unique name, unless overridden.
3256 The following example shows one way a cursor name can be supplied by
3260 CREATE TABLE test (col text);
3261 INSERT INTO test VALUES ('123');
3263 CREATE FUNCTION reffunc(refcursor) RETURNS refcursor AS '
3265 OPEN $1 FOR SELECT col FROM test;
3271 SELECT reffunc('funccursor');
3272 FETCH ALL IN funccursor;
3278 The following example uses automatic cursor name generation:
3281 CREATE FUNCTION reffunc2() RETURNS refcursor AS '
3285 OPEN ref FOR SELECT col FROM test;
3290 -- need to be in a transaction to use cursors.
3295 --------------------
3296 <unnamed cursor 1>
3299 FETCH ALL IN "<unnamed cursor 1>";
3305 The following example shows one way to return multiple cursors
3306 from a single function:
3309 CREATE FUNCTION myfunc(refcursor, refcursor) RETURNS SETOF refcursor AS $$
3311 OPEN $1 FOR SELECT * FROM table_1;
3313 OPEN $2 FOR SELECT * FROM table_2;
3316 $$ LANGUAGE plpgsql;
3318 -- need to be in a transaction to use cursors.
3321 SELECT * FROM myfunc('a', 'b');
3331 <sect2 id="plpgsql-cursor-for-loop">
3332 <title>Looping Through a Cursor's Result</title>
3335 There is a variant of the <command>FOR</> statement that allows
3336 iterating through the rows returned by a cursor. The syntax is:
3339 <optional> <<<replaceable>label</replaceable>>> </optional>
3340 FOR <replaceable>recordvar</replaceable> IN <replaceable>bound_cursorvar</replaceable> <optional> ( <optional> <replaceable>argument_name</replaceable> := </optional> <replaceable>argument_value</replaceable> <optional>, ...</optional> ) </optional> LOOP
3341 <replaceable>statements</replaceable>
3342 END LOOP <optional> <replaceable>label</replaceable> </optional>;
3345 The cursor variable must have been bound to some query when it was
3346 declared, and it <emphasis>cannot</> be open already. The
3347 <command>FOR</> statement automatically opens the cursor, and it closes
3348 the cursor again when the loop exits. A list of actual argument value
3349 expressions must appear if and only if the cursor was declared to take
3350 arguments. These values will be substituted in the query, in just
3351 the same way as during an <command>OPEN</> (see <xref
3352 linkend="plpgsql-open-bound-cursor">).
3356 The variable <replaceable>recordvar</replaceable> is automatically
3357 defined as type <type>record</> and exists only inside the loop (any
3358 existing definition of the variable name is ignored within the loop).
3359 Each row returned by the cursor is successively assigned to this
3360 record variable and the loop body is executed.
3366 <sect1 id="plpgsql-errors-and-messages">
3367 <title>Errors and Messages</title>
3370 <primary>RAISE</primary>
3374 <primary>reporting errors</primary>
3375 <secondary>in PL/pgSQL</secondary>
3379 Use the <command>RAISE</command> statement to report messages and
3383 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>;
3384 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>;
3385 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>;
3386 RAISE <optional> <replaceable class="parameter">level</replaceable> </optional> USING <replaceable class="parameter">option</replaceable> = <replaceable class="parameter">expression</replaceable> <optional>, ... </optional>;
3390 The <replaceable class="parameter">level</replaceable> option specifies
3391 the error severity. Allowed levels are <literal>DEBUG</literal>,
3392 <literal>LOG</literal>, <literal>INFO</literal>,
3393 <literal>NOTICE</literal>, <literal>WARNING</literal>,
3394 and <literal>EXCEPTION</literal>, with <literal>EXCEPTION</literal>
3396 <literal>EXCEPTION</literal> raises an error (which normally aborts the
3397 current transaction); the other levels only generate messages of different
3399 Whether messages of a particular priority are reported to the client,
3400 written to the server log, or both is controlled by the
3401 <xref linkend="guc-log-min-messages"> and
3402 <xref linkend="guc-client-min-messages"> configuration
3403 variables. See <xref linkend="runtime-config"> for more
3408 After <replaceable class="parameter">level</replaceable> if any,
3409 you can write a <replaceable class="parameter">format</replaceable>
3410 (which must be a simple string literal, not an expression). The
3411 format string specifies the error message text to be reported.
3412 The format string can be followed
3413 by optional argument expressions to be inserted into the message.
3414 Inside the format string, <literal>%</literal> is replaced by the
3415 string representation of the next optional argument's value. Write
3416 <literal>%%</literal> to emit a literal <literal>%</literal>.
3420 In this example, the value of <literal>v_job_id</> will replace the
3421 <literal>%</literal> in the string:
3423 RAISE NOTICE 'Calling cs_create_job(%)', v_job_id;
3428 You can attach additional information to the error report by writing
3429 <literal>USING</> followed by <replaceable
3430 class="parameter">option</replaceable> = <replaceable
3431 class="parameter">expression</replaceable> items. Each
3432 <replaceable class="parameter">expression</replaceable> can be any
3433 string-valued expression. The allowed <replaceable
3434 class="parameter">option</replaceable> key words are:
3436 <variablelist id="raise-using-options">
3438 <term><literal>MESSAGE</literal></term>
3440 <para>Sets the error message text. This option can't be used in the
3441 form of <command>RAISE</> that includes a format string
3442 before <literal>USING</>.</para>
3447 <term><literal>DETAIL</literal></term>
3449 <para>Supplies an error detail message.</para>
3454 <term><literal>HINT</literal></term>
3456 <para>Supplies a hint message.</para>
3461 <term><literal>ERRCODE</literal></term>
3463 <para>Specifies the error code (SQLSTATE) to report, either by condition
3464 name, as shown in <xref linkend="errcodes-appendix">, or directly as a
3465 five-character SQLSTATE code.</para>
3470 <term><literal>COLUMN</literal></term>
3471 <term><literal>CONSTRAINT</literal></term>
3472 <term><literal>DATATYPE</literal></term>
3473 <term><literal>TABLE</literal></term>
3474 <term><literal>SCHEMA</literal></term>
3476 <para>Supplies the name of a related object.</para>
3483 This example will abort the transaction with the given error message
3486 RAISE EXCEPTION 'Nonexistent ID --> %', user_id
3487 USING HINT = 'Please check your user ID';
3492 These two examples show equivalent ways of setting the SQLSTATE:
3494 RAISE 'Duplicate user ID: %', user_id USING ERRCODE = 'unique_violation';
3495 RAISE 'Duplicate user ID: %', user_id USING ERRCODE = '23505';
3500 There is a second <command>RAISE</> syntax in which the main argument
3501 is the condition name or SQLSTATE to be reported, for example:
3503 RAISE division_by_zero;
3504 RAISE SQLSTATE '22012';
3506 In this syntax, <literal>USING</> can be used to supply a custom
3507 error message, detail, or hint. Another way to do the earlier
3510 RAISE unique_violation USING MESSAGE = 'Duplicate user ID: ' || user_id;
3515 Still another variant is to write <literal>RAISE USING</> or <literal>RAISE
3516 <replaceable class="parameter">level</replaceable> USING</> and put
3517 everything else into the <literal>USING</> list.
3521 The last variant of <command>RAISE</> has no parameters at all.
3522 This form can only be used inside a <literal>BEGIN</> block's
3523 <literal>EXCEPTION</> clause;
3524 it causes the error currently being handled to be re-thrown.
3529 Before <productname>PostgreSQL</> 9.1, <command>RAISE</> without
3530 parameters was interpreted as re-throwing the error from the block
3531 containing the active exception handler. Thus an <literal>EXCEPTION</>
3532 clause nested within that handler could not catch it, even if the
3533 <command>RAISE</> was within the nested <literal>EXCEPTION</> clause's
3534 block. This was deemed surprising as well as being incompatible with
3540 If no condition name nor SQLSTATE is specified in a
3541 <command>RAISE EXCEPTION</command> command, the default is to use
3542 <literal>RAISE_EXCEPTION</> (<literal>P0001</>). If no message
3543 text is specified, the default is to use the condition name or
3544 SQLSTATE as message text.
3549 When specifying an error code by SQLSTATE code, you are not
3550 limited to the predefined error codes, but can select any
3551 error code consisting of five digits and/or upper-case ASCII
3552 letters, other than <literal>00000</>. It is recommended that
3553 you avoid throwing error codes that end in three zeroes, because
3554 these are category codes and can only be trapped by trapping
3561 <sect1 id="plpgsql-trigger">
3562 <title>Trigger Procedures</title>
3564 <indexterm zone="plpgsql-trigger">
3565 <primary>trigger</primary>
3566 <secondary>in PL/pgSQL</secondary>
3569 <sect2 id="plpgsql-dml-trigger">
3570 <title>Triggers on data changes</title>
3573 <application>PL/pgSQL</application> can be used to define trigger
3574 procedures. A trigger procedure is created with the
3575 <command>CREATE FUNCTION</> command, declaring it as a function with
3576 no arguments and a return type of <type>trigger</type>. Note that
3577 the function must be declared with no arguments even if it expects
3578 to receive arguments specified in <command>CREATE TRIGGER</> —
3579 trigger arguments are passed via <varname>TG_ARGV</>, as described
3584 When a <application>PL/pgSQL</application> function is called as a
3585 trigger, several special variables are created automatically in the
3586 top-level block. They are:
3590 <term><varname>NEW</varname></term>
3593 Data type <type>RECORD</type>; variable holding the new
3594 database row for <command>INSERT</>/<command>UPDATE</> operations in row-level
3595 triggers. This variable is unassigned in statement-level triggers
3596 and for <command>DELETE</command> operations.
3602 <term><varname>OLD</varname></term>
3605 Data type <type>RECORD</type>; variable holding the old
3606 database row for <command>UPDATE</>/<command>DELETE</> operations in row-level
3607 triggers. This variable is unassigned in statement-level triggers
3608 and for <command>INSERT</command> operations.
3614 <term><varname>TG_NAME</varname></term>
3617 Data type <type>name</type>; variable that contains the name of the trigger actually
3624 <term><varname>TG_WHEN</varname></term>
3627 Data type <type>text</type>; a string of
3628 <literal>BEFORE</literal>, <literal>AFTER</literal>, or
3629 <literal>INSTEAD OF</literal>, depending on the trigger's definition.
3635 <term><varname>TG_LEVEL</varname></term>
3638 Data type <type>text</type>; a string of either
3639 <literal>ROW</literal> or <literal>STATEMENT</literal>
3640 depending on the trigger's definition.
3646 <term><varname>TG_OP</varname></term>
3649 Data type <type>text</type>; a string of
3650 <literal>INSERT</literal>, <literal>UPDATE</literal>,
3651 <literal>DELETE</literal>, or <literal>TRUNCATE</>
3652 telling for which operation the trigger was fired.
3658 <term><varname>TG_RELID</varname></term>
3661 Data type <type>oid</type>; the object ID of the table that caused the
3668 <term><varname>TG_RELNAME</varname></term>
3671 Data type <type>name</type>; the name of the table that caused the trigger
3672 invocation. This is now deprecated, and could disappear in a future
3673 release. Use <literal>TG_TABLE_NAME</> instead.
3679 <term><varname>TG_TABLE_NAME</varname></term>
3682 Data type <type>name</type>; the name of the table that
3683 caused the trigger invocation.
3689 <term><varname>TG_TABLE_SCHEMA</varname></term>
3692 Data type <type>name</type>; the name of the schema of the
3693 table that caused the trigger invocation.
3699 <term><varname>TG_NARGS</varname></term>
3702 Data type <type>integer</type>; the number of arguments given to the trigger
3703 procedure in the <command>CREATE TRIGGER</command> statement.
3709 <term><varname>TG_ARGV[]</varname></term>
3712 Data type array of <type>text</type>; the arguments from
3713 the <command>CREATE TRIGGER</command> statement.
3714 The index counts from 0. Invalid
3715 indexes (less than 0 or greater than or equal to <varname>tg_nargs</>)
3716 result in a null value.
3724 A trigger function must return either <symbol>NULL</symbol> or a
3725 record/row value having exactly the structure of the table the
3726 trigger was fired for.
3730 Row-level triggers fired <literal>BEFORE</> can return null to signal the
3731 trigger manager to skip the rest of the operation for this row
3732 (i.e., subsequent triggers are not fired, and the
3733 <command>INSERT</>/<command>UPDATE</>/<command>DELETE</> does not occur
3734 for this row). If a nonnull
3735 value is returned then the operation proceeds with that row value.
3736 Returning a row value different from the original value
3737 of <varname>NEW</> alters the row that will be inserted or
3738 updated. Thus, if the trigger function wants the triggering
3739 action to succeed normally without altering the row
3740 value, <varname>NEW</varname> (or a value equal thereto) has to be
3741 returned. To alter the row to be stored, it is possible to
3742 replace single values directly in <varname>NEW</> and return the
3743 modified <varname>NEW</>, or to build a complete new record/row to
3744 return. In the case of a before-trigger
3745 on <command>DELETE</command>, the returned value has no direct
3746 effect, but it has to be nonnull to allow the trigger action to
3747 proceed. Note that <varname>NEW</varname> is null
3748 in <command>DELETE</command> triggers, so returning that is
3749 usually not sensible. The usual idiom in <command>DELETE</command>
3750 triggers is to return <varname>OLD</varname>.
3754 <literal>INSTEAD OF</> triggers (which are always row-level triggers,
3755 and may only be used on views) can return null to signal that they did
3756 not perform any updates, and that the rest of the operation for this
3757 row should be skipped (i.e., subsequent triggers are not fired, and the
3758 row is not counted in the rows-affected status for the surrounding
3759 <command>INSERT</>/<command>UPDATE</>/<command>DELETE</>).
3760 Otherwise a nonnull value should be returned, to signal
3761 that the trigger performed the requested operation. For
3762 <command>INSERT</> and <command>UPDATE</> operations, the return value
3763 should be <varname>NEW</>, which the trigger function may modify to
3764 support <command>INSERT RETURNING</> and <command>UPDATE RETURNING</>
3765 (this will also affect the row value passed to any subsequent triggers).
3766 For <command>DELETE</> operations, the return value should be
3771 The return value of a row-level trigger
3772 fired <literal>AFTER</literal> or a statement-level trigger
3773 fired <literal>BEFORE</> or <literal>AFTER</> is
3774 always ignored; it might as well be null. However, any of these types of
3775 triggers might still abort the entire operation by raising an error.
3779 <xref linkend="plpgsql-trigger-example"> shows an example of a
3780 trigger procedure in <application>PL/pgSQL</application>.
3783 <example id="plpgsql-trigger-example">
3784 <title>A <application>PL/pgSQL</application> Trigger Procedure</title>
3787 This example trigger ensures that any time a row is inserted or updated
3788 in the table, the current user name and time are stamped into the
3789 row. And it checks that an employee's name is given and that the
3790 salary is a positive value.
3797 last_date timestamp,
3801 CREATE FUNCTION emp_stamp() RETURNS trigger AS $emp_stamp$
3803 -- Check that empname and salary are given
3804 IF NEW.empname IS NULL THEN
3805 RAISE EXCEPTION 'empname cannot be null';
3807 IF NEW.salary IS NULL THEN
3808 RAISE EXCEPTION '% cannot have null salary', NEW.empname;
3811 -- Who works for us when she must pay for it?
3812 IF NEW.salary < 0 THEN
3813 RAISE EXCEPTION '% cannot have a negative salary', NEW.empname;
3816 -- Remember who changed the payroll when
3817 NEW.last_date := current_timestamp;
3818 NEW.last_user := current_user;
3821 $emp_stamp$ LANGUAGE plpgsql;
3823 CREATE TRIGGER emp_stamp BEFORE INSERT OR UPDATE ON emp
3824 FOR EACH ROW EXECUTE PROCEDURE emp_stamp();
3829 Another way to log changes to a table involves creating a new table that
3830 holds a row for each insert, update, or delete that occurs. This approach
3831 can be thought of as auditing changes to a table.
3832 <xref linkend="plpgsql-trigger-audit-example"> shows an example of an
3833 audit trigger procedure in <application>PL/pgSQL</application>.
3836 <example id="plpgsql-trigger-audit-example">
3837 <title>A <application>PL/pgSQL</application> Trigger Procedure For Auditing</title>
3840 This example trigger ensures that any insert, update or delete of a row
3841 in the <literal>emp</literal> table is recorded (i.e., audited) in the <literal>emp_audit</literal> table.
3842 The current time and user name are stamped into the row, together with
3843 the type of operation performed on it.
3848 empname text NOT NULL,
3852 CREATE TABLE emp_audit(
3853 operation char(1) NOT NULL,
3854 stamp timestamp NOT NULL,
3855 userid text NOT NULL,
3856 empname text NOT NULL,
3860 CREATE OR REPLACE FUNCTION process_emp_audit() RETURNS TRIGGER AS $emp_audit$
3863 -- Create a row in emp_audit to reflect the operation performed on emp,
3864 -- make use of the special variable TG_OP to work out the operation.
3866 IF (TG_OP = 'DELETE') THEN
3867 INSERT INTO emp_audit SELECT 'D', now(), user, OLD.*;
3869 ELSIF (TG_OP = 'UPDATE') THEN
3870 INSERT INTO emp_audit SELECT 'U', now(), user, NEW.*;
3872 ELSIF (TG_OP = 'INSERT') THEN
3873 INSERT INTO emp_audit SELECT 'I', now(), user, NEW.*;
3876 RETURN NULL; -- result is ignored since this is an AFTER trigger
3878 $emp_audit$ LANGUAGE plpgsql;
3880 CREATE TRIGGER emp_audit
3881 AFTER INSERT OR UPDATE OR DELETE ON emp
3882 FOR EACH ROW EXECUTE PROCEDURE process_emp_audit();
3887 A variation of the previous example uses a view joining the main table
3888 to the audit table, to show when each entry was last modified. This
3889 approach still records the full audit trail of changes to the table,
3890 but also presents a simplified view of the audit trail, showing just
3891 the last modified timestamp derived from the audit trail for each entry.
3892 <xref linkend="plpgsql-view-trigger-audit-example"> shows an example
3893 of an audit trigger on a view in <application>PL/pgSQL</application>.
3896 <example id="plpgsql-view-trigger-audit-example">
3897 <title>A <application>PL/pgSQL</application> View Trigger Procedure For Auditing</title>
3900 This example uses a trigger on the view to make it updatable, and
3901 ensure that any insert, update or delete of a row in the view is
3902 recorded (i.e., audited) in the <literal>emp_audit</literal> table. The current time
3903 and user name are recorded, together with the type of operation
3904 performed, and the view displays the last modified time of each row.
3909 empname text PRIMARY KEY,
3913 CREATE TABLE emp_audit(
3914 operation char(1) NOT NULL,
3915 userid text NOT NULL,
3916 empname text NOT NULL,
3918 stamp timestamp NOT NULL
3921 CREATE VIEW emp_view AS
3924 max(ea.stamp) AS last_updated
3926 LEFT JOIN emp_audit ea ON ea.empname = e.empname
3929 CREATE OR REPLACE FUNCTION update_emp_view() RETURNS TRIGGER AS $$
3932 -- Perform the required operation on emp, and create a row in emp_audit
3933 -- to reflect the change made to emp.
3935 IF (TG_OP = 'DELETE') THEN
3936 DELETE FROM emp WHERE empname = OLD.empname;
3937 IF NOT FOUND THEN RETURN NULL; END IF;
3939 OLD.last_updated = now();
3940 INSERT INTO emp_audit VALUES('D', user, OLD.*);
3942 ELSIF (TG_OP = 'UPDATE') THEN
3943 UPDATE emp SET salary = NEW.salary WHERE empname = OLD.empname;
3944 IF NOT FOUND THEN RETURN NULL; END IF;
3946 NEW.last_updated = now();
3947 INSERT INTO emp_audit VALUES('U', user, NEW.*);
3949 ELSIF (TG_OP = 'INSERT') THEN
3950 INSERT INTO emp VALUES(NEW.empname, NEW.salary);
3952 NEW.last_updated = now();
3953 INSERT INTO emp_audit VALUES('I', user, NEW.*);
3957 $$ LANGUAGE plpgsql;
3959 CREATE TRIGGER emp_audit
3960 INSTEAD OF INSERT OR UPDATE OR DELETE ON emp_view
3961 FOR EACH ROW EXECUTE PROCEDURE update_emp_view();
3966 One use of triggers is to maintain a summary table
3967 of another table. The resulting summary can be used in place of the
3968 original table for certain queries — often with vastly reduced run
3970 This technique is commonly used in Data Warehousing, where the tables
3971 of measured or observed data (called fact tables) might be extremely large.
3972 <xref linkend="plpgsql-trigger-summary-example"> shows an example of a
3973 trigger procedure in <application>PL/pgSQL</application> that maintains
3974 a summary table for a fact table in a data warehouse.
3978 <example id="plpgsql-trigger-summary-example">
3979 <title>A <application>PL/pgSQL</application> Trigger Procedure For Maintaining A Summary Table</title>
3982 The schema detailed here is partly based on the <emphasis>Grocery Store
3983 </emphasis> example from <emphasis>The Data Warehouse Toolkit</emphasis>
3989 -- Main tables - time dimension and sales fact.
3991 CREATE TABLE time_dimension (
3992 time_key integer NOT NULL,
3993 day_of_week integer NOT NULL,
3994 day_of_month integer NOT NULL,
3995 month integer NOT NULL,
3996 quarter integer NOT NULL,
3997 year integer NOT NULL
3999 CREATE UNIQUE INDEX time_dimension_key ON time_dimension(time_key);
4001 CREATE TABLE sales_fact (
4002 time_key integer NOT NULL,
4003 product_key integer NOT NULL,
4004 store_key integer NOT NULL,
4005 amount_sold numeric(12,2) NOT NULL,
4006 units_sold integer NOT NULL,
4007 amount_cost numeric(12,2) NOT NULL
4009 CREATE INDEX sales_fact_time ON sales_fact(time_key);
4012 -- Summary table - sales by time.
4014 CREATE TABLE sales_summary_bytime (
4015 time_key integer NOT NULL,
4016 amount_sold numeric(15,2) NOT NULL,
4017 units_sold numeric(12) NOT NULL,
4018 amount_cost numeric(15,2) NOT NULL
4020 CREATE UNIQUE INDEX sales_summary_bytime_key ON sales_summary_bytime(time_key);
4023 -- Function and trigger to amend summarized column(s) on UPDATE, INSERT, DELETE.
4025 CREATE OR REPLACE FUNCTION maint_sales_summary_bytime() RETURNS TRIGGER
4026 AS $maint_sales_summary_bytime$
4028 delta_time_key integer;
4029 delta_amount_sold numeric(15,2);
4030 delta_units_sold numeric(12);
4031 delta_amount_cost numeric(15,2);
4034 -- Work out the increment/decrement amount(s).
4035 IF (TG_OP = 'DELETE') THEN
4037 delta_time_key = OLD.time_key;
4038 delta_amount_sold = -1 * OLD.amount_sold;
4039 delta_units_sold = -1 * OLD.units_sold;
4040 delta_amount_cost = -1 * OLD.amount_cost;
4042 ELSIF (TG_OP = 'UPDATE') THEN
4044 -- forbid updates that change the time_key -
4045 -- (probably not too onerous, as DELETE + INSERT is how most
4046 -- changes will be made).
4047 IF ( OLD.time_key != NEW.time_key) THEN
4048 RAISE EXCEPTION 'Update of time_key : % -> % not allowed',
4049 OLD.time_key, NEW.time_key;
4052 delta_time_key = OLD.time_key;
4053 delta_amount_sold = NEW.amount_sold - OLD.amount_sold;
4054 delta_units_sold = NEW.units_sold - OLD.units_sold;
4055 delta_amount_cost = NEW.amount_cost - OLD.amount_cost;
4057 ELSIF (TG_OP = 'INSERT') THEN
4059 delta_time_key = NEW.time_key;
4060 delta_amount_sold = NEW.amount_sold;
4061 delta_units_sold = NEW.units_sold;
4062 delta_amount_cost = NEW.amount_cost;
4067 -- Insert or update the summary row with the new values.
4068 <<insert_update>>
4070 UPDATE sales_summary_bytime
4071 SET amount_sold = amount_sold + delta_amount_sold,
4072 units_sold = units_sold + delta_units_sold,
4073 amount_cost = amount_cost + delta_amount_cost
4074 WHERE time_key = delta_time_key;
4076 EXIT insert_update WHEN found;
4079 INSERT INTO sales_summary_bytime (
4094 WHEN UNIQUE_VIOLATION THEN
4097 END LOOP insert_update;
4102 $maint_sales_summary_bytime$ LANGUAGE plpgsql;
4104 CREATE TRIGGER maint_sales_summary_bytime
4105 AFTER INSERT OR UPDATE OR DELETE ON sales_fact
4106 FOR EACH ROW EXECUTE PROCEDURE maint_sales_summary_bytime();
4108 INSERT INTO sales_fact VALUES(1,1,1,10,3,15);
4109 INSERT INTO sales_fact VALUES(1,2,1,20,5,35);
4110 INSERT INTO sales_fact VALUES(2,2,1,40,15,135);
4111 INSERT INTO sales_fact VALUES(2,3,1,10,1,13);
4112 SELECT * FROM sales_summary_bytime;
4113 DELETE FROM sales_fact WHERE product_key = 1;
4114 SELECT * FROM sales_summary_bytime;
4115 UPDATE sales_fact SET units_sold = units_sold * 2;
4116 SELECT * FROM sales_summary_bytime;
4121 <sect2 id="plpgsql-event-trigger">
4122 <title>Triggers on events</title>
4125 <application>PL/pgSQL</application> can be used to define event
4126 triggers. <productname>PostgreSQL</> requires that a procedure that
4127 is to be called as an event trigger must be declared as a function with
4128 no arguments and a return type of <literal>event_trigger</>.
4132 When a <application>PL/pgSQL</application> function is called as a
4133 event trigger, several special variables are created automatically
4134 in the top-level block. They are:
4138 <term><varname>TG_EVENT</varname></term>
4141 Data type <type>text</type>; a string representing the event the
4142 trigger is fired for.
4148 <term><varname>TG_TAG</varname></term>
4151 Data type <type>text</type>; variable that contains the command tag
4152 for which the trigger is fired.
4160 <xref linkend="plpgsql-event-trigger-example"> shows an example of a
4161 event trigger procedure in <application>PL/pgSQL</application>.
4164 <example id="plpgsql-event-trigger-example">
4165 <title>A <application>PL/pgSQL</application> Event Trigger Procedure</title>
4168 This example trigger simply raises a <literal>NOTICE</literal> message
4169 each time a supported command is executed.
4173 CREATE OR REPLACE FUNCTION snitch() RETURNS event_trigger AS $$
4175 RAISE NOTICE 'snitch: % %', tg_event, tg_tag;
4177 $$ LANGUAGE plpgsql;
4179 CREATE EVENT TRIGGER snitch ON ddl_command_start EXECUTE PROCEDURE snitch();
4186 <sect1 id="plpgsql-implementation">
4187 <title><application>PL/pgSQL</> Under the Hood</title>
4190 This section discusses some implementation details that are
4191 frequently important for <application>PL/pgSQL</> users to know.
4194 <sect2 id="plpgsql-var-subst">
4195 <title>Variable Substitution</title>
4198 SQL statements and expressions within a <application>PL/pgSQL</> function
4199 can refer to variables and parameters of the function. Behind the scenes,
4200 <application>PL/pgSQL</> substitutes query parameters for such references.
4201 Parameters will only be substituted in places where a parameter or
4202 column reference is syntactically allowed. As an extreme case, consider
4203 this example of poor programming style:
4205 INSERT INTO foo (foo) VALUES (foo);
4207 The first occurrence of <literal>foo</> must syntactically be a table
4208 name, so it will not be substituted, even if the function has a variable
4209 named <literal>foo</>. The second occurrence must be the name of a
4210 column of the table, so it will not be substituted either. Only the
4211 third occurrence is a candidate to be a reference to the function's
4217 <productname>PostgreSQL</productname> versions before 9.0 would try
4218 to substitute the variable in all three cases, leading to syntax errors.
4223 Since the names of variables are syntactically no different from the names
4224 of table columns, there can be ambiguity in statements that also refer to
4225 tables: is a given name meant to refer to a table column, or a variable?
4226 Let's change the previous example to
4228 INSERT INTO dest (col) SELECT foo + bar FROM src;
4230 Here, <literal>dest</> and <literal>src</> must be table names, and
4231 <literal>col</> must be a column of <literal>dest</>, but <literal>foo</>
4232 and <literal>bar</> might reasonably be either variables of the function
4233 or columns of <literal>src</>.
4237 By default, <application>PL/pgSQL</> will report an error if a name
4238 in a SQL statement could refer to either a variable or a table column.
4239 You can fix such a problem by renaming the variable or column,
4240 or by qualifying the ambiguous reference, or by telling
4241 <application>PL/pgSQL</> which interpretation to prefer.
4245 The simplest solution is to rename the variable or column.
4246 A common coding rule is to use a
4247 different naming convention for <application>PL/pgSQL</application>
4248 variables than you use for column names. For example,
4249 if you consistently name function variables
4250 <literal>v_<replaceable>something</></literal> while none of your
4251 column names start with <literal>v_</>, no conflicts will occur.
4255 Alternatively you can qualify ambiguous references to make them clear.
4256 In the above example, <literal>src.foo</> would be an unambiguous reference
4257 to the table column. To create an unambiguous reference to a variable,
4258 declare it in a labeled block and use the block's label
4259 (see <xref linkend="plpgsql-structure">). For example,
4261 <<block>>
4266 INSERT INTO dest (col) SELECT block.foo + bar FROM src;
4268 Here <literal>block.foo</> means the variable even if there is a column
4269 <literal>foo</> in <literal>src</>. Function parameters, as well as
4270 special variables such as <literal>FOUND</>, can be qualified by the
4271 function's name, because they are implicitly declared in an outer block
4272 labeled with the function's name.
4276 Sometimes it is impractical to fix all the ambiguous references in a
4277 large body of <application>PL/pgSQL</> code. In such cases you can
4278 specify that <application>PL/pgSQL</> should resolve ambiguous references
4279 as the variable (which is compatible with <application>PL/pgSQL</>'s
4280 behavior before <productname>PostgreSQL</productname> 9.0), or as the
4281 table column (which is compatible with some other systems such as
4282 <productname>Oracle</productname>).
4286 <primary><varname>plpgsql.variable_conflict</> configuration parameter</primary>
4290 To change this behavior on a system-wide basis, set the configuration
4291 parameter <literal>plpgsql.variable_conflict</> to one of
4292 <literal>error</>, <literal>use_variable</>, or
4293 <literal>use_column</> (where <literal>error</> is the factory default).
4294 This parameter affects subsequent compilations
4295 of statements in <application>PL/pgSQL</> functions, but not statements
4296 already compiled in the current session.
4297 Because changing this setting
4298 can cause unexpected changes in the behavior of <application>PL/pgSQL</>
4299 functions, it can only be changed by a superuser.
4303 You can also set the behavior on a function-by-function basis, by
4304 inserting one of these special commands at the start of the function
4307 #variable_conflict error
4308 #variable_conflict use_variable
4309 #variable_conflict use_column
4311 These commands affect only the function they are written in, and override
4312 the setting of <literal>plpgsql.variable_conflict</>. An example is
4314 CREATE FUNCTION stamp_user(id int, comment text) RETURNS void AS $$
4315 #variable_conflict use_variable
4317 curtime timestamp := now();
4319 UPDATE users SET last_modified = curtime, comment = comment
4320 WHERE users.id = id;
4322 $$ LANGUAGE plpgsql;
4324 In the <literal>UPDATE</> command, <literal>curtime</>, <literal>comment</>,
4325 and <literal>id</> will refer to the function's variable and parameters
4326 whether or not <literal>users</> has columns of those names. Notice
4327 that we had to qualify the reference to <literal>users.id</> in the
4328 <literal>WHERE</> clause to make it refer to the table column.
4329 But we did not have to qualify the reference to <literal>comment</>
4330 as a target in the <literal>UPDATE</> list, because syntactically
4331 that must be a column of <literal>users</>. We could write the same
4332 function without depending on the <literal>variable_conflict</> setting
4335 CREATE FUNCTION stamp_user(id int, comment text) RETURNS void AS $$
4338 curtime timestamp := now();
4340 UPDATE users SET last_modified = fn.curtime, comment = stamp_user.comment
4341 WHERE users.id = stamp_user.id;
4343 $$ LANGUAGE plpgsql;
4348 Variable substitution does not happen in the command string given
4349 to <command>EXECUTE</> or one of its variants. If you need to
4350 insert a varying value into such a command, do so as part of
4351 constructing the string value, or use <literal>USING</>, as illustrated in
4352 <xref linkend="plpgsql-statements-executing-dyn">.
4356 Variable substitution currently works only in <command>SELECT</>,
4357 <command>INSERT</>, <command>UPDATE</>, and <command>DELETE</> commands,
4358 because the main SQL engine allows query parameters only in these
4359 commands. To use a non-constant name or value in other statement
4360 types (generically called utility statements), you must construct
4361 the utility statement as a string and <command>EXECUTE</> it.
4366 <sect2 id="plpgsql-plan-caching">
4367 <title>Plan Caching</title>
4370 The <application>PL/pgSQL</> interpreter parses the function's source
4371 text and produces an internal binary instruction tree the first time the
4372 function is called (within each session). The instruction tree
4373 fully translates the
4374 <application>PL/pgSQL</> statement structure, but individual
4375 <acronym>SQL</acronym> expressions and <acronym>SQL</acronym> commands
4376 used in the function are not translated immediately.
4381 <primary>preparing a query</>
4382 <secondary>in PL/pgSQL</>
4384 As each expression and <acronym>SQL</acronym> command is first
4385 executed in the function, the <application>PL/pgSQL</> interpreter
4386 parses and analyzes the command to create a prepared statement,
4387 using the <acronym>SPI</acronym> manager's
4388 <function>SPI_prepare</function> function.
4389 Subsequent visits to that expression or command
4390 reuse the prepared statement. Thus, a function with conditional code
4391 paths that are seldom visited will never incur the overhead of
4392 analyzing those commands that are never executed within the current
4393 session. A disadvantage is that errors
4394 in a specific expression or command cannot be detected until that
4395 part of the function is reached in execution. (Trivial syntax
4396 errors will be detected during the initial parsing pass, but
4397 anything deeper will not be detected until execution.)
4401 <application>PL/pgSQL</> (or more precisely, the SPI manager) can
4402 furthermore attempt to cache the execution plan associated with any
4403 particular prepared statement. If a cached plan is not used, then
4404 a fresh execution plan is generated on each visit to the statement,
4405 and the current parameter values (that is, <application>PL/pgSQL</>
4406 variable values) can be used to optimize the selected plan. If the
4407 statement has no parameters, or is executed many times, the SPI manager
4408 will consider creating a <firstterm>generic</> plan that is not dependent
4409 on specific parameter values, and caching that for re-use. Typically
4410 this will happen only if the execution plan is not very sensitive to
4411 the values of the <application>PL/pgSQL</> variables referenced in it.
4412 If it is, generating a plan each time is a net win. See <xref
4413 linkend="sql-prepare"> for more information about the behavior of
4414 prepared statements.
4418 Because <application>PL/pgSQL</application> saves prepared statements
4419 and sometimes execution plans in this way,
4420 SQL commands that appear directly in a
4421 <application>PL/pgSQL</application> function must refer to the
4422 same tables and columns on every execution; that is, you cannot use
4423 a parameter as the name of a table or column in an SQL command. To get
4424 around this restriction, you can construct dynamic commands using
4425 the <application>PL/pgSQL</application> <command>EXECUTE</command>
4426 statement — at the price of performing new parse analysis and
4427 constructing a new execution plan on every execution.
4431 The mutable nature of record variables presents another problem in this
4432 connection. When fields of a record variable are used in
4433 expressions or statements, the data types of the fields must not
4434 change from one call of the function to the next, since each
4435 expression will be analyzed using the data type that is present
4436 when the expression is first reached. <command>EXECUTE</command> can be
4437 used to get around this problem when necessary.
4441 If the same function is used as a trigger for more than one table,
4442 <application>PL/pgSQL</application> prepares and caches statements
4443 independently for each such table — that is, there is a cache
4444 for each trigger function and table combination, not just for each
4445 function. This alleviates some of the problems with varying
4446 data types; for instance, a trigger function will be able to work
4447 successfully with a column named <literal>key</> even if it happens
4448 to have different types in different tables.
4452 Likewise, functions having polymorphic argument types have a separate
4453 statement cache for each combination of actual argument types they have
4454 been invoked for, so that data type differences do not cause unexpected
4459 Statement caching can sometimes have surprising effects on the
4460 interpretation of time-sensitive values. For example there
4461 is a difference between what these two functions do:
4464 CREATE FUNCTION logfunc1(logtxt text) RETURNS void AS $$
4466 INSERT INTO logtable VALUES (logtxt, 'now');
4468 $$ LANGUAGE plpgsql;
4474 CREATE FUNCTION logfunc2(logtxt text) RETURNS void AS $$
4479 INSERT INTO logtable VALUES (logtxt, curtime);
4481 $$ LANGUAGE plpgsql;
4486 In the case of <function>logfunc1</function>, the
4487 <productname>PostgreSQL</productname> main parser knows when
4488 analyzing the <command>INSERT</command> that the
4489 string <literal>'now'</literal> should be interpreted as
4490 <type>timestamp</type>, because the target column of
4491 <classname>logtable</classname> is of that type. Thus,
4492 <literal>'now'</literal> will be converted to a <type>timestamp</type>
4494 <command>INSERT</command> is analyzed, and then used in all
4495 invocations of <function>logfunc1</function> during the lifetime
4496 of the session. Needless to say, this isn't what the programmer
4497 wanted. A better idea is to use the <literal>now()</> or
4498 <literal>current_timestamp</> function.
4502 In the case of <function>logfunc2</function>, the
4503 <productname>PostgreSQL</productname> main parser does not know
4504 what type <literal>'now'</literal> should become and therefore
4505 it returns a data value of type <type>text</type> containing the string
4506 <literal>now</literal>. During the ensuing assignment
4507 to the local variable <varname>curtime</varname>, the
4508 <application>PL/pgSQL</application> interpreter casts this
4509 string to the <type>timestamp</type> type by calling the
4510 <function>text_out</function> and <function>timestamp_in</function>
4511 functions for the conversion. So, the computed time stamp is updated
4512 on each execution as the programmer expects. Even though this
4513 happens to work as expected, it's not terribly efficient, so
4514 use of the <literal>now()</> function would still be a better idea.
4521 <sect1 id="plpgsql-development-tips">
4522 <title>Tips for Developing in <application>PL/pgSQL</application></title>
4525 One good way to develop in
4526 <application>PL/pgSQL</> is to use the text editor of your
4527 choice to create your functions, and in another window, use
4528 <application>psql</application> to load and test those functions.
4529 If you are doing it this way, it
4530 is a good idea to write the function using <command>CREATE OR
4531 REPLACE FUNCTION</>. That way you can just reload the file to update
4532 the function definition. For example:
4534 CREATE OR REPLACE FUNCTION testfunc(integer) RETURNS integer AS $$
4536 $$ LANGUAGE plpgsql;
4541 While running <application>psql</application>, you can load or reload such
4542 a function definition file with:
4546 and then immediately issue SQL commands to test the function.
4550 Another good way to develop in <application>PL/pgSQL</> is with a
4551 GUI database access tool that facilitates development in a
4552 procedural language. One example of such a tool is
4553 <application>pgAdmin</>, although others exist. These tools often
4554 provide convenient features such as escaping single quotes and
4555 making it easier to recreate and debug functions.
4558 <sect2 id="plpgsql-quote-tips">
4559 <title>Handling of Quotation Marks</title>
4562 The code of a <application>PL/pgSQL</> function is specified in
4563 <command>CREATE FUNCTION</command> as a string literal. If you
4564 write the string literal in the ordinary way with surrounding
4565 single quotes, then any single quotes inside the function body
4566 must be doubled; likewise any backslashes must be doubled (assuming
4567 escape string syntax is used).
4568 Doubling quotes is at best tedious, and in more complicated cases
4569 the code can become downright incomprehensible, because you can
4570 easily find yourself needing half a dozen or more adjacent quote marks.
4571 It's recommended that you instead write the function body as a
4572 <quote>dollar-quoted</> string literal (see <xref
4573 linkend="sql-syntax-dollar-quoting">). In the dollar-quoting
4574 approach, you never double any quote marks, but instead take care to
4575 choose a different dollar-quoting delimiter for each level of
4576 nesting you need. For example, you might write the <command>CREATE
4577 FUNCTION</command> command as:
4579 CREATE OR REPLACE FUNCTION testfunc(integer) RETURNS integer AS $PROC$
4581 $PROC$ LANGUAGE plpgsql;
4583 Within this, you might use quote marks for simple literal strings in
4584 SQL commands and <literal>$$</> to delimit fragments of SQL commands
4585 that you are assembling as strings. If you need to quote text that
4586 includes <literal>$$</>, you could use <literal>$Q$</>, and so on.
4590 The following chart shows what you have to do when writing quote
4591 marks without dollar quoting. It might be useful when translating
4592 pre-dollar quoting code into something more comprehensible.
4597 <term>1 quotation mark</term>
4600 To begin and end the function body, for example:
4602 CREATE FUNCTION foo() RETURNS integer AS '
4606 Anywhere within a single-quoted function body, quote marks
4607 <emphasis>must</> appear in pairs.
4613 <term>2 quotation marks</term>
4616 For string literals inside the function body, for example:
4618 a_output := ''Blah'';
4619 SELECT * FROM users WHERE f_name=''foobar'';
4621 In the dollar-quoting approach, you'd just write:
4624 SELECT * FROM users WHERE f_name='foobar';
4626 which is exactly what the <application>PL/pgSQL</> parser would see
4633 <term>4 quotation marks</term>
4636 When you need a single quotation mark in a string constant inside the
4637 function body, for example:
4639 a_output := a_output || '' AND name LIKE ''''foobar'''' AND xyz''
4641 The value actually appended to <literal>a_output</literal> would be:
4642 <literal> AND name LIKE 'foobar' AND xyz</literal>.
4645 In the dollar-quoting approach, you'd write:
4647 a_output := a_output || $$ AND name LIKE 'foobar' AND xyz$$
4649 being careful that any dollar-quote delimiters around this are not
4650 just <literal>$$</>.
4656 <term>6 quotation marks</term>
4659 When a single quotation mark in a string inside the function body is
4660 adjacent to the end of that string constant, for example:
4662 a_output := a_output || '' AND name LIKE ''''foobar''''''
4664 The value appended to <literal>a_output</literal> would then be:
4665 <literal> AND name LIKE 'foobar'</literal>.
4668 In the dollar-quoting approach, this becomes:
4670 a_output := a_output || $$ AND name LIKE 'foobar'$$
4677 <term>10 quotation marks</term>
4680 When you want two single quotation marks in a string constant (which
4681 accounts for 8 quotation marks) and this is adjacent to the end of that
4682 string constant (2 more). You will probably only need that if
4683 you are writing a function that generates other functions, as in
4684 <xref linkend="plpgsql-porting-ex2">.
4687 a_output := a_output || '' if v_'' ||
4688 referrer_keys.kind || '' like ''''''''''
4689 || referrer_keys.key_string || ''''''''''
4690 then return '''''' || referrer_keys.referrer_type
4691 || ''''''; end if;'';
4693 The value of <literal>a_output</literal> would then be:
4695 if v_... like ''...'' then return ''...''; end if;
4699 In the dollar-quoting approach, this becomes:
4701 a_output := a_output || $$ if v_$$ || referrer_keys.kind || $$ like '$$
4702 || referrer_keys.key_string || $$'
4703 then return '$$ || referrer_keys.referrer_type
4706 where we assume we only need to put single quote marks into
4707 <literal>a_output</literal>, because it will be re-quoted before use.
4716 <!-- **** Porting from Oracle PL/SQL **** -->
4718 <sect1 id="plpgsql-porting">
4719 <title>Porting from <productname>Oracle</productname> PL/SQL</title>
4721 <indexterm zone="plpgsql-porting">
4722 <primary>Oracle</primary>
4723 <secondary>porting from PL/SQL to PL/pgSQL</secondary>
4726 <indexterm zone="plpgsql-porting">
4727 <primary>PL/SQL (Oracle)</primary>
4728 <secondary>porting to PL/pgSQL</secondary>
4732 This section explains differences between
4733 <productname>PostgreSQL</>'s <application>PL/pgSQL</application>
4734 language and Oracle's <application>PL/SQL</application> language,
4735 to help developers who port applications from
4736 <trademark class="registered">Oracle</> to <productname>PostgreSQL</>.
4740 <application>PL/pgSQL</application> is similar to PL/SQL in many
4741 aspects. It is a block-structured, imperative language, and all
4742 variables have to be declared. Assignments, loops, conditionals
4743 are similar. The main differences you should keep in mind when
4744 porting from <application>PL/SQL</> to
4745 <application>PL/pgSQL</application> are:
4750 If a name used in a SQL command could be either a column name of a
4751 table or a reference to a variable of the function,
4752 <application>PL/SQL</> treats it as a column name. This corresponds
4753 to <application>PL/pgSQL</>'s
4754 <literal>plpgsql.variable_conflict</> = <literal>use_column</>
4755 behavior, which is not the default,
4756 as explained in <xref linkend="plpgsql-var-subst">.
4757 It's often best to avoid such ambiguities in the first place,
4758 but if you have to port a large amount of code that depends on
4759 this behavior, setting <literal>variable_conflict</> may be the
4766 In <productname>PostgreSQL</> the function body must be written as
4767 a string literal. Therefore you need to use dollar quoting or escape
4768 single quotes in the function body. (See <xref
4769 linkend="plpgsql-quote-tips">.)
4775 Instead of packages, use schemas to organize your functions
4782 Since there are no packages, there are no package-level variables
4783 either. This is somewhat annoying. You can keep per-session state
4784 in temporary tables instead.
4790 Integer <command>FOR</> loops with <literal>REVERSE</> work
4791 differently: <application>PL/SQL</> counts down from the second
4792 number to the first, while <application>PL/pgSQL</> counts down
4793 from the first number to the second, requiring the loop bounds
4794 to be swapped when porting. This incompatibility is unfortunate
4795 but is unlikely to be changed. (See <xref
4796 linkend="plpgsql-integer-for">.)
4802 <command>FOR</> loops over queries (other than cursors) also work
4803 differently: the target variable(s) must have been declared,
4804 whereas <application>PL/SQL</> always declares them implicitly.
4805 An advantage of this is that the variable values are still accessible
4806 after the loop exits.
4812 There are various notational differences for the use of cursor
4821 <title>Porting Examples</title>
4824 <xref linkend="pgsql-porting-ex1"> shows how to port a simple
4825 function from <application>PL/SQL</> to <application>PL/pgSQL</>.
4828 <example id="pgsql-porting-ex1">
4829 <title>Porting a Simple Function from <application>PL/SQL</> to <application>PL/pgSQL</></title>
4832 Here is an <productname>Oracle</productname> <application>PL/SQL</> function:
4834 CREATE OR REPLACE FUNCTION cs_fmt_browser_version(v_name varchar,
4838 IF v_version IS NULL THEN
4841 RETURN v_name || '/' || v_version;
4849 Let's go through this function and see the differences compared to
4850 <application>PL/pgSQL</>:
4855 The <literal>RETURN</literal> key word in the function
4856 prototype (not the function body) becomes
4857 <literal>RETURNS</literal> in
4858 <productname>PostgreSQL</productname>.
4859 Also, <literal>IS</> becomes <literal>AS</>, and you need to
4860 add a <literal>LANGUAGE</> clause because <application>PL/pgSQL</>
4861 is not the only possible function language.
4867 In <productname>PostgreSQL</>, the function body is considered
4868 to be a string literal, so you need to use quote marks or dollar
4869 quotes around it. This substitutes for the terminating <literal>/</>
4870 in the Oracle approach.
4876 The <literal>show errors</literal> command does not exist in
4877 <productname>PostgreSQL</>, and is not needed since errors are
4878 reported automatically.
4885 This is how this function would look when ported to
4886 <productname>PostgreSQL</>:
4889 CREATE OR REPLACE FUNCTION cs_fmt_browser_version(v_name varchar,
4891 RETURNS varchar AS $$
4893 IF v_version IS NULL THEN
4896 RETURN v_name || '/' || v_version;
4898 $$ LANGUAGE plpgsql;
4904 <xref linkend="plpgsql-porting-ex2"> shows how to port a
4905 function that creates another function and how to handle the
4906 ensuing quoting problems.
4909 <example id="plpgsql-porting-ex2">
4910 <title>Porting a Function that Creates Another Function from <application>PL/SQL</> to <application>PL/pgSQL</></title>
4913 The following procedure grabs rows from a
4914 <command>SELECT</command> statement and builds a large function
4915 with the results in <literal>IF</literal> statements, for the
4920 This is the Oracle version:
4922 CREATE OR REPLACE PROCEDURE cs_update_referrer_type_proc IS
4923 CURSOR referrer_keys IS
4924 SELECT * FROM cs_referrer_keys
4926 func_cmd VARCHAR(4000);
4928 func_cmd := 'CREATE OR REPLACE FUNCTION cs_find_referrer_type(v_host IN VARCHAR,
4929 v_domain IN VARCHAR, v_url IN VARCHAR) RETURN VARCHAR IS BEGIN';
4931 FOR referrer_key IN referrer_keys LOOP
4932 func_cmd := func_cmd ||
4933 ' IF v_' || referrer_key.kind
4934 || ' LIKE ''' || referrer_key.key_string
4935 || ''' THEN RETURN ''' || referrer_key.referrer_type
4939 func_cmd := func_cmd || ' RETURN NULL; END;';
4941 EXECUTE IMMEDIATE func_cmd;
4949 Here is how this function would end up in <productname>PostgreSQL</>:
4951 CREATE OR REPLACE FUNCTION cs_update_referrer_type_proc() RETURNS void AS $func$
4953 referrer_keys CURSOR IS
4954 SELECT * FROM cs_referrer_keys
4959 func_body := 'BEGIN';
4961 FOR referrer_key IN referrer_keys LOOP
4962 func_body := func_body ||
4963 ' IF v_' || referrer_key.kind
4964 || ' LIKE ' || quote_literal(referrer_key.key_string)
4965 || ' THEN RETURN ' || quote_literal(referrer_key.referrer_type)
4969 func_body := func_body || ' RETURN NULL; END;';
4972 'CREATE OR REPLACE FUNCTION cs_find_referrer_type(v_host varchar,
4975 RETURNS varchar AS '
4976 || quote_literal(func_body)
4977 || ' LANGUAGE plpgsql;' ;
4981 $func$ LANGUAGE plpgsql;
4983 Notice how the body of the function is built separately and passed
4984 through <literal>quote_literal</> to double any quote marks in it. This
4985 technique is needed because we cannot safely use dollar quoting for
4986 defining the new function: we do not know for sure what strings will
4987 be interpolated from the <structfield>referrer_key.key_string</> field.
4988 (We are assuming here that <structfield>referrer_key.kind</> can be
4989 trusted to always be <literal>host</>, <literal>domain</>, or
4990 <literal>url</>, but <structfield>referrer_key.key_string</> might be
4991 anything, in particular it might contain dollar signs.) This function
4992 is actually an improvement on the Oracle original, because it will
4993 not generate broken code when <structfield>referrer_key.key_string</> or
4994 <structfield>referrer_key.referrer_type</> contain quote marks.
4999 <xref linkend="plpgsql-porting-ex3"> shows how to port a function
5000 with <literal>OUT</> parameters and string manipulation.
5001 <productname>PostgreSQL</> does not have a built-in
5002 <function>instr</function> function, but you can create one
5003 using a combination of other
5004 functions.<indexterm><primary>instr</></indexterm> In <xref
5005 linkend="plpgsql-porting-appendix"> there is a
5006 <application>PL/pgSQL</application> implementation of
5007 <function>instr</function> that you can use to make your porting
5011 <example id="plpgsql-porting-ex3">
5012 <title>Porting a Procedure With String Manipulation and
5013 <literal>OUT</> Parameters from <application>PL/SQL</> to
5014 <application>PL/pgSQL</></title>
5017 The following <productname>Oracle</productname> PL/SQL procedure is used
5018 to parse a URL and return several elements (host, path, and query).
5022 This is the Oracle version:
5024 CREATE OR REPLACE PROCEDURE cs_parse_url(
5026 v_host OUT VARCHAR, -- This will be passed back
5027 v_path OUT VARCHAR, -- This one too
5028 v_query OUT VARCHAR) -- And this one
5036 a_pos1 := instr(v_url, '//');
5041 a_pos2 := instr(v_url, '/', a_pos1 + 2);
5043 v_host := substr(v_url, a_pos1 + 2);
5048 v_host := substr(v_url, a_pos1 + 2, a_pos2 - a_pos1 - 2);
5049 a_pos1 := instr(v_url, '?', a_pos2 + 1);
5052 v_path := substr(v_url, a_pos2);
5056 v_path := substr(v_url, a_pos2, a_pos1 - a_pos2);
5057 v_query := substr(v_url, a_pos1 + 1);
5065 Here is a possible translation into <application>PL/pgSQL</>:
5067 CREATE OR REPLACE FUNCTION cs_parse_url(
5069 v_host OUT VARCHAR, -- This will be passed back
5070 v_path OUT VARCHAR, -- This one too
5071 v_query OUT VARCHAR) -- And this one
5080 a_pos1 := instr(v_url, '//');
5085 a_pos2 := instr(v_url, '/', a_pos1 + 2);
5087 v_host := substr(v_url, a_pos1 + 2);
5092 v_host := substr(v_url, a_pos1 + 2, a_pos2 - a_pos1 - 2);
5093 a_pos1 := instr(v_url, '?', a_pos2 + 1);
5096 v_path := substr(v_url, a_pos2);
5100 v_path := substr(v_url, a_pos2, a_pos1 - a_pos2);
5101 v_query := substr(v_url, a_pos1 + 1);
5103 $$ LANGUAGE plpgsql;
5106 This function could be used like this:
5108 SELECT * FROM cs_parse_url('http://foobar.com/query.cgi?baz');
5114 <xref linkend="plpgsql-porting-ex4"> shows how to port a procedure
5115 that uses numerous features that are specific to Oracle.
5118 <example id="plpgsql-porting-ex4">
5119 <title>Porting a Procedure from <application>PL/SQL</> to <application>PL/pgSQL</></title>
5125 CREATE OR REPLACE PROCEDURE cs_create_job(v_job_id IN INTEGER) IS
5126 a_running_job_count INTEGER;
5127 PRAGMA AUTONOMOUS_TRANSACTION;<co id="co.plpgsql-porting-pragma">
5129 LOCK TABLE cs_jobs IN EXCLUSIVE MODE;<co id="co.plpgsql-porting-locktable">
5131 SELECT count(*) INTO a_running_job_count FROM cs_jobs WHERE end_stamp IS NULL;
5133 IF a_running_job_count > 0 THEN
5134 COMMIT; -- free lock<co id="co.plpgsql-porting-commit">
5135 raise_application_error(-20000,
5136 'Unable to create a new job: a job is currently running.');
5139 DELETE FROM cs_active_job;
5140 INSERT INTO cs_active_job(job_id) VALUES (v_job_id);
5143 INSERT INTO cs_jobs (job_id, start_stamp) VALUES (v_job_id, sysdate);
5145 WHEN dup_val_on_index THEN NULL; -- don't worry if it already exists
5155 Procedures like this can easily be converted into <productname>PostgreSQL</>
5156 functions returning <type>void</type>. This procedure in
5157 particular is interesting because it can teach us some things:
5160 <callout arearefs="co.plpgsql-porting-pragma">
5162 There is no <literal>PRAGMA</literal> statement in <productname>PostgreSQL</>.
5166 <callout arearefs="co.plpgsql-porting-locktable">
5168 If you do a <command>LOCK TABLE</command> in <application>PL/pgSQL</>,
5169 the lock will not be released until the calling transaction is
5174 <callout arearefs="co.plpgsql-porting-commit">
5176 You cannot issue <command>COMMIT</> in a
5177 <application>PL/pgSQL</application> function. The function is
5178 running within some outer transaction and so <command>COMMIT</>
5179 would imply terminating the function's execution. However, in
5180 this particular case it is not necessary anyway, because the lock
5181 obtained by the <command>LOCK TABLE</command> will be released when
5189 This is how we could port this procedure to <application>PL/pgSQL</>:
5192 CREATE OR REPLACE FUNCTION cs_create_job(v_job_id integer) RETURNS void AS $$
5194 a_running_job_count integer;
5196 LOCK TABLE cs_jobs IN EXCLUSIVE MODE;
5198 SELECT count(*) INTO a_running_job_count FROM cs_jobs WHERE end_stamp IS NULL;
5200 IF a_running_job_count > 0 THEN
5201 RAISE EXCEPTION 'Unable to create a new job: a job is currently running';<co id="co.plpgsql-porting-raise">
5204 DELETE FROM cs_active_job;
5205 INSERT INTO cs_active_job(job_id) VALUES (v_job_id);
5208 INSERT INTO cs_jobs (job_id, start_stamp) VALUES (v_job_id, now());
5210 WHEN unique_violation THEN <co id="co.plpgsql-porting-exception">
5211 -- don't worry if it already exists
5214 $$ LANGUAGE plpgsql;
5218 <callout arearefs="co.plpgsql-porting-raise">
5220 The syntax of <literal>RAISE</> is considerably different from
5221 Oracle's statement, although the basic case <literal>RAISE</>
5222 <replaceable class="parameter">exception_name</replaceable> works
5226 <callout arearefs="co.plpgsql-porting-exception">
5228 The exception names supported by <application>PL/pgSQL</> are
5229 different from Oracle's. The set of built-in exception names
5230 is much larger (see <xref linkend="errcodes-appendix">). There
5231 is not currently a way to declare user-defined exception names,
5232 although you can throw user-chosen SQLSTATE values instead.
5237 The main functional difference between this procedure and the
5238 Oracle equivalent is that the exclusive lock on the <literal>cs_jobs</>
5239 table will be held until the calling transaction completes. Also, if
5240 the caller later aborts (for example due to an error), the effects of
5241 this procedure will be rolled back.
5246 <sect2 id="plpgsql-porting-other">
5247 <title>Other Things to Watch For</title>
5250 This section explains a few other things to watch for when porting
5251 Oracle <application>PL/SQL</> functions to
5252 <productname>PostgreSQL</productname>.
5255 <sect3 id="plpgsql-porting-exceptions">
5256 <title>Implicit Rollback after Exceptions</title>
5259 In <application>PL/pgSQL</>, when an exception is caught by an
5260 <literal>EXCEPTION</> clause, all database changes since the block's
5261 <literal>BEGIN</> are automatically rolled back. That is, the behavior
5262 is equivalent to what you'd get in Oracle with:
5278 If you are translating an Oracle procedure that uses
5279 <command>SAVEPOINT</> and <command>ROLLBACK TO</> in this style,
5280 your task is easy: just omit the <command>SAVEPOINT</> and
5281 <command>ROLLBACK TO</>. If you have a procedure that uses
5282 <command>SAVEPOINT</> and <command>ROLLBACK TO</> in a different way
5283 then some actual thought will be required.
5288 <title><command>EXECUTE</command></title>
5291 The <application>PL/pgSQL</> version of
5292 <command>EXECUTE</command> works similarly to the
5293 <application>PL/SQL</> version, but you have to remember to use
5294 <function>quote_literal</function> and
5295 <function>quote_ident</function> as described in <xref
5296 linkend="plpgsql-statements-executing-dyn">. Constructs of the
5297 type <literal>EXECUTE 'SELECT * FROM $1';</literal> will not work
5298 reliably unless you use these functions.
5302 <sect3 id="plpgsql-porting-optimization">
5303 <title>Optimizing <application>PL/pgSQL</application> Functions</title>
5306 <productname>PostgreSQL</> gives you two function creation
5307 modifiers to optimize execution: <quote>volatility</> (whether
5308 the function always returns the same result when given the same
5309 arguments) and <quote>strictness</quote> (whether the function
5310 returns null if any argument is null). Consult the <xref
5311 linkend="sql-createfunction">
5312 reference page for details.
5316 When making use of these optimization attributes, your
5317 <command>CREATE FUNCTION</command> statement might look something
5321 CREATE FUNCTION foo(...) RETURNS integer AS $$
5323 $$ LANGUAGE plpgsql STRICT IMMUTABLE;
5329 <sect2 id="plpgsql-porting-appendix">
5330 <title>Appendix</title>
5333 This section contains the code for a set of Oracle-compatible
5334 <function>instr</function> functions that you can use to simplify
5335 your porting efforts.
5340 -- instr functions that mimic Oracle's counterpart
5341 -- Syntax: instr(string1, string2, [n], [m]) where [] denotes optional parameters.
5343 -- Searches string1 beginning at the nth character for the mth occurrence
5344 -- of string2. If n is negative, search backwards. If m is not passed,
5345 -- assume 1 (search starts at first character).
5348 CREATE FUNCTION instr(varchar, varchar) RETURNS integer AS $$
5352 pos:= instr($1, $2, 1);
5355 $$ LANGUAGE plpgsql STRICT IMMUTABLE;
5358 CREATE FUNCTION instr(string varchar, string_to_search varchar, beg_index integer)
5359 RETURNS integer AS $$
5361 pos integer NOT NULL DEFAULT 0;
5367 IF beg_index > 0 THEN
5368 temp_str := substring(string FROM beg_index);
5369 pos := position(string_to_search IN temp_str);
5374 RETURN pos + beg_index - 1;
5376 ELSIF beg_index < 0 THEN
5377 ss_length := char_length(string_to_search);
5378 length := char_length(string);
5379 beg := length + beg_index - ss_length + 2;
5381 WHILE beg > 0 LOOP
5382 temp_str := substring(string FROM beg FOR ss_length);
5383 pos := position(string_to_search IN temp_str);
5397 $$ LANGUAGE plpgsql STRICT IMMUTABLE;
5400 CREATE FUNCTION instr(string varchar, string_to_search varchar,
5401 beg_index integer, occur_index integer)
5402 RETURNS integer AS $$
5404 pos integer NOT NULL DEFAULT 0;
5405 occur_number integer NOT NULL DEFAULT 0;
5412 IF beg_index > 0 THEN
5414 temp_str := substring(string FROM beg_index);
5416 FOR i IN 1..occur_index LOOP
5417 pos := position(string_to_search IN temp_str);
5420 beg := beg + pos - 1;
5425 temp_str := substring(string FROM beg + 1);
5433 ELSIF beg_index < 0 THEN
5434 ss_length := char_length(string_to_search);
5435 length := char_length(string);
5436 beg := length + beg_index - ss_length + 2;
5438 WHILE beg > 0 LOOP
5439 temp_str := substring(string FROM beg FOR ss_length);
5440 pos := position(string_to_search IN temp_str);
5443 occur_number := occur_number + 1;
5445 IF occur_number = occur_index THEN
5458 $$ LANGUAGE plpgsql STRICT IMMUTABLE;