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
</application> were to create
17 a loadable procedural language that
22 can be used to create functions, procedures, and triggers,
27 adds control structures to the
<acronym>SQL
</acronym> language,
32 can perform complex computations,
37 inherits all user-defined types, functions, procedures, 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
</productname> 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
</productname>
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 accepting
<type>record
</type>, which means that any
127 composite type will do as input, or
128 as returning
<type>record
</type>, which means that the result
129 is a row type whose columns are determined by specification in the
130 calling query, as discussed in
<xref linkend=
"queries-tablefunctions"/>.
134 <application>PL/pgSQL
</application> functions can be declared to accept a variable
135 number of arguments by using the
<literal>VARIADIC
</literal> marker. This
136 works exactly the same way as for SQL functions, as discussed in
137 <xref linkend=
"xfunc-sql-variadic-functions"/>.
141 <application>PL/pgSQL
</application> functions can also be declared to
142 accept and return the polymorphic types described in
143 <xref linkend=
"extend-types-polymorphic"/>, thus allowing the actual data
144 types handled by the function to vary from call to call.
145 Examples appear in
<xref linkend=
"plpgsql-declaration-parameters"/>.
149 <application>PL/pgSQL
</application> functions can also be declared to return
150 a
<quote>set
</quote> (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
</command> for each desired element of the result
153 set, or by using
<command>RETURN QUERY
</command> to output the result of
158 Finally, a
<application>PL/pgSQL
</application> function can be declared to return
159 <type>void
</type> if it has no useful return value. (Alternatively, it
160 could be written as a procedure in that case.)
164 <application>PL/pgSQL
</application> functions can also be declared with output
165 parameters in place of an explicit specification of the return type.
166 This does not add any fundamental capability to the language, but
167 it is often convenient, especially for returning multiple values.
168 The
<literal>RETURNS TABLE
</literal> notation can also be used in place
169 of
<literal>RETURNS SETOF
</literal>.
173 Specific examples appear in
174 <xref linkend=
"plpgsql-declaration-parameters"/> and
175 <xref linkend=
"plpgsql-statements-returning"/>.
180 <sect1 id=
"plpgsql-structure">
181 <title>Structure of
<application>PL/pgSQL
</application></title>
184 Functions written in
<application>PL/pgSQL
</application> are defined
185 to the server by executing
<xref linkend=
"sql-createfunction"/> commands.
186 Such a command would normally look like, say,
188 CREATE FUNCTION somefunc(integer, text) RETURNS integer
189 AS '
<replaceable>function body text
</replaceable>'
192 The function body is simply a string literal so far as
<command>CREATE
193 FUNCTION
</command> is concerned. It is often helpful to use dollar quoting
194 (see
<xref linkend=
"sql-syntax-dollar-quoting"/>) to write the function
195 body, rather than the normal single quote syntax. Without dollar quoting,
196 any single quotes or backslashes in the function body must be escaped by
197 doubling them. Almost all the examples in this chapter use dollar-quoted
198 literals for their function bodies.
202 <application>PL/pgSQL
</application> is a block-structured language.
203 The complete text of a function body must be a
204 <firstterm>block
</firstterm>. A block is defined as:
207 <optional> <<<replaceable>label
</replaceable>>> </optional>
209 <replaceable>declarations
</replaceable> </optional>
211 <replaceable>statements
</replaceable>
212 END
<optional> <replaceable>label
</replaceable> </optional>;
217 Each declaration and each statement within a block is terminated
218 by a semicolon. A block that appears within another block must
219 have a semicolon after
<literal>END
</literal>, as shown above;
220 however the final
<literal>END
</literal> that
221 concludes a function body does not require a semicolon.
226 A common mistake is to write a semicolon immediately after
227 <literal>BEGIN
</literal>. This is incorrect and will result in a syntax error.
232 A
<replaceable>label
</replaceable> is only needed if you want to
233 identify the block for use
234 in an
<literal>EXIT
</literal> statement, or to qualify the names of the
235 variables declared in the block. If a label is given after
236 <literal>END
</literal>, it must match the label at the block's beginning.
240 All key words are case-insensitive.
241 Identifiers are implicitly converted to lower case
242 unless double-quoted, just as they are in ordinary SQL commands.
246 Comments work the same way in
<application>PL/pgSQL
</application> code as in
247 ordinary SQL. A double dash (
<literal>--
</literal>) starts a comment
248 that extends to the end of the line. A
<literal>/*
</literal> starts a
249 block comment that extends to the matching occurrence of
250 <literal>*/
</literal>. Block comments nest.
254 Any statement in the statement section of a block
255 can be a
<firstterm>subblock
</firstterm>. Subblocks can be used for
256 logical grouping or to localize variables to a small group
257 of statements. Variables declared in a subblock mask any
258 similarly-named variables of outer blocks for the duration
259 of the subblock; but you can access the outer variables anyway
260 if you qualify their names with their block's label. For example:
262 CREATE FUNCTION somefunc() RETURNS integer AS $$
263 << outerblock
>>
265 quantity integer :=
30;
267 RAISE NOTICE 'Quantity here is %', quantity; -- Prints
30
273 quantity integer :=
80;
275 RAISE NOTICE 'Quantity here is %', quantity; -- Prints
80
276 RAISE NOTICE 'Outer quantity here is %', outerblock.quantity; -- Prints
50
279 RAISE NOTICE 'Quantity here is %', quantity; -- Prints
50
289 There is actually a hidden
<quote>outer block
</quote> surrounding the body
290 of any
<application>PL/pgSQL
</application> function. This block provides the
291 declarations of the function's parameters (if any), as well as some
292 special variables such as
<literal>FOUND
</literal> (see
293 <xref linkend=
"plpgsql-statements-diagnostics"/>). The outer block is
294 labeled with the function's name, meaning that parameters and special
295 variables can be qualified with the function's name.
300 It is important not to confuse the use of
301 <command>BEGIN
</command>/
<command>END
</command> for grouping statements in
302 <application>PL/pgSQL
</application> with the similarly-named SQL commands
304 control.
<application>PL/pgSQL
</application>'s
<command>BEGIN
</command>/
<command>END
</command>
305 are only for grouping; they do not start or end a transaction.
306 See
<xref linkend=
"plpgsql-transactions"/> for information on managing
307 transactions in
<application>PL/pgSQL
</application>.
308 Also, a block containing an
<literal>EXCEPTION
</literal> clause effectively
309 forms a subtransaction that can be rolled back without affecting the
310 outer transaction. For more about that see
<xref
311 linkend=
"plpgsql-error-trapping"/>.
315 <sect1 id=
"plpgsql-declarations">
316 <title>Declarations
</title>
319 All variables used in a block must be declared in the
320 declarations section of the block.
321 (The only exceptions are that the loop variable of a
<literal>FOR
</literal> loop
322 iterating over a range of integer values is automatically declared as an
323 integer variable, and likewise the loop variable of a
<literal>FOR
</literal> loop
324 iterating over a cursor's result is automatically declared as a
329 <application>PL/pgSQL
</application> variables can have any SQL data type, such as
330 <type>integer
</type>,
<type>varchar
</type>, and
335 Here are some examples of variable declarations:
340 myrow tablename%ROWTYPE;
341 myfield tablename.columnname%TYPE;
347 The general syntax of a variable declaration is:
349 <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>;
351 The
<literal>DEFAULT
</literal> clause, if given, specifies the initial value assigned
352 to the variable when the block is entered. If the
<literal>DEFAULT
</literal> clause
353 is not given then the variable is initialized to the
354 <acronym>SQL
</acronym> null value.
355 The
<literal>CONSTANT
</literal> option prevents the variable from being
356 assigned to after initialization, so that its value will remain constant
357 for the duration of the block.
358 The
<literal>COLLATE
</literal> option specifies a collation to use for the
359 variable (see
<xref linkend=
"plpgsql-declaration-collation"/>).
360 If
<literal>NOT NULL
</literal>
361 is specified, an assignment of a null value results in a run-time
362 error. All variables declared as
<literal>NOT NULL
</literal>
363 must have a nonnull default value specified.
364 Equal (
<literal>=
</literal>) can be used instead of PL/SQL-compliant
365 <literal>:=
</literal>.
369 A variable's default value is evaluated and assigned to the variable
370 each time the block is entered (not just once per function call).
371 So, for example, assigning
<literal>now()
</literal> to a variable of type
372 <type>timestamp
</type> causes the variable to have the
373 time of the current function call, not the time when the function was
380 quantity integer DEFAULT
32;
381 url varchar := 'http://mysite.com';
382 transaction_time CONSTANT timestamp with time zone := now();
387 Once declared, a variable's value can be used in later initialization
388 expressions in the same block, for example:
396 <sect2 id=
"plpgsql-declaration-parameters">
397 <title>Declaring Function Parameters
</title>
400 Parameters passed to functions are named with the identifiers
401 <literal>$
1</literal>,
<literal>$
2</literal>,
402 etc. Optionally, aliases can be declared for
403 <literal>$
<replaceable>n
</replaceable></literal>
404 parameter names for increased readability. Either the alias or the
405 numeric identifier can then be used to refer to the parameter value.
409 There are two ways to create an alias. The preferred way is to give a
410 name to the parameter in the
<command>CREATE FUNCTION
</command> command,
413 CREATE FUNCTION sales_tax(subtotal real) RETURNS real AS $$
415 RETURN subtotal *
0.06;
419 The other way is to explicitly declare an alias, using the
423 <replaceable>name
</replaceable> ALIAS FOR $
<replaceable>n
</replaceable>;
426 The same example in this style looks like:
428 CREATE FUNCTION sales_tax(real) RETURNS real AS $$
430 subtotal ALIAS FOR $
1;
432 RETURN subtotal *
0.06;
440 These two examples are not perfectly equivalent. In the first case,
441 <literal>subtotal
</literal> could be referenced as
442 <literal>sales_tax.subtotal
</literal>, but in the second case it could not.
443 (Had we attached a label to the inner block,
<literal>subtotal
</literal> could
444 be qualified with that label, instead.)
451 CREATE FUNCTION instr(varchar, integer) RETURNS integer AS $$
453 v_string ALIAS FOR $
1;
456 -- some computations using v_string and index here
461 CREATE FUNCTION concat_selected_fields(in_t sometablename) RETURNS text AS $$
463 RETURN in_t.f1 || in_t.f3 || in_t.f5 || in_t.f7;
470 When a
<application>PL/pgSQL
</application> function is declared
471 with output parameters, the output parameters are given
472 <literal>$
<replaceable>n
</replaceable></literal> names and optional
473 aliases in just the same way as the normal input parameters. An
474 output parameter is effectively a variable that starts out NULL;
475 it should be assigned to during the execution of the function.
476 The final value of the parameter is what is returned. For instance,
477 the sales-tax example could also be done this way:
480 CREATE FUNCTION sales_tax(subtotal real, OUT tax real) AS $$
482 tax := subtotal *
0.06;
487 Notice that we omitted
<literal>RETURNS real
</literal> — we could have
488 included it, but it would be redundant.
492 To call a function with
<literal>OUT
</literal> parameters, omit the
493 output parameter(s) in the function call:
495 SELECT sales_tax(
100.00);
500 Output parameters are most useful when returning multiple values.
501 A trivial example is:
504 CREATE FUNCTION sum_n_product(x int, y int, OUT sum int, OUT prod int) AS $$
511 SELECT * FROM sum_n_product(
2,
4);
517 As discussed in
<xref linkend=
"xfunc-output-parameters"/>, this
518 effectively creates an anonymous record type for the function's
519 results. If a
<literal>RETURNS
</literal> clause is given, it must say
520 <literal>RETURNS record
</literal>.
524 This also works with procedures, for example:
527 CREATE PROCEDURE sum_n_product(x int, y int, OUT sum int, OUT prod int) AS $$
535 In a call to a procedure, all the parameters must be specified. For
536 output parameters,
<literal>NULL
</literal> may be specified when
537 calling the procedure from plain SQL:
539 CALL sum_n_product(
2,
4, NULL, NULL);
545 However, when calling a procedure
546 from
<application>PL/pgSQL
</application>, you should instead write a
547 variable for any output parameter; the variable will receive the result
548 of the call. See
<xref linkend=
"plpgsql-statements-calling-procedure"/>
553 Another way to declare a
<application>PL/pgSQL
</application> function
554 is with
<literal>RETURNS TABLE
</literal>, for example:
557 CREATE FUNCTION extended_sales(p_itemno int)
558 RETURNS TABLE(quantity int, total numeric) AS $$
560 RETURN QUERY SELECT s.quantity, s.quantity * s.price FROM sales AS s
561 WHERE s.itemno = p_itemno;
566 This is exactly equivalent to declaring one or more
<literal>OUT
</literal>
567 parameters and specifying
<literal>RETURNS SETOF
568 <replaceable>sometype
</replaceable></literal>.
572 When the return type of a
<application>PL/pgSQL
</application> function
573 is declared as a polymorphic type (see
574 <xref linkend=
"extend-types-polymorphic"/>), a special
575 parameter
<literal>$
0</literal> is created. Its data type is the actual
576 return type of the function, as deduced from the actual input types.
577 This allows the function to access its actual return type
578 as shown in
<xref linkend=
"plpgsql-declaration-type"/>.
579 <literal>$
0</literal> is initialized to null and can be modified by
580 the function, so it can be used to hold the return value if desired,
581 though that is not required.
<literal>$
0</literal> can also be
582 given an alias. For example, this function works on any data type
583 that has a
<literal>+
</literal> operator:
586 CREATE FUNCTION add_three_values(v1 anyelement, v2 anyelement, v3 anyelement)
587 RETURNS anyelement AS $$
591 result := v1 + v2 + v3;
599 The same effect can be obtained by declaring one or more output parameters as
600 polymorphic types. In this case the
601 special
<literal>$
0</literal> parameter is not used; the output
602 parameters themselves serve the same purpose. For example:
605 CREATE FUNCTION add_three_values(v1 anyelement, v2 anyelement, v3 anyelement,
616 In practice it might be more useful to declare a polymorphic function
617 using the
<type>anycompatible
</type> family of types, so that automatic
618 promotion of the input arguments to a common type will occur.
622 CREATE FUNCTION add_three_values(v1 anycompatible, v2 anycompatible, v3 anycompatible)
623 RETURNS anycompatible AS $$
630 With this example, a call such as
633 SELECT add_three_values(
1,
2,
4.7);
636 will work, automatically promoting the integer inputs to numeric.
637 The function using
<type>anyelement
</type> would require you to
638 cast the three inputs to the same type manually.
642 <sect2 id=
"plpgsql-declaration-alias">
643 <title><literal>ALIAS
</literal></title>
646 <replaceable>newname
</replaceable> ALIAS FOR
<replaceable>oldname
</replaceable>;
650 The
<literal>ALIAS
</literal> syntax is more general than is suggested in the
651 previous section: you can declare an alias for any variable, not just
652 function parameters. The main practical use for this is to assign
653 a different name for variables with predetermined names, such as
654 <varname>NEW
</varname> or
<varname>OLD
</varname> within
663 updated ALIAS FOR new;
668 Since
<literal>ALIAS
</literal> creates two different ways to name the same
669 object, unrestricted use can be confusing. It's best to use it only
670 for the purpose of overriding predetermined names.
674 <sect2 id=
"plpgsql-declaration-type">
675 <title>Copying Types
</title>
678 <replaceable>name
</replaceable> <replaceable>table
</replaceable>.
<replaceable>column
</replaceable>%TYPE
679 <replaceable>name
</replaceable> <replaceable>variable
</replaceable>%TYPE
683 <literal>%TYPE
</literal> provides the data type of a table column
684 or a previously-declared
<application>PL/pgSQL
</application>
685 variable. You can use this to declare variables that will hold
686 database values. For example, let's say you have a column named
687 <literal>user_id
</literal> in your
<literal>users
</literal>
688 table. To declare a variable with the same data type as
689 <literal>users.user_id
</literal> you write:
691 user_id users.user_id%TYPE;
696 It is also possible to write array decoration
697 after
<literal>%TYPE
</literal>, thereby creating a variable that holds
698 an array of the referenced type:
700 user_ids users.user_id%TYPE[];
701 user_ids users.user_id%TYPE ARRAY[
4]; -- equivalent to the above
703 Just as when declaring table columns that are arrays, it doesn't
704 matter whether you write multiple bracket pairs or specific array
705 dimensions:
<productname>PostgreSQL
</productname> treats all arrays of
706 a given element type as the same type, regardless of dimensionality.
707 (See
<xref linkend=
"arrays-declaration"/>.)
711 By using
<literal>%TYPE
</literal> you don't need to know the data
712 type of the structure you are referencing, and most importantly,
713 if the data type of the referenced item changes in the future (for
714 instance: you change the type of
<literal>user_id
</literal>
715 from
<type>integer
</type> to
<type>real
</type>), you might not need
716 to change your function definition.
720 <literal>%TYPE
</literal> is particularly valuable in polymorphic
721 functions, since the data types needed for internal variables can
722 change from one call to the next. Appropriate variables can be
723 created by applying
<literal>%TYPE
</literal> to the function's
724 arguments or result placeholders.
729 <sect2 id=
"plpgsql-declaration-rowtypes">
730 <title>Row Types
</title>
733 <replaceable>name
</replaceable> <replaceable>table_name
</replaceable><literal>%ROWTYPE
</literal>;
734 <replaceable>name
</replaceable> <replaceable>composite_type_name
</replaceable>;
738 A variable of a composite type is called a
<firstterm>row
</firstterm>
739 variable (or
<firstterm>row-type
</firstterm> variable). Such a variable
740 can hold a whole row of a
<command>SELECT
</command> or
<command>FOR
</command>
741 query result, so long as that query's column set matches the
742 declared type of the variable.
743 The individual fields of the row value
744 are accessed using the usual dot notation, for example
745 <literal>rowvar.field
</literal>.
749 A row variable can be declared to have the same type as the rows of
750 an existing table or view, by using the
751 <replaceable>table_name
</replaceable><literal>%ROWTYPE
</literal>
752 notation; or it can be declared by giving a composite type's name.
753 (Since every table has an associated composite type of the same name,
754 it actually does not matter in
<productname>PostgreSQL
</productname> whether you
755 write
<literal>%ROWTYPE
</literal> or not. But the form with
756 <literal>%ROWTYPE
</literal> is more portable.)
760 As with
<literal>%TYPE
</literal>,
<literal>%ROWTYPE
</literal> can be
761 followed by array decoration to declare a variable that holds an array
762 of the referenced composite type.
766 Parameters to a function can be
767 composite types (complete table rows). In that case, the
768 corresponding identifier
<literal>$
<replaceable>n
</replaceable></literal> will be a row variable, and fields can
769 be selected from it, for example
<literal>$
1.user_id
</literal>.
773 Here is an example of using composite types.
<structname>table1
</structname>
774 and
<structname>table2
</structname> are existing tables having at least the
778 CREATE FUNCTION merge_fields(t_row table1) RETURNS text AS $$
780 t2_row table2%ROWTYPE;
782 SELECT * INTO t2_row FROM table2 WHERE ... ;
783 RETURN t_row.f1 || t2_row.f3 || t_row.f5 || t2_row.f7;
787 SELECT merge_fields(t.*) FROM table1 t WHERE ... ;
792 <sect2 id=
"plpgsql-declaration-records">
793 <title>Record Types
</title>
796 <replaceable>name
</replaceable> RECORD;
800 Record variables are similar to row-type variables, but they have no
801 predefined structure. They take on the actual row structure of the
802 row they are assigned during a
<command>SELECT
</command> or
<command>FOR
</command> command. The substructure
803 of a record variable can change each time it is assigned to.
804 A consequence of this is that until a record variable is first assigned
805 to, it has no substructure, and any attempt to access a
806 field in it will draw a run-time error.
810 Note that
<literal>RECORD
</literal> is not a true data type, only a placeholder.
811 One should also realize that when a
<application>PL/pgSQL
</application>
812 function is declared to return type
<type>record
</type>, this is not quite the
813 same concept as a record variable, even though such a function might
814 use a record variable to hold its result. In both cases the actual row
815 structure is unknown when the function is written, but for a function
816 returning
<type>record
</type> the actual structure is determined when the
817 calling query is parsed, whereas a record variable can change its row
818 structure on-the-fly.
822 <sect2 id=
"plpgsql-declaration-collation">
823 <title>Collation of
<application>PL/pgSQL
</application> Variables
</title>
826 <primary>collation
</primary>
827 <secondary>in PL/pgSQL
</secondary>
831 When a
<application>PL/pgSQL
</application> function has one or more
832 parameters of collatable data types, a collation is identified for each
833 function call depending on the collations assigned to the actual
834 arguments, as described in
<xref linkend=
"collation"/>. If a collation is
835 successfully identified (i.e., there are no conflicts of implicit
836 collations among the arguments) then all the collatable parameters are
837 treated as having that collation implicitly. This will affect the
838 behavior of collation-sensitive operations within the function.
839 For example, consider
842 CREATE FUNCTION less_than(a text, b text) RETURNS boolean AS $$
848 SELECT less_than(text_field_1, text_field_2) FROM table1;
849 SELECT less_than(text_field_1, text_field_2 COLLATE
"C") FROM table1;
852 The first use of
<function>less_than
</function> will use the common collation
853 of
<structfield>text_field_1
</structfield> and
<structfield>text_field_2
</structfield> for
854 the comparison, while the second use will use
<literal>C
</literal> collation.
858 Furthermore, the identified collation is also assumed as the collation of
859 any local variables that are of collatable types. Thus this function
860 would not work any differently if it were written as
863 CREATE FUNCTION less_than(a text, b text) RETURNS boolean AS $$
868 RETURN local_a
< local_b;
875 If there are no parameters of collatable data types, or no common
876 collation can be identified for them, then parameters and local variables
877 use the default collation of their data type (which is usually the
878 database's default collation, but could be different for variables of
883 A local variable of a collatable data type can have a different collation
884 associated with it by including the
<literal>COLLATE
</literal> option in its
885 declaration, for example
889 local_a text COLLATE
"en_US";
892 This option overrides the collation that would otherwise be
893 given to the variable according to the rules above.
897 Also, of course explicit
<literal>COLLATE
</literal> clauses can be written inside
898 a function if it is desired to force a particular collation to be used in
899 a particular operation. For example,
902 CREATE FUNCTION less_than_c(a text, b text) RETURNS boolean AS $$
904 RETURN a
< b COLLATE
"C";
909 This overrides the collations associated with the table columns,
910 parameters, or local variables used in the expression, just as would
911 happen in a plain SQL command.
916 <sect1 id=
"plpgsql-expressions">
917 <title>Expressions
</title>
920 All expressions used in
<application>PL/pgSQL
</application>
921 statements are processed using the server's main
922 <acronym>SQL
</acronym> executor. For example, when you write
923 a
<application>PL/pgSQL
</application> statement like
925 IF
<replaceable>expression
</replaceable> THEN ...
927 <application>PL/pgSQL
</application> will evaluate the expression by
930 SELECT
<replaceable>expression
</replaceable>
932 to the main SQL engine. While forming the
<command>SELECT
</command> command,
933 any occurrences of
<application>PL/pgSQL
</application> variable names
934 are replaced by query parameters, as discussed in detail in
935 <xref linkend=
"plpgsql-var-subst"/>.
936 This allows the query plan for the
<command>SELECT
</command> to
937 be prepared just once and then reused for subsequent
938 evaluations with different values of the variables. Thus, what
939 really happens on first use of an expression is essentially a
940 <command>PREPARE
</command> command. For example, if we have declared
941 two integer variables
<literal>x
</literal> and
<literal>y
</literal>, and we write
945 what happens behind the scenes is equivalent to
947 PREPARE
<replaceable>statement_name
</replaceable>(integer, integer) AS SELECT $
1 < $
2;
949 and then this prepared statement is
<command>EXECUTE
</command>d for each
950 execution of the
<command>IF
</command> statement, with the current values
951 of the
<application>PL/pgSQL
</application> variables supplied as
952 parameter values. Normally these details are
953 not important to a
<application>PL/pgSQL
</application> user, but
954 they are useful to know when trying to diagnose a problem.
955 More information appears in
<xref linkend=
"plpgsql-plan-caching"/>.
959 Since an
<replaceable>expression
</replaceable> is converted to a
960 <literal>SELECT
</literal> command, it can contain the same clauses
961 that an ordinary
<literal>SELECT
</literal> would, except that it
962 cannot include a top-level
<literal>UNION
</literal>,
963 <literal>INTERSECT
</literal>, or
<literal>EXCEPT
</literal> clause.
964 Thus for example one could test whether a table is non-empty with
966 IF count(*)
> 0 FROM my_table THEN ...
968 since the
<replaceable>expression
</replaceable>
969 between
<literal>IF
</literal> and
<literal>THEN
</literal> is parsed as
970 though it were
<literal>SELECT count(*)
> 0 FROM my_table
</literal>.
971 The
<literal>SELECT
</literal> must produce a single column, and not
972 more than one row. (If it produces no rows, the result is taken as
977 <sect1 id=
"plpgsql-statements">
978 <title>Basic Statements
</title>
981 In this section and the following ones, we describe all the statement
982 types that are explicitly understood by
983 <application>PL/pgSQL
</application>.
984 Anything not recognized as one of these statement types is presumed
985 to be an SQL command and is sent to the main database engine to execute,
986 as described in
<xref linkend=
"plpgsql-statements-general-sql"/>.
989 <sect2 id=
"plpgsql-statements-assignment">
990 <title>Assignment
</title>
993 An assignment of a value to a
<application>PL/pgSQL
</application>
994 variable is written as:
996 <replaceable>variable
</replaceable> { := | = }
<replaceable>expression
</replaceable>;
998 As explained previously, the expression in such a statement is evaluated
999 by means of an SQL
<command>SELECT
</command> command sent to the main
1000 database engine. The expression must yield a single value (possibly
1001 a row value, if the variable is a row or record variable). The target
1002 variable can be a simple variable (optionally qualified with a block
1003 name), a field of a row or record target, or an element or slice of
1004 an array target. Equal (
<literal>=
</literal>) can be
1005 used instead of PL/SQL-compliant
<literal>:=
</literal>.
1009 If the expression's result data type doesn't match the variable's
1010 data type, the value will be coerced as though by an assignment cast
1011 (see
<xref linkend=
"typeconv-query"/>). If no assignment cast is known
1012 for the pair of data types involved, the
<application>PL/pgSQL
</application>
1013 interpreter will attempt to convert the result value textually, that is
1014 by applying the result type's output function followed by the variable
1015 type's input function. Note that this could result in run-time errors
1016 generated by the input function, if the string form of the result value
1017 is not acceptable to the input function.
1023 tax := subtotal *
0.06;
1024 my_record.user_id :=
20;
1026 my_array[
1:
3] := array[
1,
2,
3];
1027 complex_array[n].realpart =
12.3;
1032 <sect2 id=
"plpgsql-statements-general-sql">
1033 <title>Executing SQL Commands
</title>
1036 In general, any SQL command that does not return rows can be executed
1037 within a
<application>PL/pgSQL
</application> function just by writing
1038 the command. For example, you could create and fill a table by writing
1040 CREATE TABLE mytable (id int primary key, data text);
1041 INSERT INTO mytable VALUES (
1,'one'), (
2,'two');
1046 If the command does return rows (for example
<command>SELECT
</command>, or
1047 <command>INSERT
</command>/
<command>UPDATE
</command>/
<command>DELETE
</command>/
<command>MERGE
</command>
1048 with
<literal>RETURNING
</literal>), there are two ways to proceed.
1049 When the command will return at most one row, or you only care about
1050 the first row of output, write the command as usual but add
1051 an
<literal>INTO
</literal> clause to capture the output, as described
1052 in
<xref linkend=
"plpgsql-statements-sql-onerow"/>.
1053 To process all of the output rows, write the command as the data
1054 source for a
<command>FOR
</command> loop, as described in
1055 <xref linkend=
"plpgsql-records-iterating"/>.
1059 Usually it is not sufficient just to execute statically-defined SQL
1060 commands. Typically you'll want a command to use varying data values,
1061 or even to vary in more fundamental ways such as by using different
1062 table names at different times. Again, there are two ways to proceed
1063 depending on the situation.
1067 <application>PL/pgSQL
</application> variable values can be
1068 automatically inserted into optimizable SQL commands, which
1069 are
<command>SELECT
</command>,
<command>INSERT
</command>,
1070 <command>UPDATE
</command>,
<command>DELETE
</command>,
1071 <command>MERGE
</command>, and certain
1072 utility commands that incorporate one of these, such
1073 as
<command>EXPLAIN
</command> and
<command>CREATE TABLE ... AS
1074 SELECT
</command>. In these commands,
1075 any
<application>PL/pgSQL
</application> variable name appearing
1076 in the command text is replaced by a query parameter, and then the
1077 current value of the variable is provided as the parameter value
1078 at run time. This is exactly like the processing described earlier
1079 for expressions; for details see
<xref linkend=
"plpgsql-var-subst"/>.
1083 When executing an optimizable SQL command in this way,
1084 <application>PL/pgSQL
</application> may cache and re-use the execution
1085 plan for the command, as discussed in
1086 <xref linkend=
"plpgsql-plan-caching"/>.
1090 Non-optimizable SQL commands (also called utility commands) are not
1091 capable of accepting query parameters. So automatic substitution
1092 of
<application>PL/pgSQL
</application> variables does not work in such
1093 commands. To include non-constant text in a utility command executed
1094 from
<application>PL/pgSQL
</application>, you must build the utility
1095 command as a string and then
<command>EXECUTE
</command> it, as
1096 discussed in
<xref linkend=
"plpgsql-statements-executing-dyn"/>.
1100 <command>EXECUTE
</command> must also be used if you want to modify
1101 the command in some other way than supplying a data value, for example
1102 by changing a table name.
1106 Sometimes it is useful to evaluate an expression or
<command>SELECT
</command>
1107 query but discard the result, for example when calling a function
1108 that has side-effects but no useful result value. To do
1109 this in
<application>PL/pgSQL
</application>, use the
1110 <command>PERFORM
</command> statement:
1113 PERFORM
<replaceable>query
</replaceable>;
1116 This executes
<replaceable>query
</replaceable> and discards the
1117 result. Write the
<replaceable>query
</replaceable> the same
1118 way you would write an SQL
<command>SELECT
</command> command, but replace the
1119 initial keyword
<command>SELECT
</command> with
<command>PERFORM
</command>.
1120 For
<command>WITH
</command> queries, use
<command>PERFORM
</command> and then
1121 place the query in parentheses. (In this case, the query can only
1123 <application>PL/pgSQL
</application> variables will be
1124 substituted into the query just as described above,
1125 and the plan is cached in the same way. Also, the special variable
1126 <literal>FOUND
</literal> is set to true if the query produced at
1127 least one row, or false if it produced no rows (see
1128 <xref linkend=
"plpgsql-statements-diagnostics"/>).
1133 One might expect that writing
<command>SELECT
</command> directly
1134 would accomplish this result, but at
1135 present the only accepted way to do it is
1136 <command>PERFORM
</command>. An SQL command that can return rows,
1137 such as
<command>SELECT
</command>, will be rejected as an error
1138 unless it has an
<literal>INTO
</literal> clause as discussed in the
1146 PERFORM create_mv('cs_session_page_requests_mv', my_query);
1151 <sect2 id=
"plpgsql-statements-sql-onerow">
1152 <title>Executing a Command with a Single-Row Result
</title>
1154 <indexterm zone=
"plpgsql-statements-sql-onerow">
1155 <primary>SELECT INTO
</primary>
1156 <secondary>in PL/pgSQL
</secondary>
1159 <indexterm zone=
"plpgsql-statements-sql-onerow">
1160 <primary>RETURNING INTO
</primary>
1161 <secondary>in PL/pgSQL
</secondary>
1165 The result of an SQL command yielding a single row (possibly of multiple
1166 columns) can be assigned to a record variable, row-type variable, or list
1167 of scalar variables. This is done by writing the base SQL command and
1168 adding an
<literal>INTO
</literal> clause. For example,
1171 SELECT
<replaceable>select_expressions
</replaceable> INTO
<optional>STRICT
</optional> <replaceable>target
</replaceable> FROM ...;
1172 INSERT ... RETURNING
<replaceable>expressions
</replaceable> INTO
<optional>STRICT
</optional> <replaceable>target
</replaceable>;
1173 UPDATE ... RETURNING
<replaceable>expressions
</replaceable> INTO
<optional>STRICT
</optional> <replaceable>target
</replaceable>;
1174 DELETE ... RETURNING
<replaceable>expressions
</replaceable> INTO
<optional>STRICT
</optional> <replaceable>target
</replaceable>;
1175 MERGE ... RETURNING
<replaceable>expressions
</replaceable> INTO
<optional>STRICT
</optional> <replaceable>target
</replaceable>;
1178 where
<replaceable>target
</replaceable> can be a record variable, a row
1179 variable, or a comma-separated list of simple variables and
1181 <application>PL/pgSQL
</application> variables will be
1182 substituted into the rest of the command (that is, everything but the
1183 <literal>INTO
</literal> clause) just as described above,
1184 and the plan is cached in the same way.
1185 This works for
<command>SELECT
</command>,
1186 <command>INSERT
</command>/
<command>UPDATE
</command>/
<command>DELETE
</command>/
<command>MERGE
</command>
1187 with
<literal>RETURNING
</literal>, and certain utility commands
1188 that return row sets, such as
<command>EXPLAIN
</command>.
1189 Except for the
<literal>INTO
</literal> clause, the SQL command is the same
1190 as it would be written outside
<application>PL/pgSQL
</application>.
1195 Note that this interpretation of
<command>SELECT
</command> with
<literal>INTO
</literal>
1196 is quite different from
<productname>PostgreSQL
</productname>'s regular
1197 <command>SELECT INTO
</command> command, wherein the
<literal>INTO
</literal>
1198 target is a newly created table. If you want to create a table from a
1199 <command>SELECT
</command> result inside a
1200 <application>PL/pgSQL
</application> function, use the syntax
1201 <command>CREATE TABLE ... AS SELECT
</command>.
1206 If a row variable or a variable list is used as target,
1207 the command's result columns
1208 must exactly match the structure of the target as to number and data
1209 types, or else a run-time error
1210 occurs. When a record variable is the target, it automatically
1211 configures itself to the row type of the command's result columns.
1215 The
<literal>INTO
</literal> clause can appear almost anywhere in the SQL
1216 command. Customarily it is written either just before or just after
1217 the list of
<replaceable>select_expressions
</replaceable> in a
1218 <command>SELECT
</command> command, or at the end of the command for other
1219 command types. It is recommended that you follow this convention
1220 in case the
<application>PL/pgSQL
</application> parser becomes
1221 stricter in future versions.
1225 If
<literal>STRICT
</literal> is not specified in the
<literal>INTO
</literal>
1226 clause, then
<replaceable>target
</replaceable> will be set to the first
1227 row returned by the command, or to nulls if the command returned no rows.
1228 (Note that
<quote>the first row
</quote> is not
1229 well-defined unless you've used
<literal>ORDER BY
</literal>.) Any result rows
1230 after the first row are discarded.
1231 You can check the special
<literal>FOUND
</literal> variable (see
1232 <xref linkend=
"plpgsql-statements-diagnostics"/>) to
1233 determine whether a row was returned:
1236 SELECT * INTO myrec FROM emp WHERE empname = myname;
1238 RAISE EXCEPTION 'employee % not found', myname;
1242 If the
<literal>STRICT
</literal> option is specified, the command must
1243 return exactly one row or a run-time error will be reported, either
1244 <literal>NO_DATA_FOUND
</literal> (no rows) or
<literal>TOO_MANY_ROWS
</literal>
1245 (more than one row). You can use an exception block if you wish
1246 to catch the error, for example:
1250 SELECT * INTO STRICT myrec FROM emp WHERE empname = myname;
1252 WHEN NO_DATA_FOUND THEN
1253 RAISE EXCEPTION 'employee % not found', myname;
1254 WHEN TOO_MANY_ROWS THEN
1255 RAISE EXCEPTION 'employee % not unique', myname;
1258 Successful execution of a command with
<literal>STRICT
</literal>
1259 always sets
<literal>FOUND
</literal> to true.
1263 For
<command>INSERT
</command>/
<command>UPDATE
</command>/
<command>DELETE
</command>/
<command>MERGE
</command> with
1264 <literal>RETURNING
</literal>,
<application>PL/pgSQL
</application> reports
1265 an error for more than one returned row, even when
1266 <literal>STRICT
</literal> is not specified. This is because there
1267 is no option such as
<literal>ORDER BY
</literal> with which to determine
1268 which affected row should be returned.
1272 If
<literal>print_strict_params
</literal> is enabled for the function,
1273 then when an error is thrown because the requirements
1274 of
<literal>STRICT
</literal> are not met, the
<literal>DETAIL
</literal> part of
1275 the error message will include information about the parameters
1276 passed to the command.
1277 You can change the
<literal>print_strict_params
</literal>
1278 setting for all functions by setting
1279 <varname>plpgsql.print_strict_params
</varname>, though only subsequent
1280 function compilations will be affected. You can also enable it
1281 on a per-function basis by using a compiler option, for example:
1283 CREATE FUNCTION get_userid(username text) RETURNS int
1285 #print_strict_params on
1289 SELECT users.userid INTO STRICT userid
1290 FROM users WHERE users.username = get_userid.username;
1293 $$ LANGUAGE plpgsql;
1295 On failure, this function might produce an error message such as
1297 ERROR: query returned no rows
1298 DETAIL: parameters: username = 'nosuchuser'
1299 CONTEXT: PL/pgSQL function get_userid(text) line
6 at SQL statement
1305 The
<literal>STRICT
</literal> option matches the behavior of
1306 Oracle PL/SQL's
<command>SELECT INTO
</command> and related statements.
1312 <sect2 id=
"plpgsql-statements-executing-dyn">
1313 <title>Executing Dynamic Commands
</title>
1316 Oftentimes you will want to generate dynamic commands inside your
1317 <application>PL/pgSQL
</application> functions, that is, commands
1318 that will involve different tables or different data types each
1319 time they are executed.
<application>PL/pgSQL
</application>'s
1320 normal attempts to cache plans for commands (as discussed in
1321 <xref linkend=
"plpgsql-plan-caching"/>) will not work in such
1322 scenarios. To handle this sort of problem, the
1323 <command>EXECUTE
</command> statement is provided:
1326 EXECUTE
<replaceable class=
"command">command-string
</replaceable> <optional> INTO
<optional>STRICT
</optional> <replaceable>target
</replaceable> </optional> <optional> USING
<replaceable>expression
</replaceable> <optional>, ...
</optional> </optional>;
1329 where
<replaceable>command-string
</replaceable> is an expression
1330 yielding a string (of type
<type>text
</type>) containing the
1331 command to be executed. The optional
<replaceable>target
</replaceable>
1332 is a record variable, a row variable, or a comma-separated list of
1333 simple variables and record/row fields, into which the results of
1334 the command will be stored. The optional
<literal>USING
</literal> expressions
1335 supply values to be inserted into the command.
1339 No substitution of
<application>PL/pgSQL
</application> variables is done on the
1340 computed command string. Any required variable values must be inserted
1341 in the command string as it is constructed; or you can use parameters
1346 Also, there is no plan caching for commands executed via
1347 <command>EXECUTE
</command>. Instead, the command is always planned
1348 each time the statement is run. Thus the command
1349 string can be dynamically created within the function to perform
1350 actions on different tables and columns.
1354 The
<literal>INTO
</literal> clause specifies where the results of
1355 an SQL command returning rows should be assigned. If a row variable
1356 or variable list is provided, it must exactly match the structure
1357 of the command's results; if a
1358 record variable is provided, it will configure itself to match the
1359 result structure automatically. If multiple rows are returned,
1360 only the first will be assigned to the
<literal>INTO
</literal>
1361 variable(s). If no rows are returned, NULL is assigned to the
1362 <literal>INTO
</literal> variable(s). If no
<literal>INTO
</literal>
1363 clause is specified, the command results are discarded.
1367 If the
<literal>STRICT
</literal> option is given, an error is reported
1368 unless the command produces exactly one row.
1372 The command string can use parameter values, which are referenced
1373 in the command as
<literal>$
1</literal>,
<literal>$
2</literal>, etc.
1374 These symbols refer to values supplied in the
<literal>USING
</literal>
1375 clause. This method is often preferable to inserting data values
1376 into the command string as text: it avoids run-time overhead of
1377 converting the values to text and back, and it is much less prone
1378 to SQL-injection attacks since there is no need for quoting or escaping.
1381 EXECUTE 'SELECT count(*) FROM mytable WHERE inserted_by = $
1 AND inserted
<= $
2'
1383 USING checked_user, checked_date;
1388 Note that parameter symbols can only be used for data values
1389 — if you want to use dynamically determined table or column
1390 names, you must insert them into the command string textually.
1391 For example, if the preceding query needed to be done against a
1392 dynamically selected table, you could do this:
1394 EXECUTE 'SELECT count(*) FROM '
1395 || quote_ident(tabname)
1396 || ' WHERE inserted_by = $
1 AND inserted
<= $
2'
1398 USING checked_user, checked_date;
1400 A cleaner approach is to use
<function>format()
</function>'s
<literal>%I
</literal>
1401 specification to insert table or column names with automatic quoting:
1403 EXECUTE format('SELECT count(*) FROM %I '
1404 'WHERE inserted_by = $
1 AND inserted
<= $
2', tabname)
1406 USING checked_user, checked_date;
1408 (This example relies on the SQL rule that string literals separated by a
1409 newline are implicitly concatenated.)
1413 Another restriction on parameter symbols is that they only work in
1414 optimizable SQL commands
1415 (
<command>SELECT
</command>,
<command>INSERT
</command>,
<command>UPDATE
</command>,
1416 <command>DELETE
</command>,
<command>MERGE
</command>, and certain commands containing one of these).
1418 types (generically called utility statements), you must insert
1419 values textually even if they are just data values.
1423 An
<command>EXECUTE
</command> with a simple constant command string and some
1424 <literal>USING
</literal> parameters, as in the first example above, is
1425 functionally equivalent to just writing the command directly in
1426 <application>PL/pgSQL
</application> and allowing replacement of
1427 <application>PL/pgSQL
</application> variables to happen automatically.
1428 The important difference is that
<command>EXECUTE
</command> will re-plan
1429 the command on each execution, generating a plan that is specific
1430 to the current parameter values; whereas
1431 <application>PL/pgSQL
</application> may otherwise create a generic plan
1432 and cache it for re-use. In situations where the best plan depends
1433 strongly on the parameter values, it can be helpful to use
1434 <command>EXECUTE
</command> to positively ensure that a generic plan is not
1439 <command>SELECT INTO
</command> is not currently supported within
1440 <command>EXECUTE
</command>; instead, execute a plain
<command>SELECT
</command>
1441 command and specify
<literal>INTO
</literal> as part of the
<command>EXECUTE
</command>
1447 The
<application>PL/pgSQL
</application>
1448 <command>EXECUTE
</command> statement is not related to the
1449 <link linkend=
"sql-execute"><command>EXECUTE
</command></link> SQL
1450 statement supported by the
1451 <productname>PostgreSQL
</productname> server. The server's
1452 <command>EXECUTE
</command> statement cannot be used directly within
1453 <application>PL/pgSQL
</application> functions (and is not needed).
1457 <example id=
"plpgsql-quote-literal-example">
1458 <title>Quoting Values in Dynamic Queries
</title>
1461 <primary>quote_ident
</primary>
1462 <secondary>use in PL/pgSQL
</secondary>
1466 <primary>quote_literal
</primary>
1467 <secondary>use in PL/pgSQL
</secondary>
1471 <primary>quote_nullable
</primary>
1472 <secondary>use in PL/pgSQL
</secondary>
1476 <primary>format
</primary>
1477 <secondary>use in PL/pgSQL
</secondary>
1481 When working with dynamic commands you will often have to handle escaping
1482 of single quotes. The recommended method for quoting fixed text in your
1483 function body is dollar quoting. (If you have legacy code that does
1484 not use dollar quoting, please refer to the
1485 overview in
<xref linkend=
"plpgsql-quote-tips"/>, which can save you
1486 some effort when translating said code to a more reasonable scheme.)
1490 Dynamic values require careful handling since they might contain
1492 An example using
<function>format()
</function> (this assumes that you are
1493 dollar quoting the function body so quote marks need not be doubled):
1495 EXECUTE format('UPDATE tbl SET %I = $
1 '
1496 'WHERE key = $
2', colname) USING newvalue, keyvalue;
1498 It is also possible to call the quoting functions directly:
1500 EXECUTE 'UPDATE tbl SET '
1501 || quote_ident(colname)
1503 || quote_literal(newvalue)
1505 || quote_literal(keyvalue);
1510 This example demonstrates the use of the
1511 <function>quote_ident
</function> and
1512 <function>quote_literal
</function> functions (see
<xref
1513 linkend=
"functions-string"/>). For safety, expressions containing column
1514 or table identifiers should be passed through
1515 <function>quote_ident
</function> before insertion in a dynamic query.
1516 Expressions containing values that should be literal strings in the
1517 constructed command should be passed through
<function>quote_literal
</function>.
1518 These functions take the appropriate steps to return the input text
1519 enclosed in double or single quotes respectively, with any embedded
1520 special characters properly escaped.
1524 Because
<function>quote_literal
</function> is labeled
1525 <literal>STRICT
</literal>, it will always return null when called with a
1526 null argument. In the above example, if
<literal>newvalue
</literal> or
1527 <literal>keyvalue
</literal> were null, the entire dynamic query string would
1528 become null, leading to an error from
<command>EXECUTE
</command>.
1529 You can avoid this problem by using the
<function>quote_nullable
</function>
1530 function, which works the same as
<function>quote_literal
</function> except that
1531 when called with a null argument it returns the string
<literal>NULL
</literal>.
1534 EXECUTE 'UPDATE tbl SET '
1535 || quote_ident(colname)
1537 || quote_nullable(newvalue)
1539 || quote_nullable(keyvalue);
1541 If you are dealing with values that might be null, you should usually
1542 use
<function>quote_nullable
</function> in place of
<function>quote_literal
</function>.
1546 As always, care must be taken to ensure that null values in a query do
1547 not deliver unintended results. For example the
<literal>WHERE
</literal> clause
1549 'WHERE key = ' || quote_nullable(keyvalue)
1551 will never succeed if
<literal>keyvalue
</literal> is null, because the
1552 result of using the equality operator
<literal>=
</literal> with a null operand
1553 is always null. If you wish null to work like an ordinary key value,
1554 you would need to rewrite the above as
1556 'WHERE key IS NOT DISTINCT FROM ' || quote_nullable(keyvalue)
1558 (At present,
<literal>IS NOT DISTINCT FROM
</literal> is handled much less
1559 efficiently than
<literal>=
</literal>, so don't do this unless you must.
1560 See
<xref linkend=
"functions-comparison"/> for
1561 more information on nulls and
<literal>IS DISTINCT
</literal>.)
1565 Note that dollar quoting is only useful for quoting fixed text.
1566 It would be a very bad idea to try to write this example as:
1568 EXECUTE 'UPDATE tbl SET '
1569 || quote_ident(colname)
1572 || '$$ WHERE key = '
1573 || quote_literal(keyvalue);
1575 because it would break if the contents of
<literal>newvalue
</literal>
1576 happened to contain
<literal>$$
</literal>. The same objection would
1577 apply to any other dollar-quoting delimiter you might pick.
1578 So, to safely quote text that is not known in advance, you
1579 <emphasis>must
</emphasis> use
<function>quote_literal
</function>,
1580 <function>quote_nullable
</function>, or
<function>quote_ident
</function>, as appropriate.
1584 Dynamic SQL statements can also be safely constructed using the
1585 <function>format
</function> function (see
<xref
1586 linkend=
"functions-string-format"/>). For example:
1588 EXECUTE format('UPDATE tbl SET %I = %L '
1589 'WHERE key = %L', colname, newvalue, keyvalue);
1591 <literal>%I
</literal> is equivalent to
<function>quote_ident
</function>, and
1592 <literal>%L
</literal> is equivalent to
<function>quote_nullable
</function>.
1593 The
<function>format
</function> function can be used in conjunction with
1594 the
<literal>USING
</literal> clause:
1596 EXECUTE format('UPDATE tbl SET %I = $
1 WHERE key = $
2', colname)
1597 USING newvalue, keyvalue;
1599 This form is better because the variables are handled in their native
1600 data type format, rather than unconditionally converting them to
1601 text and quoting them via
<literal>%L
</literal>. It is also more efficient.
1606 A much larger example of a dynamic command and
1607 <command>EXECUTE
</command> can be seen in
<xref
1608 linkend=
"plpgsql-porting-ex2"/>, which builds and executes a
1609 <command>CREATE FUNCTION
</command> command to define a new function.
1613 <sect2 id=
"plpgsql-statements-diagnostics">
1614 <title>Obtaining the Result Status
</title>
1617 There are several ways to determine the effect of a command. The
1618 first method is to use the
<command>GET DIAGNOSTICS
</command>
1619 command, which has the form:
1622 GET
<optional> CURRENT
</optional> DIAGNOSTICS
<replaceable>variable
</replaceable> { = | := }
<replaceable>item
</replaceable> <optional> , ...
</optional>;
1625 This command allows retrieval of system status indicators.
1626 <literal>CURRENT
</literal> is a noise word (but see also
<command>GET STACKED
1627 DIAGNOSTICS
</command> in
<xref linkend=
"plpgsql-exception-diagnostics"/>).
1628 Each
<replaceable>item
</replaceable> is a key word identifying a status
1629 value to be assigned to the specified
<replaceable>variable
</replaceable>
1630 (which should be of the right data type to receive it). The currently
1631 available status items are shown
1632 in
<xref linkend=
"plpgsql-current-diagnostics-values"/>. Colon-equal
1633 (
<literal>:=
</literal>) can be used instead of the SQL-standard
<literal>=
</literal>
1636 GET DIAGNOSTICS integer_var = ROW_COUNT;
1640 <table id=
"plpgsql-current-diagnostics-values">
1641 <title>Available Diagnostics Items
</title>
1643 <colspec colname=
"col1" colwidth=
"1*"/>
1644 <colspec colname=
"col2" colwidth=
"1*"/>
1645 <colspec colname=
"col3" colwidth=
"2*"/>
1650 <entry>Description
</entry>
1655 <entry><varname>ROW_COUNT
</varname></entry>
1656 <entry><type>bigint
</type></entry>
1657 <entry>the number of rows processed by the most
1658 recent
<acronym>SQL
</acronym> command
</entry>
1661 <entry><literal>PG_CONTEXT
</literal></entry>
1662 <entry><type>text
</type></entry>
1663 <entry>line(s) of text describing the current call stack
1664 (see
<xref linkend=
"plpgsql-call-stack"/>)
</entry>
1667 <entry><literal>PG_ROUTINE_OID
</literal></entry>
1668 <entry><type>oid
</type></entry>
1669 <entry>OID of the current function
</entry>
1676 The second method to determine the effects of a command is to check the
1677 special variable named
<literal>FOUND
</literal>, which is of
1678 type
<type>boolean
</type>.
<literal>FOUND
</literal> starts out
1679 false within each
<application>PL/pgSQL
</application> function call.
1680 It is set by each of the following types of statements:
1685 A
<command>SELECT INTO
</command> statement sets
1686 <literal>FOUND
</literal> true if a row is assigned, false if no
1692 A
<command>PERFORM
</command> statement sets
<literal>FOUND
</literal>
1693 true if it produces (and discards) one or more rows, false if
1699 <command>UPDATE
</command>,
<command>INSERT
</command>,
<command>DELETE
</command>,
1700 and
<command>MERGE
</command>
1701 statements set
<literal>FOUND
</literal> true if at least one
1702 row is affected, false if no row is affected.
1707 A
<command>FETCH
</command> statement sets
<literal>FOUND
</literal>
1708 true if it returns a row, false if no row is returned.
1713 A
<command>MOVE
</command> statement sets
<literal>FOUND
</literal>
1714 true if it successfully repositions the cursor, false otherwise.
1719 A
<command>FOR
</command> or
<command>FOREACH
</command> statement sets
1720 <literal>FOUND
</literal> true
1721 if it iterates one or more times, else false.
1722 <literal>FOUND
</literal> is set this way when the
1723 loop exits; inside the execution of the loop,
1724 <literal>FOUND
</literal> is not modified by the
1725 loop statement, although it might be changed by the
1726 execution of other statements within the loop body.
1731 <command>RETURN QUERY
</command> and
<command>RETURN QUERY
1732 EXECUTE
</command> statements set
<literal>FOUND
</literal>
1733 true if the query returns at least one row, false if no row
1739 Other
<application>PL/pgSQL
</application> statements do not change
1740 the state of
<literal>FOUND
</literal>.
1741 Note in particular that
<command>EXECUTE
</command>
1742 changes the output of
<command>GET DIAGNOSTICS
</command>, but
1743 does not change
<literal>FOUND
</literal>.
1747 <literal>FOUND
</literal> is a local variable within each
1748 <application>PL/pgSQL
</application> function; any changes to it
1749 affect only the current function.
1754 <sect2 id=
"plpgsql-statements-null">
1755 <title>Doing Nothing At All
</title>
1758 Sometimes a placeholder statement that does nothing is useful.
1759 For example, it can indicate that one arm of an if/then/else
1760 chain is deliberately empty. For this purpose, use the
1761 <command>NULL
</command> statement:
1769 For example, the following two fragments of code are equivalent:
1774 WHEN division_by_zero THEN
1775 NULL; -- ignore the error
1783 WHEN division_by_zero THEN -- ignore the error
1786 Which is preferable is a matter of taste.
1791 In Oracle's PL/SQL, empty statement lists are not allowed, and so
1792 <command>NULL
</command> statements are
<emphasis>required
</emphasis> for situations
1793 such as this.
<application>PL/pgSQL
</application> allows you to
1794 just write nothing, instead.
1801 <sect1 id=
"plpgsql-control-structures">
1802 <title>Control Structures
</title>
1805 Control structures are probably the most useful (and
1806 important) part of
<application>PL/pgSQL
</application>. With
1807 <application>PL/pgSQL
</application>'s control structures,
1808 you can manipulate
<productname>PostgreSQL
</productname> data in a very
1809 flexible and powerful way.
1812 <sect2 id=
"plpgsql-statements-returning">
1813 <title>Returning from a Function
</title>
1816 There are two commands available that allow you to return data
1817 from a function:
<command>RETURN
</command> and
<command>RETURN
1821 <sect3 id=
"plpgsql-statements-returning-return">
1822 <title><command>RETURN
</command></title>
1825 RETURN
<replaceable>expression
</replaceable>;
1829 <command>RETURN
</command> with an expression terminates the
1830 function and returns the value of
1831 <replaceable>expression
</replaceable> to the caller. This form
1832 is used for
<application>PL/pgSQL
</application> functions that do
1837 In a function that returns a scalar type, the expression's result will
1838 automatically be cast into the function's return type as described for
1839 assignments. But to return a composite (row) value, you must write an
1840 expression delivering exactly the requested column set. This may
1841 require use of explicit casting.
1845 If you declared the function with output parameters, write just
1846 <command>RETURN
</command> with no expression. The current values
1847 of the output parameter variables will be returned.
1851 If you declared the function to return
<type>void
</type>, a
1852 <command>RETURN
</command> statement can be used to exit the function
1853 early; but do not write an expression following
1854 <command>RETURN
</command>.
1858 The return value of a function cannot be left undefined. If
1859 control reaches the end of the top-level block of the function
1860 without hitting a
<command>RETURN
</command> statement, a run-time
1861 error will occur. This restriction does not apply to functions
1862 with output parameters and functions returning
<type>void
</type>,
1863 however. In those cases a
<command>RETURN
</command> statement is
1864 automatically executed if the top-level block finishes.
1871 -- functions returning a scalar type
1875 -- functions returning a composite type
1876 RETURN composite_type_var;
1877 RETURN (
1,
2, 'three'::text); -- must cast columns to correct types
1882 <sect3 id=
"plpgsql-statements-returning-return-next">
1883 <title><command>RETURN NEXT
</command> and
<command>RETURN QUERY
</command></title>
1885 <primary>RETURN NEXT
</primary>
1886 <secondary>in PL/pgSQL
</secondary>
1889 <primary>RETURN QUERY
</primary>
1890 <secondary>in PL/pgSQL
</secondary>
1894 RETURN NEXT
<replaceable>expression
</replaceable>;
1895 RETURN QUERY
<replaceable>query
</replaceable>;
1896 RETURN QUERY EXECUTE
<replaceable class=
"command">command-string
</replaceable> <optional> USING
<replaceable>expression
</replaceable> <optional>, ...
</optional> </optional>;
1900 When a
<application>PL/pgSQL
</application> function is declared to return
1901 <literal>SETOF
<replaceable>sometype
</replaceable></literal>, the procedure
1902 to follow is slightly different. In that case, the individual
1903 items to return are specified by a sequence of
<command>RETURN
1904 NEXT
</command> or
<command>RETURN QUERY
</command> commands, and
1905 then a final
<command>RETURN
</command> command with no argument
1906 is used to indicate that the function has finished executing.
1907 <command>RETURN NEXT
</command> can be used with both scalar and
1908 composite data types; with a composite result type, an entire
1909 <quote>table
</quote> of results will be returned.
1910 <command>RETURN QUERY
</command> appends the results of executing
1911 a query to the function's result set.
<command>RETURN
1912 NEXT
</command> and
<command>RETURN QUERY
</command> can be freely
1913 intermixed in a single set-returning function, in which case
1914 their results will be concatenated.
1918 <command>RETURN NEXT
</command> and
<command>RETURN
1919 QUERY
</command> do not actually return from the function
—
1920 they simply append zero or more rows to the function's result
1921 set. Execution then continues with the next statement in the
1922 <application>PL/pgSQL
</application> function. As successive
1923 <command>RETURN NEXT
</command> or
<command>RETURN
1924 QUERY
</command> commands are executed, the result set is built
1925 up. A final
<command>RETURN
</command>, which should have no
1926 argument, causes control to exit the function (or you can just
1927 let control reach the end of the function).
1931 <command>RETURN QUERY
</command> has a variant
1932 <command>RETURN QUERY EXECUTE
</command>, which specifies the
1933 query to be executed dynamically. Parameter expressions can
1934 be inserted into the computed query string via
<literal>USING
</literal>,
1935 in just the same way as in the
<command>EXECUTE
</command> command.
1939 If you declared the function with output parameters, write just
1940 <command>RETURN NEXT
</command> with no expression. On each
1941 execution, the current values of the output parameter
1942 variable(s) will be saved for eventual return as a row of the
1943 result. Note that you must declare the function as returning
1944 <literal>SETOF record
</literal> when there are multiple output
1945 parameters, or
<literal>SETOF
<replaceable>sometype
</replaceable></literal>
1946 when there is just one output parameter of type
1947 <replaceable>sometype
</replaceable>, in order to create a set-returning
1948 function with output parameters.
1952 Here is an example of a function using
<command>RETURN
1956 CREATE TABLE foo (fooid INT, foosubid INT, fooname TEXT);
1957 INSERT INTO foo VALUES (
1,
2, 'three');
1958 INSERT INTO foo VALUES (
4,
5, 'six');
1960 CREATE OR REPLACE FUNCTION get_all_foo() RETURNS SETOF foo AS
1966 SELECT * FROM foo WHERE fooid
> 0
1968 -- can do some processing here
1969 RETURN NEXT r; -- return current row of SELECT
1976 SELECT * FROM get_all_foo();
1981 Here is an example of a function using
<command>RETURN
1985 CREATE FUNCTION get_available_flightid(date) RETURNS SETOF integer AS
1988 RETURN QUERY SELECT flightid
1990 WHERE flightdate
>= $
1
1991 AND flightdate
< ($
1 +
1);
1993 -- Since execution is not finished, we can check whether rows were returned
1994 -- and raise exception if not.
1996 RAISE EXCEPTION 'No flight at %.', $
1;
2004 -- Returns available flights or raises exception if there are no
2005 -- available flights.
2006 SELECT * FROM get_available_flightid(CURRENT_DATE);
2012 The current implementation of
<command>RETURN NEXT
</command>
2013 and
<command>RETURN QUERY
</command> stores the entire result set
2014 before returning from the function, as discussed above. That
2015 means that if a
<application>PL/pgSQL
</application> function produces a
2016 very large result set, performance might be poor: data will be
2017 written to disk to avoid memory exhaustion, but the function
2018 itself will not return until the entire result set has been
2019 generated. A future version of
<application>PL/pgSQL
</application> might
2020 allow users to define set-returning functions
2021 that do not have this limitation. Currently, the point at
2022 which data begins being written to disk is controlled by the
2023 <xref linkend=
"guc-work-mem"/>
2024 configuration variable. Administrators who have sufficient
2025 memory to store larger result sets in memory should consider
2026 increasing this parameter.
2032 <sect2 id=
"plpgsql-statements-returning-procedure">
2033 <title>Returning from a Procedure
</title>
2036 A procedure does not have a return value. A procedure can therefore end
2037 without a
<command>RETURN
</command> statement. If you wish to use
2038 a
<command>RETURN
</command> statement to exit the code early, write
2039 just
<command>RETURN
</command> with no expression.
2043 If the procedure has output parameters, the final values of the output
2044 parameter variables will be returned to the caller.
2048 <sect2 id=
"plpgsql-statements-calling-procedure">
2049 <title>Calling a Procedure
</title>
2052 A
<application>PL/pgSQL
</application> function, procedure,
2053 or
<command>DO
</command> block can call a procedure
2054 using
<command>CALL
</command>. Output parameters are handled
2055 differently from the way that
<command>CALL
</command> works in plain
2056 SQL. Each
<literal>OUT
</literal> or
<literal>INOUT
</literal>
2057 parameter of the procedure must
2058 correspond to a variable in the
<command>CALL
</command> statement, and
2059 whatever the procedure returns is assigned back to that variable after
2060 it returns. For example:
2062 CREATE PROCEDURE triple(INOUT x int)
2071 DECLARE myvar int :=
5;
2074 RAISE NOTICE 'myvar = %', myvar; -- prints
15
2078 The variable corresponding to an output parameter can be a simple
2079 variable or a field of a composite-type variable. Currently,
2080 it cannot be an element of an array.
2084 <sect2 id=
"plpgsql-conditionals">
2085 <title>Conditionals
</title>
2088 <command>IF
</command> and
<command>CASE
</command> statements let you execute
2089 alternative commands based on certain conditions.
2090 <application>PL/pgSQL
</application> has three forms of
<command>IF
</command>:
2093 <para><literal>IF ... THEN ... END IF
</literal></para>
2096 <para><literal>IF ... THEN ... ELSE ... END IF
</literal></para>
2099 <para><literal>IF ... THEN ... ELSIF ... THEN ... ELSE ... END IF
</literal></para>
2103 and two forms of
<command>CASE
</command>:
2106 <para><literal>CASE ... WHEN ... THEN ... ELSE ... END CASE
</literal></para>
2109 <para><literal>CASE WHEN ... THEN ... ELSE ... END CASE
</literal></para>
2114 <sect3 id=
"plpgsql-conditionals-if-then">
2115 <title><literal>IF-THEN
</literal></title>
2118 IF
<replaceable>boolean-expression
</replaceable> THEN
2119 <replaceable>statements
</replaceable>
2124 <literal>IF-THEN
</literal> statements are the simplest form of
2125 <literal>IF
</literal>. The statements between
2126 <literal>THEN
</literal> and
<literal>END IF
</literal> will be
2127 executed if the condition is true. Otherwise, they are
2134 IF v_user_id
<> 0 THEN
2135 UPDATE users SET email = v_email WHERE user_id = v_user_id;
2141 <sect3 id=
"plpgsql-conditionals-if-then-else">
2142 <title><literal>IF-THEN-ELSE
</literal></title>
2145 IF
<replaceable>boolean-expression
</replaceable> THEN
2146 <replaceable>statements
</replaceable>
2148 <replaceable>statements
</replaceable>
2153 <literal>IF-THEN-ELSE
</literal> statements add to
2154 <literal>IF-THEN
</literal> by letting you specify an
2155 alternative set of statements that should be executed if the
2156 condition is not true. (Note this includes the case where the
2157 condition evaluates to NULL.)
2163 IF parentid IS NULL OR parentid = ''
2167 RETURN hp_true_filename(parentid) || '/' || fullname;
2172 IF v_count
> 0 THEN
2173 INSERT INTO users_count (count) VALUES (v_count);
2182 <sect3 id=
"plpgsql-conditionals-if-then-elsif">
2183 <title><literal>IF-THEN-ELSIF
</literal></title>
2186 IF
<replaceable>boolean-expression
</replaceable> THEN
2187 <replaceable>statements
</replaceable>
2188 <optional> ELSIF
<replaceable>boolean-expression
</replaceable> THEN
2189 <replaceable>statements
</replaceable>
2190 <optional> ELSIF
<replaceable>boolean-expression
</replaceable> THEN
2191 <replaceable>statements
</replaceable>
2196 <replaceable>statements
</replaceable> </optional>
2201 Sometimes there are more than just two alternatives.
2202 <literal>IF-THEN-ELSIF
</literal> provides a convenient
2203 method of checking several alternatives in turn.
2204 The
<literal>IF
</literal> conditions are tested successively
2205 until the first one that is true is found. Then the
2206 associated statement(s) are executed, after which control
2207 passes to the next statement after
<literal>END IF
</literal>.
2208 (Any subsequent
<literal>IF
</literal> conditions are
<emphasis>not
</emphasis>
2209 tested.) If none of the
<literal>IF
</literal> conditions is true,
2210 then the
<literal>ELSE
</literal> block (if any) is executed.
2219 ELSIF number
> 0 THEN
2220 result := 'positive';
2221 ELSIF number
< 0 THEN
2222 result := 'negative';
2224 -- hmm, the only other possibility is that number is null
2231 The key word
<literal>ELSIF
</literal> can also be spelled
2232 <literal>ELSEIF
</literal>.
2236 An alternative way of accomplishing the same task is to nest
2237 <literal>IF-THEN-ELSE
</literal> statements, as in the
2241 IF demo_row.sex = 'm' THEN
2242 pretty_sex := 'man';
2244 IF demo_row.sex = 'f' THEN
2245 pretty_sex := 'woman';
2252 However, this method requires writing a matching
<literal>END IF
</literal>
2253 for each
<literal>IF
</literal>, so it is much more cumbersome than
2254 using
<literal>ELSIF
</literal> when there are many alternatives.
2258 <sect3 id=
"plpgsql-conditionals-simple-case">
2259 <title>Simple
<literal>CASE
</literal></title>
2262 CASE
<replaceable>search-expression
</replaceable>
2263 WHEN
<replaceable>expression
</replaceable> <optional>,
<replaceable>expression
</replaceable> <optional> ...
</optional></optional> THEN
2264 <replaceable>statements
</replaceable>
2265 <optional> WHEN
<replaceable>expression
</replaceable> <optional>,
<replaceable>expression
</replaceable> <optional> ...
</optional></optional> THEN
2266 <replaceable>statements
</replaceable>
2269 <replaceable>statements
</replaceable> </optional>
2274 The simple form of
<command>CASE
</command> provides conditional execution
2275 based on equality of operands. The
<replaceable>search-expression
</replaceable>
2276 is evaluated (once) and successively compared to each
2277 <replaceable>expression
</replaceable> in the
<literal>WHEN
</literal> clauses.
2278 If a match is found, then the corresponding
2279 <replaceable>statements
</replaceable> are executed, and then control
2280 passes to the next statement after
<literal>END CASE
</literal>. (Subsequent
2281 <literal>WHEN
</literal> expressions are not evaluated.) If no match is
2282 found, the
<literal>ELSE
</literal> <replaceable>statements
</replaceable> are
2283 executed; but if
<literal>ELSE
</literal> is not present, then a
2284 <literal>CASE_NOT_FOUND
</literal> exception is raised.
2288 Here is a simple example:
2293 msg := 'one or two';
2295 msg := 'other value than one or two';
2301 <sect3 id=
"plpgsql-conditionals-searched-case">
2302 <title>Searched
<literal>CASE
</literal></title>
2306 WHEN
<replaceable>boolean-expression
</replaceable> THEN
2307 <replaceable>statements
</replaceable>
2308 <optional> WHEN
<replaceable>boolean-expression
</replaceable> THEN
2309 <replaceable>statements
</replaceable>
2312 <replaceable>statements
</replaceable> </optional>
2317 The searched form of
<command>CASE
</command> provides conditional execution
2318 based on truth of Boolean expressions. Each
<literal>WHEN
</literal> clause's
2319 <replaceable>boolean-expression
</replaceable> is evaluated in turn,
2320 until one is found that yields
<literal>true
</literal>. Then the
2321 corresponding
<replaceable>statements
</replaceable> are executed, and
2322 then control passes to the next statement after
<literal>END CASE
</literal>.
2323 (Subsequent
<literal>WHEN
</literal> expressions are not evaluated.)
2324 If no true result is found, the
<literal>ELSE
</literal>
2325 <replaceable>statements
</replaceable> are executed;
2326 but if
<literal>ELSE
</literal> is not present, then a
2327 <literal>CASE_NOT_FOUND
</literal> exception is raised.
2335 WHEN x BETWEEN
0 AND
10 THEN
2336 msg := 'value is between zero and ten';
2337 WHEN x BETWEEN
11 AND
20 THEN
2338 msg := 'value is between eleven and twenty';
2344 This form of
<command>CASE
</command> is entirely equivalent to
2345 <literal>IF-THEN-ELSIF
</literal>, except for the rule that reaching
2346 an omitted
<literal>ELSE
</literal> clause results in an error rather
2353 <sect2 id=
"plpgsql-control-structures-loops">
2354 <title>Simple Loops
</title>
2356 <indexterm zone=
"plpgsql-control-structures-loops">
2357 <primary>loop
</primary>
2358 <secondary>in PL/pgSQL
</secondary>
2362 With the
<literal>LOOP
</literal>,
<literal>EXIT
</literal>,
2363 <literal>CONTINUE
</literal>,
<literal>WHILE
</literal>,
<literal>FOR
</literal>,
2364 and
<literal>FOREACH
</literal> statements, you can arrange for your
2365 <application>PL/pgSQL
</application> function to repeat a series of commands.
2368 <sect3 id=
"plpgsql-control-structures-loops-loop">
2369 <title><literal>LOOP
</literal></title>
2372 <optional> <<<replaceable>label
</replaceable>>> </optional>
2374 <replaceable>statements
</replaceable>
2375 END LOOP
<optional> <replaceable>label
</replaceable> </optional>;
2379 <literal>LOOP
</literal> defines an unconditional loop that is repeated
2380 indefinitely until terminated by an
<literal>EXIT
</literal> or
2381 <command>RETURN
</command> statement. The optional
2382 <replaceable>label
</replaceable> can be used by
<literal>EXIT
</literal>
2383 and
<literal>CONTINUE
</literal> statements within nested loops to
2384 specify which loop those statements refer to.
2388 <sect3 id=
"plpgsql-control-structures-loops-exit">
2389 <title><literal>EXIT
</literal></title>
2392 <primary>EXIT
</primary>
2393 <secondary>in PL/pgSQL
</secondary>
2397 EXIT
<optional> <replaceable>label
</replaceable> </optional> <optional> WHEN
<replaceable>boolean-expression
</replaceable> </optional>;
2401 If no
<replaceable>label
</replaceable> is given, the innermost
2402 loop is terminated and the statement following
<literal>END
2403 LOOP
</literal> is executed next. If
<replaceable>label
</replaceable>
2404 is given, it must be the label of the current or some outer
2405 level of nested loop or block. Then the named loop or block is
2406 terminated and control continues with the statement after the
2407 loop's/block's corresponding
<literal>END
</literal>.
2411 If
<literal>WHEN
</literal> is specified, the loop exit occurs only if
2412 <replaceable>boolean-expression
</replaceable> is true. Otherwise, control passes
2413 to the statement after
<literal>EXIT
</literal>.
2417 <literal>EXIT
</literal> can be used with all types of loops; it is
2418 not limited to use with unconditional loops.
2423 <literal>BEGIN
</literal> block,
<literal>EXIT
</literal> passes
2424 control to the next statement after the end of the block.
2425 Note that a label must be used for this purpose; an unlabeled
2426 <literal>EXIT
</literal> is never considered to match a
2427 <literal>BEGIN
</literal> block. (This is a change from
2428 pre-
8.4 releases of
<productname>PostgreSQL
</productname>, which
2429 would allow an unlabeled
<literal>EXIT
</literal> to match
2430 a
<literal>BEGIN
</literal> block.)
2437 -- some computations
2438 IF count
> 0 THEN
2444 -- some computations
2445 EXIT WHEN count
> 0; -- same result as previous example
2448 <<ablock
>>
2450 -- some computations
2451 IF stocks
> 100000 THEN
2452 EXIT ablock; -- causes exit from the BEGIN block
2454 -- computations here will be skipped when stocks
> 100000
2460 <sect3 id=
"plpgsql-control-structures-loops-continue">
2461 <title><literal>CONTINUE
</literal></title>
2464 <primary>CONTINUE
</primary>
2465 <secondary>in PL/pgSQL
</secondary>
2469 CONTINUE
<optional> <replaceable>label
</replaceable> </optional> <optional> WHEN
<replaceable>boolean-expression
</replaceable> </optional>;
2473 If no
<replaceable>label
</replaceable> is given, the next iteration of
2474 the innermost loop is begun. That is, all statements remaining
2475 in the loop body are skipped, and control returns
2476 to the loop control expression (if any) to determine whether
2477 another loop iteration is needed.
2478 If
<replaceable>label
</replaceable> is present, it
2479 specifies the label of the loop whose execution will be
2484 If
<literal>WHEN
</literal> is specified, the next iteration of the
2485 loop is begun only if
<replaceable>boolean-expression
</replaceable> is
2486 true. Otherwise, control passes to the statement after
2487 <literal>CONTINUE
</literal>.
2491 <literal>CONTINUE
</literal> can be used with all types of loops; it
2492 is not limited to use with unconditional loops.
2499 -- some computations
2500 EXIT WHEN count
> 100;
2501 CONTINUE WHEN count
< 50;
2502 -- some computations for count IN [
50 ..
100]
2509 <sect3 id=
"plpgsql-control-structures-loops-while">
2510 <title><literal>WHILE
</literal></title>
2513 <primary>WHILE
</primary>
2514 <secondary>in PL/pgSQL
</secondary>
2518 <optional> <<<replaceable>label
</replaceable>>> </optional>
2519 WHILE
<replaceable>boolean-expression
</replaceable> LOOP
2520 <replaceable>statements
</replaceable>
2521 END LOOP
<optional> <replaceable>label
</replaceable> </optional>;
2525 The
<literal>WHILE
</literal> statement repeats a
2526 sequence of statements so long as the
2527 <replaceable>boolean-expression
</replaceable>
2528 evaluates to true. The expression is checked just before
2529 each entry to the loop body.
2535 WHILE amount_owed
> 0 AND gift_certificate_balance
> 0 LOOP
2536 -- some computations here
2540 -- some computations here
2546 <sect3 id=
"plpgsql-integer-for">
2547 <title><literal>FOR
</literal> (Integer Variant)
</title>
2550 <optional> <<<replaceable>label
</replaceable>>> </optional>
2551 FOR
<replaceable>name
</replaceable> IN
<optional> REVERSE
</optional> <replaceable>expression
</replaceable> ..
<replaceable>expression
</replaceable> <optional> BY
<replaceable>expression
</replaceable> </optional> LOOP
2552 <replaceable>statements
</replaceable>
2553 END LOOP
<optional> <replaceable>label
</replaceable> </optional>;
2557 This form of
<literal>FOR
</literal> creates a loop that iterates over a range
2558 of integer values. The variable
2559 <replaceable>name
</replaceable> is automatically defined as type
2560 <type>integer
</type> and exists only inside the loop (any existing
2561 definition of the variable name is ignored within the loop).
2562 The two expressions giving
2563 the lower and upper bound of the range are evaluated once when entering
2564 the loop. If the
<literal>BY
</literal> clause isn't specified the iteration
2565 step is
1, otherwise it's the value specified in the
<literal>BY
</literal>
2566 clause, which again is evaluated once on loop entry.
2567 If
<literal>REVERSE
</literal> is specified then the step value is
2568 subtracted, rather than added, after each iteration.
2572 Some examples of integer
<literal>FOR
</literal> loops:
2575 -- i will take on the values
1,
2,
3,
4,
5,
6,
7,
8,
9,
10 within the loop
2578 FOR i IN REVERSE
10.
.1 LOOP
2579 -- i will take on the values
10,
9,
8,
7,
6,
5,
4,
3,
2,
1 within the loop
2582 FOR i IN REVERSE
10.
.1 BY
2 LOOP
2583 -- i will take on the values
10,
8,
6,
4,
2 within the loop
2589 If the lower bound is greater than the upper bound (or less than,
2590 in the
<literal>REVERSE
</literal> case), the loop body is not
2591 executed at all. No error is raised.
2595 If a
<replaceable>label
</replaceable> is attached to the
2596 <literal>FOR
</literal> loop then the integer loop variable can be
2597 referenced with a qualified name, using that
2598 <replaceable>label
</replaceable>.
2603 <sect2 id=
"plpgsql-records-iterating">
2604 <title>Looping through Query Results
</title>
2607 Using a different type of
<literal>FOR
</literal> loop, you can iterate through
2608 the results of a query and manipulate that data
2609 accordingly. The syntax is:
2611 <optional> <<<replaceable>label
</replaceable>>> </optional>
2612 FOR
<replaceable>target
</replaceable> IN
<replaceable>query
</replaceable> LOOP
2613 <replaceable>statements
</replaceable>
2614 END LOOP
<optional> <replaceable>label
</replaceable> </optional>;
2616 The
<replaceable>target
</replaceable> is a record variable, row variable,
2617 or comma-separated list of scalar variables.
2618 The
<replaceable>target
</replaceable> is successively assigned each row
2619 resulting from the
<replaceable>query
</replaceable> and the loop body is
2620 executed for each row. Here is an example:
2622 CREATE FUNCTION refresh_mviews() RETURNS integer AS $$
2626 RAISE NOTICE 'Refreshing all materialized views...';
2629 SELECT n.nspname AS mv_schema,
2630 c.relname AS mv_name,
2631 pg_catalog.pg_get_userbyid(c.relowner) AS owner
2632 FROM pg_catalog.pg_class c
2633 LEFT JOIN pg_catalog.pg_namespace n ON (n.oid = c.relnamespace)
2634 WHERE c.relkind = 'm'
2638 -- Now
"mviews" has one record with information about the materialized view
2640 RAISE NOTICE 'Refreshing materialized view %.% (owner: %)...',
2641 quote_ident(mviews.mv_schema),
2642 quote_ident(mviews.mv_name),
2643 quote_ident(mviews.owner);
2644 EXECUTE format('REFRESH MATERIALIZED VIEW %I.%I', mviews.mv_schema, mviews.mv_name);
2647 RAISE NOTICE 'Done refreshing materialized views.';
2650 $$ LANGUAGE plpgsql;
2653 If the loop is terminated by an
<literal>EXIT
</literal> statement, the last
2654 assigned row value is still accessible after the loop.
2658 The
<replaceable>query
</replaceable> used in this type of
<literal>FOR
</literal>
2659 statement can be any SQL command that returns rows to the caller:
2660 <command>SELECT
</command> is the most common case,
2661 but you can also use
<command>INSERT
</command>,
<command>UPDATE
</command>,
2662 <command>DELETE
</command>, or
<command>MERGE
</command> with a
2663 <literal>RETURNING
</literal> clause. Some utility
2664 commands such as
<command>EXPLAIN
</command> will work too.
2668 <application>PL/pgSQL
</application> variables are replaced by query parameters,
2669 and the query plan is cached for possible re-use, as discussed in
2670 detail in
<xref linkend=
"plpgsql-var-subst"/> and
2671 <xref linkend=
"plpgsql-plan-caching"/>.
2675 The
<literal>FOR-IN-EXECUTE
</literal> statement is another way to iterate over
2678 <optional> <<<replaceable>label
</replaceable>>> </optional>
2679 FOR
<replaceable>target
</replaceable> IN EXECUTE
<replaceable>text_expression
</replaceable> <optional> USING
<replaceable>expression
</replaceable> <optional>, ...
</optional> </optional> LOOP
2680 <replaceable>statements
</replaceable>
2681 END LOOP
<optional> <replaceable>label
</replaceable> </optional>;
2683 This is like the previous form, except that the source query
2684 is specified as a string expression, which is evaluated and replanned
2685 on each entry to the
<literal>FOR
</literal> loop. This allows the programmer to
2686 choose the speed of a preplanned query or the flexibility of a dynamic
2687 query, just as with a plain
<command>EXECUTE
</command> statement.
2688 As with
<command>EXECUTE
</command>, parameter values can be inserted
2689 into the dynamic command via
<literal>USING
</literal>.
2693 Another way to specify the query whose results should be iterated
2694 through is to declare it as a cursor. This is described in
2695 <xref linkend=
"plpgsql-cursor-for-loop"/>.
2699 <sect2 id=
"plpgsql-foreach-array">
2700 <title>Looping through Arrays
</title>
2703 The
<literal>FOREACH
</literal> loop is much like a
<literal>FOR
</literal> loop,
2704 but instead of iterating through the rows returned by an SQL query,
2705 it iterates through the elements of an array value.
2706 (In general,
<literal>FOREACH
</literal> is meant for looping through
2707 components of a composite-valued expression; variants for looping
2708 through composites besides arrays may be added in future.)
2709 The
<literal>FOREACH
</literal> statement to loop over an array is:
2712 <optional> <<<replaceable>label
</replaceable>>> </optional>
2713 FOREACH
<replaceable>target
</replaceable> <optional> SLICE
<replaceable>number
</replaceable> </optional> IN ARRAY
<replaceable>expression
</replaceable> LOOP
2714 <replaceable>statements
</replaceable>
2715 END LOOP
<optional> <replaceable>label
</replaceable> </optional>;
2720 Without
<literal>SLICE
</literal>, or if
<literal>SLICE
0</literal> is specified,
2721 the loop iterates through individual elements of the array produced
2722 by evaluating the
<replaceable>expression
</replaceable>.
2723 The
<replaceable>target
</replaceable> variable is assigned each
2724 element value in sequence, and the loop body is executed for each element.
2725 Here is an example of looping through the elements of an integer
2729 CREATE FUNCTION sum(int[]) RETURNS int8 AS $$
2734 FOREACH x IN ARRAY $
1
2740 $$ LANGUAGE plpgsql;
2743 The elements are visited in storage order, regardless of the number of
2744 array dimensions. Although the
<replaceable>target
</replaceable> is
2745 usually just a single variable, it can be a list of variables when
2746 looping through an array of composite values (records). In that case,
2747 for each array element, the variables are assigned from successive
2748 columns of the composite value.
2752 With a positive
<literal>SLICE
</literal> value,
<literal>FOREACH
</literal>
2753 iterates through slices of the array rather than single elements.
2754 The
<literal>SLICE
</literal> value must be an integer constant not larger
2755 than the number of dimensions of the array. The
2756 <replaceable>target
</replaceable> variable must be an array,
2757 and it receives successive slices of the array value, where each slice
2758 is of the number of dimensions specified by
<literal>SLICE
</literal>.
2759 Here is an example of iterating through one-dimensional slices:
2762 CREATE FUNCTION scan_rows(int[]) RETURNS void AS $$
2766 FOREACH x SLICE
1 IN ARRAY $
1
2768 RAISE NOTICE 'row = %', x;
2771 $$ LANGUAGE plpgsql;
2773 SELECT scan_rows(ARRAY[[
1,
2,
3],[
4,
5,
6],[
7,
8,
9],[
10,
11,
12]]);
2775 NOTICE: row = {
1,
2,
3}
2776 NOTICE: row = {
4,
5,
6}
2777 NOTICE: row = {
7,
8,
9}
2778 NOTICE: row = {
10,
11,
12}
2783 <sect2 id=
"plpgsql-error-trapping">
2784 <title>Trapping Errors
</title>
2787 <primary>exceptions
</primary>
2788 <secondary>in PL/pgSQL
</secondary>
2792 By default, any error occurring in a
<application>PL/pgSQL
</application>
2793 function aborts execution of the function and the
2794 surrounding transaction. You can trap errors and recover
2795 from them by using a
<command>BEGIN
</command> block with an
2796 <literal>EXCEPTION
</literal> clause. The syntax is an extension of the
2797 normal syntax for a
<command>BEGIN
</command> block:
2800 <optional> <<<replaceable>label
</replaceable>>> </optional>
2802 <replaceable>declarations
</replaceable> </optional>
2804 <replaceable>statements
</replaceable>
2806 WHEN
<replaceable>condition
</replaceable> <optional> OR
<replaceable>condition
</replaceable> ...
</optional> THEN
2807 <replaceable>handler_statements
</replaceable>
2808 <optional> WHEN
<replaceable>condition
</replaceable> <optional> OR
<replaceable>condition
</replaceable> ...
</optional> THEN
2809 <replaceable>handler_statements
</replaceable>
2816 If no error occurs, this form of block simply executes all the
2817 <replaceable>statements
</replaceable>, and then control passes
2818 to the next statement after
<literal>END
</literal>. But if an error
2819 occurs within the
<replaceable>statements
</replaceable>, further
2820 processing of the
<replaceable>statements
</replaceable> is
2821 abandoned, and control passes to the
<literal>EXCEPTION
</literal> list.
2822 The list is searched for the first
<replaceable>condition
</replaceable>
2823 matching the error that occurred. If a match is found, the
2824 corresponding
<replaceable>handler_statements
</replaceable> are
2825 executed, and then control passes to the next statement after
2826 <literal>END
</literal>. If no match is found, the error propagates out
2827 as though the
<literal>EXCEPTION
</literal> clause were not there at all:
2828 the error can be caught by an enclosing block with
2829 <literal>EXCEPTION
</literal>, or if there is none it aborts processing
2834 The
<replaceable>condition
</replaceable> names can be any of
2835 those shown in
<xref linkend=
"errcodes-appendix"/>. A category
2836 name matches any error within its category. The special
2837 condition name
<literal>OTHERS
</literal> matches every error type except
2838 <literal>QUERY_CANCELED
</literal> and
<literal>ASSERT_FAILURE
</literal>.
2839 (It is possible, but often unwise, to trap those two error types
2840 by name.) Condition names are
2841 not case-sensitive. Also, an error condition can be specified
2842 by
<literal>SQLSTATE
</literal> code; for example these are equivalent:
2844 WHEN division_by_zero THEN ...
2845 WHEN SQLSTATE '
22012' THEN ...
2850 If a new error occurs within the selected
2851 <replaceable>handler_statements
</replaceable>, it cannot be caught
2852 by this
<literal>EXCEPTION
</literal> clause, but is propagated out.
2853 A surrounding
<literal>EXCEPTION
</literal> clause could catch it.
2857 When an error is caught by an
<literal>EXCEPTION
</literal> clause,
2858 the local variables of the
<application>PL/pgSQL
</application> function
2859 remain as they were when the error occurred, but all changes
2860 to persistent database state within the block are rolled back.
2861 As an example, consider this fragment:
2864 INSERT INTO mytab(firstname, lastname) VALUES('Tom', 'Jones');
2866 UPDATE mytab SET firstname = 'Joe' WHERE lastname = 'Jones';
2870 WHEN division_by_zero THEN
2871 RAISE NOTICE 'caught division_by_zero';
2876 When control reaches the assignment to
<literal>y
</literal>, it will
2877 fail with a
<literal>division_by_zero
</literal> error. This will be caught by
2878 the
<literal>EXCEPTION
</literal> clause. The value returned in the
2879 <command>RETURN
</command> statement will be the incremented value of
2880 <literal>x
</literal>, but the effects of the
<command>UPDATE
</command> command will
2881 have been rolled back. The
<command>INSERT
</command> command preceding the
2882 block is not rolled back, however, so the end result is that the database
2883 contains
<literal>Tom Jones
</literal> not
<literal>Joe Jones
</literal>.
2888 A block containing an
<literal>EXCEPTION
</literal> clause is significantly
2889 more expensive to enter and exit than a block without one. Therefore,
2890 don't use
<literal>EXCEPTION
</literal> without need.
2894 <example id=
"plpgsql-upsert-example">
2895 <title>Exceptions with
<command>UPDATE
</command>/
<command>INSERT
</command></title>
2898 This example uses exception handling to perform either
2899 <command>UPDATE
</command> or
<command>INSERT
</command>, as appropriate. It is
2900 recommended that applications use
<command>INSERT
</command> with
2901 <literal>ON CONFLICT DO UPDATE
</literal> rather than actually using
2902 this pattern. This example serves primarily to illustrate use of
2903 <application>PL/pgSQL
</application> control flow structures:
2906 CREATE TABLE db (a INT PRIMARY KEY, b TEXT);
2908 CREATE FUNCTION merge_db(key INT, data TEXT) RETURNS VOID AS
2912 -- first try to update the key
2913 UPDATE db SET b = data WHERE a = key;
2917 -- not there, so try to insert the key
2918 -- if someone else inserts the same key concurrently,
2919 -- we could get a unique-key failure
2921 INSERT INTO db(a,b) VALUES (key, data);
2923 EXCEPTION WHEN unique_violation THEN
2924 -- Do nothing, and loop to try the UPDATE again.
2931 SELECT merge_db(
1, 'david');
2932 SELECT merge_db(
1, 'dennis');
2935 This coding assumes the
<literal>unique_violation
</literal> error is caused by
2936 the
<command>INSERT
</command>, and not by, say, an
<command>INSERT
</command> in a
2937 trigger function on the table. It might also misbehave if there is
2938 more than one unique index on the table, since it will retry the
2939 operation regardless of which index caused the error.
2940 More safety could be had by using the
2941 features discussed next to check that the trapped error was the one
2946 <sect3 id=
"plpgsql-exception-diagnostics">
2947 <title>Obtaining Information about an Error
</title>
2950 Exception handlers frequently need to identify the specific error that
2951 occurred. There are two ways to get information about the current
2952 exception in
<application>PL/pgSQL
</application>: special variables and the
2953 <command>GET STACKED DIAGNOSTICS
</command> command.
2957 Within an exception handler, the special variable
2958 <varname>SQLSTATE
</varname> contains the error code that corresponds to
2959 the exception that was raised (refer to
<xref linkend=
"errcodes-table"/>
2960 for a list of possible error codes). The special variable
2961 <varname>SQLERRM
</varname> contains the error message associated with the
2962 exception. These variables are undefined outside exception handlers.
2966 Within an exception handler, one may also retrieve
2967 information about the current exception by using the
2968 <command>GET STACKED DIAGNOSTICS
</command> command, which has the form:
2971 GET STACKED DIAGNOSTICS
<replaceable>variable
</replaceable> { = | := }
<replaceable>item
</replaceable> <optional> , ...
</optional>;
2974 Each
<replaceable>item
</replaceable> is a key word identifying a status
2975 value to be assigned to the specified
<replaceable>variable
</replaceable>
2976 (which should be of the right data type to receive it). The currently
2977 available status items are shown
2978 in
<xref linkend=
"plpgsql-exception-diagnostics-values"/>.
2981 <table id=
"plpgsql-exception-diagnostics-values">
2982 <title>Error Diagnostics Items
</title>
2984 <colspec colname=
"col1" colwidth=
"2*"/>
2985 <colspec colname=
"col2" colwidth=
"1*"/>
2986 <colspec colname=
"col3" colwidth=
"2*"/>
2991 <entry>Description
</entry>
2996 <entry><literal>RETURNED_SQLSTATE
</literal></entry>
2997 <entry><type>text
</type></entry>
2998 <entry>the SQLSTATE error code of the exception
</entry>
3001 <entry><literal>COLUMN_NAME
</literal></entry>
3002 <entry><type>text
</type></entry>
3003 <entry>the name of the column related to exception
</entry>
3006 <entry><literal>CONSTRAINT_NAME
</literal></entry>
3007 <entry><type>text
</type></entry>
3008 <entry>the name of the constraint related to exception
</entry>
3011 <entry><literal>PG_DATATYPE_NAME
</literal></entry>
3012 <entry><type>text
</type></entry>
3013 <entry>the name of the data type related to exception
</entry>
3016 <entry><literal>MESSAGE_TEXT
</literal></entry>
3017 <entry><type>text
</type></entry>
3018 <entry>the text of the exception's primary message
</entry>
3021 <entry><literal>TABLE_NAME
</literal></entry>
3022 <entry><type>text
</type></entry>
3023 <entry>the name of the table related to exception
</entry>
3026 <entry><literal>SCHEMA_NAME
</literal></entry>
3027 <entry><type>text
</type></entry>
3028 <entry>the name of the schema related to exception
</entry>
3031 <entry><literal>PG_EXCEPTION_DETAIL
</literal></entry>
3032 <entry><type>text
</type></entry>
3033 <entry>the text of the exception's detail message, if any
</entry>
3036 <entry><literal>PG_EXCEPTION_HINT
</literal></entry>
3037 <entry><type>text
</type></entry>
3038 <entry>the text of the exception's hint message, if any
</entry>
3041 <entry><literal>PG_EXCEPTION_CONTEXT
</literal></entry>
3042 <entry><type>text
</type></entry>
3043 <entry>line(s) of text describing the call stack at the time of the
3044 exception (see
<xref linkend=
"plpgsql-call-stack"/>)
</entry>
3051 If the exception did not set a value for an item, an empty string
3063 -- some processing which might cause an exception
3065 EXCEPTION WHEN OTHERS THEN
3066 GET STACKED DIAGNOSTICS text_var1 = MESSAGE_TEXT,
3067 text_var2 = PG_EXCEPTION_DETAIL,
3068 text_var3 = PG_EXCEPTION_HINT;
3075 <sect2 id=
"plpgsql-call-stack">
3076 <title>Obtaining Execution Location Information
</title>
3079 The
<command>GET DIAGNOSTICS
</command> command, previously described
3080 in
<xref linkend=
"plpgsql-statements-diagnostics"/>, retrieves information
3081 about current execution state (whereas the
<command>GET STACKED
3082 DIAGNOSTICS
</command> command discussed above reports information about
3083 the execution state as of a previous error). Its
<literal>PG_CONTEXT
</literal>
3084 status item is useful for identifying the current execution
3085 location.
<literal>PG_CONTEXT
</literal> returns a text string with line(s)
3086 of text describing the call stack. The first line refers to the current
3087 function and currently executing
<command>GET DIAGNOSTICS
</command>
3088 command. The second and any subsequent lines refer to calling functions
3089 further up the call stack. For example:
3092 CREATE OR REPLACE FUNCTION outer_func() RETURNS integer AS $$
3094 RETURN inner_func();
3096 $$ LANGUAGE plpgsql;
3098 CREATE OR REPLACE FUNCTION inner_func() RETURNS integer AS $$
3102 GET DIAGNOSTICS stack = PG_CONTEXT;
3103 RAISE NOTICE E'--- Call Stack ---\n%', stack;
3106 $$ LANGUAGE plpgsql;
3108 SELECT outer_func();
3110 NOTICE: --- Call Stack ---
3111 PL/pgSQL function inner_func() line
5 at GET DIAGNOSTICS
3112 PL/pgSQL function outer_func() line
3 at RETURN
3113 CONTEXT: PL/pgSQL function outer_func() line
3 at RETURN
3123 <literal>GET STACKED DIAGNOSTICS ... PG_EXCEPTION_CONTEXT
</literal>
3124 returns the same sort of stack trace, but describing the location
3125 at which an error was detected, rather than the current location.
3130 <sect1 id=
"plpgsql-cursors">
3131 <title>Cursors
</title>
3133 <indexterm zone=
"plpgsql-cursors">
3134 <primary>cursor
</primary>
3135 <secondary>in PL/pgSQL
</secondary>
3139 Rather than executing a whole query at once, it is possible to set
3140 up a
<firstterm>cursor
</firstterm> that encapsulates the query, and then read
3141 the query result a few rows at a time. One reason for doing this is
3142 to avoid memory overrun when the result contains a large number of
3143 rows. (However,
<application>PL/pgSQL
</application> users do not normally need
3144 to worry about that, since
<literal>FOR
</literal> loops automatically use a cursor
3145 internally to avoid memory problems.) A more interesting usage is to
3146 return a reference to a cursor that a function has created, allowing the
3147 caller to read the rows. This provides an efficient way to return
3148 large row sets from functions.
3151 <sect2 id=
"plpgsql-cursor-declarations">
3152 <title>Declaring Cursor Variables
</title>
3155 All access to cursors in
<application>PL/pgSQL
</application> goes through
3156 cursor variables, which are always of the special data type
3157 <type>refcursor
</type>. One way to create a cursor variable
3158 is just to declare it as a variable of type
<type>refcursor
</type>.
3159 Another way is to use the cursor declaration syntax,
3160 which in general is:
3162 <replaceable>name
</replaceable> <optional> <optional> NO
</optional> SCROLL
</optional> CURSOR
<optional> (
<replaceable>arguments
</replaceable> )
</optional> FOR
<replaceable>query
</replaceable>;
3164 (
<literal>FOR
</literal> can be replaced by
<literal>IS
</literal> for
3165 <productname>Oracle
</productname> compatibility.)
3166 If
<literal>SCROLL
</literal> is specified, the cursor will be capable of
3167 scrolling backward; if
<literal>NO SCROLL
</literal> is specified, backward
3168 fetches will be rejected; if neither specification appears, it is
3169 query-dependent whether backward fetches will be allowed.
3170 <replaceable>arguments
</replaceable>, if specified, is a
3171 comma-separated list of pairs
<literal><replaceable>name
</replaceable>
3172 <replaceable>datatype
</replaceable></literal> that define names to be
3173 replaced by parameter values in the given query. The actual
3174 values to substitute for these names will be specified later,
3175 when the cursor is opened.
3182 curs2 CURSOR FOR SELECT * FROM tenk1;
3183 curs3 CURSOR (key integer) FOR SELECT * FROM tenk1 WHERE unique1 = key;
3185 All three of these variables have the data type
<type>refcursor
</type>,
3186 but the first can be used with any query, while the second has
3187 a fully specified query already
<firstterm>bound
</firstterm> to it, and the last
3188 has a parameterized query bound to it. (
<literal>key
</literal> will be
3189 replaced by an integer parameter value when the cursor is opened.)
3190 The variable
<literal>curs1
</literal>
3191 is said to be
<firstterm>unbound
</firstterm> since it is not bound to
3192 any particular query.
3196 The
<literal>SCROLL
</literal> option cannot be used when the cursor's
3197 query uses
<literal>FOR UPDATE/SHARE
</literal>. Also, it is
3198 best to use
<literal>NO SCROLL
</literal> with a query that involves
3199 volatile functions. The implementation of
<literal>SCROLL
</literal>
3200 assumes that re-reading the query's output will give consistent
3201 results, which a volatile function might not do.
3205 <sect2 id=
"plpgsql-cursor-opening">
3206 <title>Opening Cursors
</title>
3209 Before a cursor can be used to retrieve rows, it must be
3210 <firstterm>opened
</firstterm>. (This is the equivalent action to the SQL
3211 command
<link linkend=
"sql-declare"><command>DECLARE
3212 CURSOR
</command></link>.)
3213 <application>PL/pgSQL
</application> has
3214 three forms of the
<command>OPEN
</command> statement, two of which use unbound
3215 cursor variables while the third uses a bound cursor variable.
3220 Bound cursor variables can also be used without explicitly opening the cursor,
3221 via the
<command>FOR
</command> statement described in
3222 <xref linkend=
"plpgsql-cursor-for-loop"/>.
3223 A
<command>FOR
</command> loop will open the cursor and then
3224 close it again when the loop completes.
3229 <primary>portal
</primary>
3230 <secondary>in PL/pgSQL
</secondary>
3234 Opening a cursor involves creating a server-internal data structure
3235 called a
<firstterm>portal
</firstterm>, which holds the execution
3236 state for the cursor's query. A portal has a name, which must be
3237 unique within the session for the duration of the portal's existence.
3238 By default,
<application>PL/pgSQL
</application> will assign a unique
3239 name to each portal it creates. However, if you assign a non-null
3240 string value to a cursor variable, that string will be used as its
3241 portal name. This feature can be used as described in
3242 <xref linkend=
"plpgsql-cursor-returning"/>.
3245 <sect3 id=
"plpgsql-cursor-opening-open-for-query">
3246 <title><command>OPEN FOR
</command> <replaceable>query
</replaceable></title>
3249 OPEN
<replaceable>unbound_cursorvar
</replaceable> <optional> <optional> NO
</optional> SCROLL
</optional> FOR
<replaceable>query
</replaceable>;
3253 The cursor variable is opened and given the specified query to
3254 execute. The cursor cannot be open already, and it must have been
3255 declared as an unbound cursor variable (that is, as a simple
3256 <type>refcursor
</type> variable). The query must be a
3257 <command>SELECT
</command>, or something else that returns rows
3258 (such as
<command>EXPLAIN
</command>). The query
3259 is treated in the same way as other SQL commands in
3260 <application>PL/pgSQL
</application>:
<application>PL/pgSQL
</application>
3261 variable names are substituted, and the query plan is cached for
3262 possible reuse. When a
<application>PL/pgSQL
</application>
3263 variable is substituted into the cursor query, the value that is
3264 substituted is the one it has at the time of the
<command>OPEN
</command>;
3265 subsequent changes to the variable will not affect the cursor's
3267 The
<literal>SCROLL
</literal> and
<literal>NO SCROLL
</literal>
3268 options have the same meanings as for a bound cursor.
3274 OPEN curs1 FOR SELECT * FROM foo WHERE key = mykey;
3279 <sect3 id=
"plpgsql-cursor-opening-open-for-execute">
3280 <title><command>OPEN FOR EXECUTE
</command></title>
3283 OPEN
<replaceable>unbound_cursorvar
</replaceable> <optional> <optional> NO
</optional> SCROLL
</optional> FOR EXECUTE
<replaceable class=
"command">query_string
</replaceable>
3284 <optional> USING
<replaceable>expression
</replaceable> <optional>, ...
</optional> </optional>;
3288 The cursor variable is opened and given the specified query to
3289 execute. The cursor cannot be open already, and it must have been
3290 declared as an unbound cursor variable (that is, as a simple
3291 <type>refcursor
</type> variable). The query is specified as a string
3292 expression, in the same way as in the
<command>EXECUTE
</command>
3293 command. As usual, this gives flexibility so the query plan can vary
3294 from one run to the next (see
<xref linkend=
"plpgsql-plan-caching"/>),
3295 and it also means that variable substitution is not done on the
3296 command string. As with
<command>EXECUTE
</command>, parameter values
3297 can be inserted into the dynamic command via
3298 <literal>format()
</literal> and
<literal>USING
</literal>.
3299 The
<literal>SCROLL
</literal> and
3300 <literal>NO SCROLL
</literal> options have the same meanings as for a bound
3307 OPEN curs1 FOR EXECUTE format('SELECT * FROM %I WHERE col1 = $
1',tabname) USING keyvalue;
3309 In this example, the table name is inserted into the query via
3310 <function>format()
</function>. The comparison value for
<literal>col1
</literal>
3311 is inserted via a
<literal>USING
</literal> parameter, so it needs
3316 <sect3 id=
"plpgsql-open-bound-cursor">
3317 <title>Opening a Bound Cursor
</title>
3320 OPEN
<replaceable>bound_cursorvar
</replaceable> <optional> (
<optional> <replaceable>argument_name
</replaceable> :=
</optional> <replaceable>argument_value
</replaceable> <optional>, ...
</optional> )
</optional>;
3324 This form of
<command>OPEN
</command> is used to open a cursor
3325 variable whose query was bound to it when it was declared. The
3326 cursor cannot be open already. A list of actual argument value
3327 expressions must appear if and only if the cursor was declared to
3328 take arguments. These values will be substituted in the query.
3332 The query plan for a bound cursor is always considered cacheable;
3333 there is no equivalent of
<command>EXECUTE
</command> in this case.
3334 Notice that
<literal>SCROLL
</literal> and
<literal>NO SCROLL
</literal> cannot be
3335 specified in
<command>OPEN
</command>, as the cursor's scrolling
3336 behavior was already determined.
3340 Argument values can be passed using either
<firstterm>positional
</firstterm>
3341 or
<firstterm>named
</firstterm> notation. In positional
3342 notation, all arguments are specified in order. In named notation,
3343 each argument's name is specified using
<literal>:=
</literal> to
3344 separate it from the argument expression. Similar to calling
3345 functions, described in
<xref linkend=
"sql-syntax-calling-funcs"/>, it
3346 is also allowed to mix positional and named notation.
3350 Examples (these use the cursor declaration examples above):
3354 OPEN curs3(key :=
42);
3359 Because variable substitution is done on a bound cursor's query,
3360 there are really two ways to pass values into the cursor: either
3361 with an explicit argument to
<command>OPEN
</command>, or implicitly by
3362 referencing a
<application>PL/pgSQL
</application> variable in the query.
3363 However, only variables declared before the bound cursor was
3364 declared will be substituted into it. In either case the value to
3365 be passed is determined at the time of the
<command>OPEN
</command>.
3366 For example, another way to get the same effect as the
3367 <literal>curs3
</literal> example above is
3371 curs4 CURSOR FOR SELECT * FROM tenk1 WHERE unique1 = key;
3380 <sect2 id=
"plpgsql-cursor-using">
3381 <title>Using Cursors
</title>
3384 Once a cursor has been opened, it can be manipulated with the
3385 statements described here.
3389 These manipulations need not occur in the same function that
3390 opened the cursor to begin with. You can return a
<type>refcursor
</type>
3391 value out of a function and let the caller operate on the cursor.
3392 (Internally, a
<type>refcursor
</type> value is simply the string name
3393 of the portal containing the active query for the cursor. This name
3394 can be passed around, assigned to other
<type>refcursor
</type> variables,
3395 and so on, without disturbing the portal.)
3399 All portals are implicitly closed at transaction end. Therefore
3400 a
<type>refcursor
</type> value is usable to reference an open cursor
3401 only until the end of the transaction.
3404 <sect3 id=
"plpgsql-cursor-using-fetch">
3405 <title><literal>FETCH
</literal></title>
3408 FETCH
<optional> <replaceable>direction
</replaceable> { FROM | IN }
</optional> <replaceable>cursor
</replaceable> INTO
<replaceable>target
</replaceable>;
3412 <command>FETCH
</command> retrieves the next row (in the indicated
3414 cursor into a target, which might be a row variable, a record
3415 variable, or a comma-separated list of simple variables, just like
3416 <command>SELECT INTO
</command>. If there is no suitable row, the
3417 target is set to NULL(s). As with
<command>SELECT
3418 INTO
</command>, the special variable
<literal>FOUND
</literal> can
3419 be checked to see whether a row was obtained or not. If no row is
3420 obtained, the cursor is positioned after the last row or before the
3421 first row, depending on the movement direction.
3425 The
<replaceable>direction
</replaceable> clause can be any of the
3426 variants allowed in the SQL
<xref linkend=
"sql-fetch"/>
3427 command except the ones that can fetch
3428 more than one row; namely, it can be
3429 <literal>NEXT
</literal>,
3430 <literal>PRIOR
</literal>,
3431 <literal>FIRST
</literal>,
3432 <literal>LAST
</literal>,
3433 <literal>ABSOLUTE
</literal> <replaceable>count
</replaceable>,
3434 <literal>RELATIVE
</literal> <replaceable>count
</replaceable>,
3435 <literal>FORWARD
</literal>, or
3436 <literal>BACKWARD
</literal>.
3437 Omitting
<replaceable>direction
</replaceable> is the same
3438 as specifying
<literal>NEXT
</literal>.
3439 In the forms using a
<replaceable>count
</replaceable>,
3440 the
<replaceable>count
</replaceable> can be any integer-valued
3441 expression (unlike the SQL
<command>FETCH
</command> command,
3442 which only allows an integer constant).
3443 <replaceable>direction
</replaceable> values that require moving
3444 backward are likely to fail unless the cursor was declared or opened
3445 with the
<literal>SCROLL
</literal> option.
3449 <replaceable>cursor
</replaceable> must be the name of a
<type>refcursor
</type>
3450 variable that references an open cursor portal.
3456 FETCH curs1 INTO rowvar;
3457 FETCH curs2 INTO foo, bar, baz;
3458 FETCH LAST FROM curs3 INTO x, y;
3459 FETCH RELATIVE -
2 FROM curs4 INTO x;
3464 <sect3 id=
"plpgsql-cursor-using-move">
3465 <title><literal>MOVE
</literal></title>
3468 MOVE
<optional> <replaceable>direction
</replaceable> { FROM | IN }
</optional> <replaceable>cursor
</replaceable>;
3472 <command>MOVE
</command> repositions a cursor without retrieving
3473 any data.
<command>MOVE
</command> works like the
3474 <command>FETCH
</command> command, except it only repositions the
3475 cursor and does not return the row moved to.
3476 The
<replaceable>direction
</replaceable> clause can be any of the
3477 variants allowed in the SQL
<xref linkend=
"sql-fetch"/>
3478 command, including those that can fetch more than one row;
3479 the cursor is positioned to the last such row.
3480 (However, the case in which the
<replaceable>direction
</replaceable>
3481 clause is simply a
<replaceable>count
</replaceable> expression with
3482 no key word is deprecated in
<application>PL/pgSQL
</application>.
3483 That syntax is ambiguous with the case where
3484 the
<replaceable>direction
</replaceable> clause is omitted
3485 altogether, and hence it may fail if
3486 the
<replaceable>count
</replaceable> is not a constant.)
3487 As with
<command>SELECT
3488 INTO
</command>, the special variable
<literal>FOUND
</literal> can
3489 be checked to see whether there was a row to move to. If there is no
3490 such row, the cursor is positioned after the last row or before the
3491 first row, depending on the movement direction.
3498 MOVE LAST FROM curs3;
3499 MOVE RELATIVE -
2 FROM curs4;
3500 MOVE FORWARD
2 FROM curs4;
3505 <sect3 id=
"plpgsql-cursor-using-update-delete">
3506 <title><literal>UPDATE/DELETE WHERE CURRENT OF
</literal></title>
3509 UPDATE
<replaceable>table
</replaceable> SET ... WHERE CURRENT OF
<replaceable>cursor
</replaceable>;
3510 DELETE FROM
<replaceable>table
</replaceable> WHERE CURRENT OF
<replaceable>cursor
</replaceable>;
3514 When a cursor is positioned on a table row, that row can be updated
3515 or deleted using the cursor to identify the row. There are
3516 restrictions on what the cursor's query can be (in particular,
3517 no grouping) and it's best to use
<literal>FOR UPDATE
</literal> in the
3518 cursor. For more information see the
3519 <xref linkend=
"sql-declare"/>
3526 UPDATE foo SET dataval = myval WHERE CURRENT OF curs1;
3531 <sect3 id=
"plpgsql-cursor-using-close">
3532 <title><literal>CLOSE
</literal></title>
3535 CLOSE
<replaceable>cursor
</replaceable>;
3539 <command>CLOSE
</command> closes the portal underlying an open
3540 cursor. This can be used to release resources earlier than end of
3541 transaction, or to free up the cursor variable to be opened again.
3552 <sect3 id=
"plpgsql-cursor-returning">
3553 <title>Returning Cursors
</title>
3556 <application>PL/pgSQL
</application> functions can return cursors to the
3557 caller. This is useful to return multiple rows or columns,
3558 especially with very large result sets. To do this, the function
3559 opens the cursor and returns the cursor name to the caller (or simply
3560 opens the cursor using a portal name specified by or otherwise known
3561 to the caller). The caller can then fetch rows from the cursor. The
3562 cursor can be closed by the caller, or it will be closed automatically
3563 when the transaction closes.
3567 The portal name used for a cursor can be specified by the
3568 programmer or automatically generated. To specify a portal name,
3569 simply assign a string to the
<type>refcursor
</type> variable before
3570 opening it. The string value of the
<type>refcursor
</type> variable
3571 will be used by
<command>OPEN
</command> as the name of the underlying portal.
3572 However, if the
<type>refcursor
</type> variable's value is null
3573 (as it will be by default), then
3574 <command>OPEN
</command> automatically generates a name that does not
3575 conflict with any existing portal, and assigns it to the
3576 <type>refcursor
</type> variable.
3581 Prior to
<productname>PostgreSQL
</productname> 16, bound cursor
3582 variables were initialized to contain their own names, rather
3583 than being left as null, so that the underlying portal name would
3584 be the same as the cursor variable's name by default. This was
3585 changed because it created too much risk of conflicts between
3586 similarly-named cursors in different functions.
3591 The following example shows one way a cursor name can be supplied by
3595 CREATE TABLE test (col text);
3596 INSERT INTO test VALUES ('
123');
3598 CREATE FUNCTION reffunc(refcursor) RETURNS refcursor AS '
3600 OPEN $
1 FOR SELECT col FROM test;
3606 SELECT reffunc('funccursor');
3607 FETCH ALL IN funccursor;
3613 The following example uses automatic cursor name generation:
3616 CREATE FUNCTION reffunc2() RETURNS refcursor AS '
3620 OPEN ref FOR SELECT col FROM test;
3625 -- need to be in a transaction to use cursors.
3630 --------------------
3631 <unnamed cursor
1>
3634 FETCH ALL IN
"<unnamed cursor 1>";
3640 The following example shows one way to return multiple cursors
3641 from a single function:
3644 CREATE FUNCTION myfunc(refcursor, refcursor) RETURNS SETOF refcursor AS $$
3646 OPEN $
1 FOR SELECT * FROM table_1;
3648 OPEN $
2 FOR SELECT * FROM table_2;
3651 $$ LANGUAGE plpgsql;
3653 -- need to be in a transaction to use cursors.
3656 SELECT * FROM myfunc('a', 'b');
3666 <sect2 id=
"plpgsql-cursor-for-loop">
3667 <title>Looping through a Cursor's Result
</title>
3670 There is a variant of the
<command>FOR
</command> statement that allows
3671 iterating through the rows returned by a cursor. The syntax is:
3674 <optional> <<<replaceable>label
</replaceable>>> </optional>
3675 FOR
<replaceable>recordvar
</replaceable> IN
<replaceable>bound_cursorvar
</replaceable> <optional> (
<optional> <replaceable>argument_name
</replaceable> :=
</optional> <replaceable>argument_value
</replaceable> <optional>, ...
</optional> )
</optional> LOOP
3676 <replaceable>statements
</replaceable>
3677 END LOOP
<optional> <replaceable>label
</replaceable> </optional>;
3680 The cursor variable must have been bound to some query when it was
3681 declared, and it
<emphasis>cannot
</emphasis> be open already. The
3682 <command>FOR
</command> statement automatically opens the cursor, and it closes
3683 the cursor again when the loop exits. A list of actual argument value
3684 expressions must appear if and only if the cursor was declared to take
3685 arguments. These values will be substituted in the query, in just
3686 the same way as during an
<command>OPEN
</command> (see
<xref
3687 linkend=
"plpgsql-open-bound-cursor"/>).
3691 The variable
<replaceable>recordvar
</replaceable> is automatically
3692 defined as type
<type>record
</type> and exists only inside the loop (any
3693 existing definition of the variable name is ignored within the loop).
3694 Each row returned by the cursor is successively assigned to this
3695 record variable and the loop body is executed.
3701 <sect1 id=
"plpgsql-transactions">
3702 <title>Transaction Management
</title>
3705 In procedures invoked by the
<command>CALL
</command> command
3706 as well as in anonymous code blocks (
<command>DO
</command> command),
3707 it is possible to end transactions using the
3708 commands
<command>COMMIT
</command> and
<command>ROLLBACK
</command>. A new
3709 transaction is started automatically after a transaction is ended using
3710 these commands, so there is no separate
<command>START
3711 TRANSACTION
</command> command. (Note that
<command>BEGIN
</command> and
3712 <command>END
</command> have different meanings in PL/pgSQL.)
3716 Here is a simple example:
3718 CREATE PROCEDURE transaction_test1()
3723 INSERT INTO test1 (a) VALUES (i);
3733 CALL transaction_test1();
3737 <indexterm zone=
"plpgsql-transaction-chain">
3738 <primary>chained transactions
</primary>
3739 <secondary>in PL/pgSQL
</secondary>
3742 <para id=
"plpgsql-transaction-chain">
3743 A new transaction starts out with default transaction characteristics such
3744 as transaction isolation level. In cases where transactions are committed
3745 in a loop, it might be desirable to start new transactions automatically
3746 with the same characteristics as the previous one. The commands
3747 <command>COMMIT AND CHAIN
</command> and
<command>ROLLBACK AND
3748 CHAIN
</command> accomplish this.
3752 Transaction control is only possible in
<command>CALL
</command> or
3753 <command>DO
</command> invocations from the top level or nested
3754 <command>CALL
</command> or
<command>DO
</command> invocations without any
3755 other intervening command. For example, if the call stack is
3756 <command>CALL proc1()
</command> → <command>CALL proc2()
</command>
3757 → <command>CALL proc3()
</command>, then the second and third
3758 procedures can perform transaction control actions. But if the call stack
3759 is
<command>CALL proc1()
</command> → <command>SELECT
3760 func2()
</command> → <command>CALL proc3()
</command>, then the last
3761 procedure cannot do transaction control, because of the
3762 <command>SELECT
</command> in between.
3766 <application>PL/pgSQL
</application> does not support savepoints
3767 (
<command>SAVEPOINT
</command>/
<command>ROLLBACK TO
3768 SAVEPOINT
</command>/
<command>RELEASE SAVEPOINT
</command> commands).
3769 Typical usage patterns for savepoints can be replaced by blocks with
3770 exception handlers (see
<xref linkend=
"plpgsql-error-trapping"/>).
3771 Under the hood, a block with exception handlers forms a
3772 subtransaction, which means that transactions cannot be ended inside
3777 Special considerations apply to cursor loops. Consider this example:
3779 CREATE PROCEDURE transaction_test2()
3785 FOR r IN SELECT * FROM test2 ORDER BY x LOOP
3786 INSERT INTO test1 (a) VALUES (r.x);
3792 CALL transaction_test2();
3794 Normally, cursors are automatically closed at transaction commit.
3795 However, a cursor created as part of a loop like this is automatically
3796 converted to a holdable cursor by the first
<command>COMMIT
</command> or
3797 <command>ROLLBACK
</command>. That means that the cursor is fully
3798 evaluated at the first
<command>COMMIT
</command> or
3799 <command>ROLLBACK
</command> rather than row by row. The cursor is still
3800 removed automatically after the loop, so this is mostly invisible to the
3801 user. But one must keep in mind that any table or row locks taken by
3802 the cursor's query will no longer be held after the
3803 first
<command>COMMIT
</command> or
3804 <command>ROLLBACK
</command>.
3808 Transaction commands are not allowed in cursor loops driven by commands
3809 that are not read-only (for example
<command>UPDATE
3810 ... RETURNING
</command>).
3814 <sect1 id=
"plpgsql-errors-and-messages">
3815 <title>Errors and Messages
</title>
3817 <sect2 id=
"plpgsql-statements-raise">
3818 <title>Reporting Errors and Messages
</title>
3821 <primary>RAISE
</primary>
3822 <secondary>in PL/pgSQL
</secondary>
3826 <primary>reporting errors
</primary>
3827 <secondary>in PL/pgSQL
</secondary>
3831 Use the
<command>RAISE
</command> statement to report messages and
3835 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>;
3836 RAISE
<optional> <replaceable class=
"parameter">level
</replaceable> </optional> <replaceable class=
"parameter">condition_name
</replaceable> <optional> USING
<replaceable class=
"parameter">option
</replaceable> { = | := }
<replaceable class=
"parameter">expression
</replaceable> <optional>, ...
</optional> </optional>;
3837 RAISE
<optional> <replaceable class=
"parameter">level
</replaceable> </optional> SQLSTATE '
<replaceable class=
"parameter">sqlstate
</replaceable>'
<optional> USING
<replaceable class=
"parameter">option
</replaceable> { = | := }
<replaceable class=
"parameter">expression
</replaceable> <optional>, ...
</optional> </optional>;
3838 RAISE
<optional> <replaceable class=
"parameter">level
</replaceable> </optional> USING
<replaceable class=
"parameter">option
</replaceable> { = | := }
<replaceable class=
"parameter">expression
</replaceable> <optional>, ...
</optional>;
3842 The
<replaceable class=
"parameter">level
</replaceable> option specifies
3843 the error severity. Allowed levels are
<literal>DEBUG
</literal>,
3844 <literal>LOG
</literal>,
<literal>INFO
</literal>,
3845 <literal>NOTICE
</literal>,
<literal>WARNING
</literal>,
3846 and
<literal>EXCEPTION
</literal>, with
<literal>EXCEPTION
</literal>
3848 <literal>EXCEPTION
</literal> raises an error (which normally aborts the
3849 current transaction); the other levels only generate messages of different
3851 Whether messages of a particular priority are reported to the client,
3852 written to the server log, or both is controlled by the
3853 <xref linkend=
"guc-log-min-messages"/> and
3854 <xref linkend=
"guc-client-min-messages"/> configuration
3855 variables. See
<xref linkend=
"runtime-config"/> for more
3860 In the first syntax variant,
3861 after the
<replaceable class=
"parameter">level
</replaceable> if any,
3862 write a
<replaceable class=
"parameter">format
</replaceable> string
3863 (which must be a simple string literal, not an expression). The
3864 format string specifies the error message text to be reported.
3865 The format string can be followed
3866 by optional argument expressions to be inserted into the message.
3867 Inside the format string,
<literal>%
</literal> is replaced by the
3868 string representation of the next optional argument's value. Write
3869 <literal>%%
</literal> to emit a literal
<literal>%
</literal>.
3870 The number of arguments must match the number of
<literal>%
</literal>
3871 placeholders in the format string, or an error is raised during
3872 the compilation of the function.
3876 In this example, the value of
<literal>v_job_id
</literal> will replace the
3877 <literal>%
</literal> in the string:
3879 RAISE NOTICE 'Calling cs_create_job(%)', v_job_id;
3884 In the second and third syntax variants,
3885 <replaceable class=
"parameter">condition_name
</replaceable> and
3886 <replaceable class=
"parameter">sqlstate
</replaceable> specify an
3887 error condition name or a five-character SQLSTATE code, respectively.
3888 See
<xref linkend=
"errcodes-appendix"/> for the valid error condition
3889 names and the predefined SQLSTATE codes.
3894 of
<replaceable class=
"parameter">condition_name
</replaceable>
3895 and
<replaceable class=
"parameter">sqlstate
</replaceable> usage:
3897 RAISE division_by_zero;
3898 RAISE WARNING SQLSTATE '
22012';
3903 In any of these syntax variants,
3904 you can attach additional information to the error report by writing
3905 <literal>USING
</literal> followed by
<replaceable
3906 class=
"parameter">option
</replaceable> =
<replaceable
3907 class=
"parameter">expression
</replaceable> items. Each
3908 <replaceable class=
"parameter">expression
</replaceable> can be any
3909 string-valued expression. The allowed
<replaceable
3910 class=
"parameter">option
</replaceable> key words are:
3912 <variablelist id=
"raise-using-options">
3913 <varlistentry id=
"raise-using-option-message">
3914 <term><literal>MESSAGE
</literal></term>
3916 <para>Sets the error message text. This option can't be used in the
3917 first syntax variant, since the message is already supplied.
</para>
3921 <varlistentry id=
"raise-using-option-detail">
3922 <term><literal>DETAIL
</literal></term>
3924 <para>Supplies an error detail message.
</para>
3928 <varlistentry id=
"raise-using-option-hint">
3929 <term><literal>HINT
</literal></term>
3931 <para>Supplies a hint message.
</para>
3935 <varlistentry id=
"raise-using-option-errcode">
3936 <term><literal>ERRCODE
</literal></term>
3938 <para>Specifies the error code (SQLSTATE) to report, either by condition
3939 name, as shown in
<xref linkend=
"errcodes-appendix"/>, or directly as a
3940 five-character SQLSTATE code. This option can't be used in the
3941 second or third syntax variant, since the error code is already
3946 <varlistentry id=
"raise-using-option-column">
3947 <term><literal>COLUMN
</literal></term>
3948 <term><literal>CONSTRAINT
</literal></term>
3949 <term><literal>DATATYPE
</literal></term>
3950 <term><literal>TABLE
</literal></term>
3951 <term><literal>SCHEMA
</literal></term>
3953 <para>Supplies the name of a related object.
</para>
3960 This example will abort the transaction with the given error message
3963 RAISE EXCEPTION 'Nonexistent ID --> %', user_id
3964 USING HINT = 'Please check your user ID';
3969 These two examples show equivalent ways of setting the SQLSTATE:
3971 RAISE 'Duplicate user ID: %', user_id USING ERRCODE = 'unique_violation';
3972 RAISE 'Duplicate user ID: %', user_id USING ERRCODE = '
23505';
3974 Another way to produce the same result is:
3976 RAISE unique_violation USING MESSAGE = 'Duplicate user ID: ' || user_id;
3981 As shown in the fourth syntax variant, it is also possible to
3982 write
<literal>RAISE USING
</literal> or
<literal>RAISE
3983 <replaceable class=
"parameter">level
</replaceable> USING
</literal> and put
3984 everything else into the
<literal>USING
</literal> list.
3988 The last variant of
<command>RAISE
</command> has no parameters at all.
3989 This form can only be used inside a
<literal>BEGIN
</literal> block's
3990 <literal>EXCEPTION
</literal> clause;
3991 it causes the error currently being handled to be re-thrown.
3996 Before
<productname>PostgreSQL
</productname> 9.1,
<command>RAISE
</command> without
3997 parameters was interpreted as re-throwing the error from the block
3998 containing the active exception handler. Thus an
<literal>EXCEPTION
</literal>
3999 clause nested within that handler could not catch it, even if the
4000 <command>RAISE
</command> was within the nested
<literal>EXCEPTION
</literal> clause's
4001 block. This was deemed surprising as well as being incompatible with
4007 If no condition name nor SQLSTATE is specified in a
4008 <command>RAISE EXCEPTION
</command> command, the default is to use
4009 <literal>raise_exception
</literal> (
<literal>P0001
</literal>).
4010 If no message text is specified, the default is to use the condition
4011 name or SQLSTATE as message text.
4016 When specifying an error code by SQLSTATE code, you are not
4017 limited to the predefined error codes, but can select any
4018 error code consisting of five digits and/or upper-case ASCII
4019 letters, other than
<literal>00000</literal>. It is recommended that
4020 you avoid throwing error codes that end in three zeroes, because
4021 these are category codes and can only be trapped by trapping
4028 <sect2 id=
"plpgsql-statements-assert">
4029 <title>Checking Assertions
</title>
4032 <primary>ASSERT
</primary>
4033 <secondary>in PL/pgSQL
</secondary>
4037 <primary>assertions
</primary>
4038 <secondary>in PL/pgSQL
</secondary>
4042 <primary><varname>plpgsql.check_asserts
</varname> configuration parameter
</primary>
4046 The
<command>ASSERT
</command> statement is a convenient shorthand for
4047 inserting debugging checks into
<application>PL/pgSQL
</application>
4051 ASSERT
<replaceable class=
"parameter">condition
</replaceable> <optional> ,
<replaceable class=
"parameter">message
</replaceable> </optional>;
4054 The
<replaceable class=
"parameter">condition
</replaceable> is a Boolean
4055 expression that is expected to always evaluate to true; if it does,
4056 the
<command>ASSERT
</command> statement does nothing further. If the
4057 result is false or null, then an
<literal>ASSERT_FAILURE
</literal> exception
4058 is raised. (If an error occurs while evaluating
4059 the
<replaceable class=
"parameter">condition
</replaceable>, it is
4060 reported as a normal error.)
4064 If the optional
<replaceable class=
"parameter">message
</replaceable> is
4065 provided, it is an expression whose result (if not null) replaces the
4066 default error message text
<quote>assertion failed
</quote>, should
4067 the
<replaceable class=
"parameter">condition
</replaceable> fail.
4068 The
<replaceable class=
"parameter">message
</replaceable> expression is
4069 not evaluated in the normal case where the assertion succeeds.
4073 Testing of assertions can be enabled or disabled via the configuration
4074 parameter
<literal>plpgsql.check_asserts
</literal>, which takes a Boolean
4075 value; the default is
<literal>on
</literal>. If this parameter
4076 is
<literal>off
</literal> then
<command>ASSERT
</command> statements do nothing.
4080 Note that
<command>ASSERT
</command> is meant for detecting program
4081 bugs, not for reporting ordinary error conditions. Use
4082 the
<command>RAISE
</command> statement, described above, for that.
4089 <sect1 id=
"plpgsql-trigger">
4090 <title>Trigger Functions
</title>
4092 <indexterm zone=
"plpgsql-trigger">
4093 <primary>trigger
</primary>
4094 <secondary>in PL/pgSQL
</secondary>
4098 <application>PL/pgSQL
</application> can be used to define trigger
4099 functions on data changes or database events.
4100 A trigger function is created with the
<command>CREATE FUNCTION
</command>
4101 command, declaring it as a function with no arguments and a return type of
4102 <type>trigger
</type> (for data change triggers) or
4103 <type>event_trigger
</type> (for database event triggers).
4104 Special local variables named
<varname>TG_
<replaceable>something
</replaceable></varname> are
4105 automatically defined to describe the condition that triggered the call.
4108 <sect2 id=
"plpgsql-dml-trigger">
4109 <title>Triggers on Data Changes
</title>
4112 A
<link linkend=
"triggers">data change trigger
</link> is declared as a
4113 function with no arguments and a return type of
<type>trigger
</type>.
4114 Note that the function must be declared with no arguments even if it
4115 expects to receive some arguments specified in
<command>CREATE TRIGGER
</command>
4116 — such arguments are passed via
<varname>TG_ARGV
</varname>, as described
4121 When a
<application>PL/pgSQL
</application> function is called as a
4122 trigger, several special variables are created automatically in the
4123 top-level block. They are:
4126 <varlistentry id=
"plpgsql-dml-trigger-new">
4127 <term><varname>NEW
</varname> <type>record
</type></term>
4130 new database row for
<command>INSERT
</command>/
<command>UPDATE
</command> operations in row-level
4131 triggers. This variable is null in statement-level triggers
4132 and for
<command>DELETE
</command> operations.
4137 <varlistentry id=
"plpgsql-dml-trigger-old">
4138 <term><varname>OLD
</varname> <type>record
</type></term>
4141 old database row for
<command>UPDATE
</command>/
<command>DELETE
</command> operations in row-level
4142 triggers. This variable is null in statement-level triggers
4143 and for
<command>INSERT
</command> operations.
4148 <varlistentry id=
"plpgsql-dml-trigger-tg-name">
4149 <term><varname>TG_NAME
</varname> <type>name
</type></term>
4152 name of the trigger which fired.
4157 <varlistentry id=
"plpgsql-dml-trigger-tg-when">
4158 <term><varname>TG_WHEN
</varname> <type>text
</type></term>
4161 <literal>BEFORE
</literal>,
<literal>AFTER
</literal>, or
4162 <literal>INSTEAD OF
</literal>, depending on the trigger's definition.
4167 <varlistentry id=
"plpgsql-dml-trigger-tg-level">
4168 <term><varname>TG_LEVEL
</varname> <type>text
</type></term>
4171 <literal>ROW
</literal> or
<literal>STATEMENT
</literal>,
4172 depending on the trigger's definition.
4177 <varlistentry id=
"plpgsql-dml-trigger-tg-op">
4178 <term><varname>TG_OP
</varname> <type>text
</type></term>
4181 operation for which the trigger was fired:
4182 <literal>INSERT
</literal>,
<literal>UPDATE
</literal>,
4183 <literal>DELETE
</literal>, or
<literal>TRUNCATE
</literal>.
4188 <varlistentry id=
"plpgsql-dml-trigger-tg-relid">
4189 <term><varname>TG_RELID
</varname> <type>oid
</type> (references
<link linkend=
"catalog-pg-class"><structname>pg_class
</structname></link>.
<structfield>oid
</structfield>)
</term>
4192 object ID of the table that caused the trigger invocation.
4197 <varlistentry id=
"plpgsql-dml-trigger-tg-relname">
4198 <term><varname>TG_RELNAME
</varname> <type>name
</type></term>
4201 table that caused the trigger
4202 invocation. This is now deprecated, and could disappear in a future
4203 release. Use
<literal>TG_TABLE_NAME
</literal> instead.
4208 <varlistentry id=
"plpgsql-dml-trigger-tg-table-name">
4209 <term><varname>TG_TABLE_NAME
</varname> <type>name
</type></term>
4212 table that caused the trigger invocation.
4217 <varlistentry id=
"plpgsql-dml-trigger-tg-table-schema">
4218 <term><varname>TG_TABLE_SCHEMA
</varname> <type>name
</type></term>
4221 schema of the table that caused the trigger invocation.
4226 <varlistentry id=
"plpgsql-dml-trigger-tg-nargs">
4227 <term><varname>TG_NARGS
</varname> <type>integer
</type></term>
4230 number of arguments given to the trigger
4231 function in the
<command>CREATE TRIGGER
</command> statement.
4236 <varlistentry id=
"plpgsql-dml-trigger-tg-argv">
4237 <term><varname>TG_ARGV
</varname> <type>text[]
</type></term>
4241 the
<command>CREATE TRIGGER
</command> statement.
4242 The index counts from
0. Invalid
4243 indexes (less than
0 or greater than or equal to
<varname>tg_nargs
</varname>)
4244 result in a null value.
4252 A trigger function must return either
<symbol>NULL
</symbol> or a
4253 record/row value having exactly the structure of the table the
4254 trigger was fired for.
4258 Row-level triggers fired
<literal>BEFORE
</literal> can return null to signal the
4259 trigger manager to skip the rest of the operation for this row
4260 (i.e., subsequent triggers are not fired, and the
4261 <command>INSERT
</command>/
<command>UPDATE
</command>/
<command>DELETE
</command> does not occur
4262 for this row). If a nonnull
4263 value is returned then the operation proceeds with that row value.
4264 Returning a row value different from the original value
4265 of
<varname>NEW
</varname> alters the row that will be inserted or
4266 updated. Thus, if the trigger function wants the triggering
4267 action to succeed normally without altering the row
4268 value,
<varname>NEW
</varname> (or a value equal thereto) has to be
4269 returned. To alter the row to be stored, it is possible to
4270 replace single values directly in
<varname>NEW
</varname> and return the
4271 modified
<varname>NEW
</varname>, or to build a complete new record/row to
4272 return. In the case of a before-trigger
4273 on
<command>DELETE
</command>, the returned value has no direct
4274 effect, but it has to be nonnull to allow the trigger action to
4275 proceed. Note that
<varname>NEW
</varname> is null
4276 in
<command>DELETE
</command> triggers, so returning that is
4277 usually not sensible. The usual idiom in
<command>DELETE
</command>
4278 triggers is to return
<varname>OLD
</varname>.
4282 <literal>INSTEAD OF
</literal> triggers (which are always row-level triggers,
4283 and may only be used on views) can return null to signal that they did
4284 not perform any updates, and that the rest of the operation for this
4285 row should be skipped (i.e., subsequent triggers are not fired, and the
4286 row is not counted in the rows-affected status for the surrounding
4287 <command>INSERT
</command>/
<command>UPDATE
</command>/
<command>DELETE
</command>).
4288 Otherwise a nonnull value should be returned, to signal
4289 that the trigger performed the requested operation. For
4290 <command>INSERT
</command> and
<command>UPDATE
</command> operations, the return value
4291 should be
<varname>NEW
</varname>, which the trigger function may modify to
4292 support
<command>INSERT RETURNING
</command> and
<command>UPDATE RETURNING
</command>
4293 (this will also affect the row value passed to any subsequent triggers,
4294 or passed to a special
<varname>EXCLUDED
</varname> alias reference within
4295 an
<command>INSERT
</command> statement with an
<literal>ON CONFLICT DO
4296 UPDATE
</literal> clause). For
<command>DELETE
</command> operations, the return
4297 value should be
<varname>OLD
</varname>.
4301 The return value of a row-level trigger
4302 fired
<literal>AFTER
</literal> or a statement-level trigger
4303 fired
<literal>BEFORE
</literal> or
<literal>AFTER
</literal> is
4304 always ignored; it might as well be null. However, any of these types of
4305 triggers might still abort the entire operation by raising an error.
4309 <xref linkend=
"plpgsql-trigger-example"/> shows an example of a
4310 trigger function in
<application>PL/pgSQL
</application>.
4313 <example id=
"plpgsql-trigger-example">
4314 <title>A
<application>PL/pgSQL
</application> Trigger Function
</title>
4317 This example trigger ensures that any time a row is inserted or updated
4318 in the table, the current user name and time are stamped into the
4319 row. And it checks that an employee's name is given and that the
4320 salary is a positive value.
4327 last_date timestamp,
4331 CREATE FUNCTION emp_stamp() RETURNS trigger AS $emp_stamp$
4333 -- Check that empname and salary are given
4334 IF NEW.empname IS NULL THEN
4335 RAISE EXCEPTION 'empname cannot be null';
4337 IF NEW.salary IS NULL THEN
4338 RAISE EXCEPTION '% cannot have null salary', NEW.empname;
4341 -- Who works for us when they must pay for it?
4342 IF NEW.salary
< 0 THEN
4343 RAISE EXCEPTION '% cannot have a negative salary', NEW.empname;
4346 -- Remember who changed the payroll when
4347 NEW.last_date := current_timestamp;
4348 NEW.last_user := current_user;
4351 $emp_stamp$ LANGUAGE plpgsql;
4353 CREATE TRIGGER emp_stamp BEFORE INSERT OR UPDATE ON emp
4354 FOR EACH ROW EXECUTE FUNCTION emp_stamp();
4359 Another way to log changes to a table involves creating a new table that
4360 holds a row for each insert, update, or delete that occurs. This approach
4361 can be thought of as auditing changes to a table.
4362 <xref linkend=
"plpgsql-trigger-audit-example"/> shows an example of an
4363 audit trigger function in
<application>PL/pgSQL
</application>.
4366 <example id=
"plpgsql-trigger-audit-example">
4367 <title>A
<application>PL/pgSQL
</application> Trigger Function for Auditing
</title>
4370 This example trigger ensures that any insert, update or delete of a row
4371 in the
<literal>emp
</literal> table is recorded (i.e., audited) in the
<literal>emp_audit
</literal> table.
4372 The current time and user name are stamped into the row, together with
4373 the type of operation performed on it.
4378 empname text NOT NULL,
4382 CREATE TABLE emp_audit(
4383 operation char(
1) NOT NULL,
4384 stamp timestamp NOT NULL,
4385 userid text NOT NULL,
4386 empname text NOT NULL,
4390 CREATE OR REPLACE FUNCTION process_emp_audit() RETURNS TRIGGER AS $emp_audit$
4393 -- Create a row in emp_audit to reflect the operation performed on emp,
4394 -- making use of the special variable TG_OP to work out the operation.
4396 IF (TG_OP = 'DELETE') THEN
4397 INSERT INTO emp_audit SELECT 'D', now(), current_user, OLD.*;
4398 ELSIF (TG_OP = 'UPDATE') THEN
4399 INSERT INTO emp_audit SELECT 'U', now(), current_user, NEW.*;
4400 ELSIF (TG_OP = 'INSERT') THEN
4401 INSERT INTO emp_audit SELECT 'I', now(), current_user, NEW.*;
4403 RETURN NULL; -- result is ignored since this is an AFTER trigger
4405 $emp_audit$ LANGUAGE plpgsql;
4407 CREATE TRIGGER emp_audit
4408 AFTER INSERT OR UPDATE OR DELETE ON emp
4409 FOR EACH ROW EXECUTE FUNCTION process_emp_audit();
4414 A variation of the previous example uses a view joining the main table
4415 to the audit table, to show when each entry was last modified. This
4416 approach still records the full audit trail of changes to the table,
4417 but also presents a simplified view of the audit trail, showing just
4418 the last modified timestamp derived from the audit trail for each entry.
4419 <xref linkend=
"plpgsql-view-trigger-audit-example"/> shows an example
4420 of an audit trigger on a view in
<application>PL/pgSQL
</application>.
4423 <example id=
"plpgsql-view-trigger-audit-example">
4424 <title>A
<application>PL/pgSQL
</application> View Trigger Function for Auditing
</title>
4427 This example uses a trigger on the view to make it updatable, and
4428 ensure that any insert, update or delete of a row in the view is
4429 recorded (i.e., audited) in the
<literal>emp_audit
</literal> table. The current time
4430 and user name are recorded, together with the type of operation
4431 performed, and the view displays the last modified time of each row.
4436 empname text PRIMARY KEY,
4440 CREATE TABLE emp_audit(
4441 operation char(
1) NOT NULL,
4442 userid text NOT NULL,
4443 empname text NOT NULL,
4445 stamp timestamp NOT NULL
4448 CREATE VIEW emp_view AS
4451 max(ea.stamp) AS last_updated
4453 LEFT JOIN emp_audit ea ON ea.empname = e.empname
4456 CREATE OR REPLACE FUNCTION update_emp_view() RETURNS TRIGGER AS $$
4459 -- Perform the required operation on emp, and create a row in emp_audit
4460 -- to reflect the change made to emp.
4462 IF (TG_OP = 'DELETE') THEN
4463 DELETE FROM emp WHERE empname = OLD.empname;
4464 IF NOT FOUND THEN RETURN NULL; END IF;
4466 OLD.last_updated = now();
4467 INSERT INTO emp_audit VALUES('D', current_user, OLD.*);
4469 ELSIF (TG_OP = 'UPDATE') THEN
4470 UPDATE emp SET salary = NEW.salary WHERE empname = OLD.empname;
4471 IF NOT FOUND THEN RETURN NULL; END IF;
4473 NEW.last_updated = now();
4474 INSERT INTO emp_audit VALUES('U', current_user, NEW.*);
4476 ELSIF (TG_OP = 'INSERT') THEN
4477 INSERT INTO emp VALUES(NEW.empname, NEW.salary);
4479 NEW.last_updated = now();
4480 INSERT INTO emp_audit VALUES('I', current_user, NEW.*);
4484 $$ LANGUAGE plpgsql;
4486 CREATE TRIGGER emp_audit
4487 INSTEAD OF INSERT OR UPDATE OR DELETE ON emp_view
4488 FOR EACH ROW EXECUTE FUNCTION update_emp_view();
4493 One use of triggers is to maintain a summary table
4494 of another table. The resulting summary can be used in place of the
4495 original table for certain queries
— often with vastly reduced run
4497 This technique is commonly used in Data Warehousing, where the tables
4498 of measured or observed data (called fact tables) might be extremely large.
4499 <xref linkend=
"plpgsql-trigger-summary-example"/> shows an example of a
4500 trigger function in
<application>PL/pgSQL
</application> that maintains
4501 a summary table for a fact table in a data warehouse.
4505 <example id=
"plpgsql-trigger-summary-example">
4506 <title>A
<application>PL/pgSQL
</application> Trigger Function for Maintaining a Summary Table
</title>
4509 The schema detailed here is partly based on the
<emphasis>Grocery Store
4510 </emphasis> example from
<emphasis>The Data Warehouse Toolkit
</emphasis>
4516 -- Main tables - time dimension and sales fact.
4518 CREATE TABLE time_dimension (
4519 time_key integer NOT NULL,
4520 day_of_week integer NOT NULL,
4521 day_of_month integer NOT NULL,
4522 month integer NOT NULL,
4523 quarter integer NOT NULL,
4524 year integer NOT NULL
4526 CREATE UNIQUE INDEX time_dimension_key ON time_dimension(time_key);
4528 CREATE TABLE sales_fact (
4529 time_key integer NOT NULL,
4530 product_key integer NOT NULL,
4531 store_key integer NOT NULL,
4532 amount_sold numeric(
12,
2) NOT NULL,
4533 units_sold integer NOT NULL,
4534 amount_cost numeric(
12,
2) NOT NULL
4536 CREATE INDEX sales_fact_time ON sales_fact(time_key);
4539 -- Summary table - sales by time.
4541 CREATE TABLE sales_summary_bytime (
4542 time_key integer NOT NULL,
4543 amount_sold numeric(
15,
2) NOT NULL,
4544 units_sold numeric(
12) NOT NULL,
4545 amount_cost numeric(
15,
2) NOT NULL
4547 CREATE UNIQUE INDEX sales_summary_bytime_key ON sales_summary_bytime(time_key);
4550 -- Function and trigger to amend summarized column(s) on UPDATE, INSERT, DELETE.
4552 CREATE OR REPLACE FUNCTION maint_sales_summary_bytime() RETURNS TRIGGER
4553 AS $maint_sales_summary_bytime$
4555 delta_time_key integer;
4556 delta_amount_sold numeric(
15,
2);
4557 delta_units_sold numeric(
12);
4558 delta_amount_cost numeric(
15,
2);
4561 -- Work out the increment/decrement amount(s).
4562 IF (TG_OP = 'DELETE') THEN
4564 delta_time_key = OLD.time_key;
4565 delta_amount_sold = -
1 * OLD.amount_sold;
4566 delta_units_sold = -
1 * OLD.units_sold;
4567 delta_amount_cost = -
1 * OLD.amount_cost;
4569 ELSIF (TG_OP = 'UPDATE') THEN
4571 -- forbid updates that change the time_key -
4572 -- (probably not too onerous, as DELETE + INSERT is how most
4573 -- changes will be made).
4574 IF ( OLD.time_key != NEW.time_key) THEN
4575 RAISE EXCEPTION 'Update of time_key : % -
> % not allowed',
4576 OLD.time_key, NEW.time_key;
4579 delta_time_key = OLD.time_key;
4580 delta_amount_sold = NEW.amount_sold - OLD.amount_sold;
4581 delta_units_sold = NEW.units_sold - OLD.units_sold;
4582 delta_amount_cost = NEW.amount_cost - OLD.amount_cost;
4584 ELSIF (TG_OP = 'INSERT') THEN
4586 delta_time_key = NEW.time_key;
4587 delta_amount_sold = NEW.amount_sold;
4588 delta_units_sold = NEW.units_sold;
4589 delta_amount_cost = NEW.amount_cost;
4594 -- Insert or update the summary row with the new values.
4595 <<insert_update
>>
4597 UPDATE sales_summary_bytime
4598 SET amount_sold = amount_sold + delta_amount_sold,
4599 units_sold = units_sold + delta_units_sold,
4600 amount_cost = amount_cost + delta_amount_cost
4601 WHERE time_key = delta_time_key;
4603 EXIT insert_update WHEN found;
4606 INSERT INTO sales_summary_bytime (
4621 WHEN UNIQUE_VIOLATION THEN
4624 END LOOP insert_update;
4629 $maint_sales_summary_bytime$ LANGUAGE plpgsql;
4631 CREATE TRIGGER maint_sales_summary_bytime
4632 AFTER INSERT OR UPDATE OR DELETE ON sales_fact
4633 FOR EACH ROW EXECUTE FUNCTION maint_sales_summary_bytime();
4635 INSERT INTO sales_fact VALUES(
1,
1,
1,
10,
3,
15);
4636 INSERT INTO sales_fact VALUES(
1,
2,
1,
20,
5,
35);
4637 INSERT INTO sales_fact VALUES(
2,
2,
1,
40,
15,
135);
4638 INSERT INTO sales_fact VALUES(
2,
3,
1,
10,
1,
13);
4639 SELECT * FROM sales_summary_bytime;
4640 DELETE FROM sales_fact WHERE product_key =
1;
4641 SELECT * FROM sales_summary_bytime;
4642 UPDATE sales_fact SET units_sold = units_sold *
2;
4643 SELECT * FROM sales_summary_bytime;
4648 <literal>AFTER
</literal> triggers can also make use of
<firstterm>transition
4649 tables
</firstterm> to inspect the entire set of rows changed by the triggering
4650 statement. The
<command>CREATE TRIGGER
</command> command assigns names to one
4651 or both transition tables, and then the function can refer to those names
4652 as though they were read-only temporary tables.
4653 <xref linkend=
"plpgsql-trigger-audit-transition-example"/> shows an example.
4656 <example id=
"plpgsql-trigger-audit-transition-example">
4657 <title>Auditing with Transition Tables
</title>
4660 This example produces the same results as
4661 <xref linkend=
"plpgsql-trigger-audit-example"/>, but instead of using a
4662 trigger that fires for every row, it uses a trigger that fires once
4663 per statement, after collecting the relevant information in a transition
4664 table. This can be significantly faster than the row-trigger approach
4665 when the invoking statement has modified many rows. Notice that we must
4666 make a separate trigger declaration for each kind of event, since the
4667 <literal>REFERENCING
</literal> clauses must be different for each case. But
4668 this does not stop us from using a single trigger function if we choose.
4669 (In practice, it might be better to use three separate functions and
4670 avoid the run-time tests on
<varname>TG_OP
</varname>.)
4675 empname text NOT NULL,
4679 CREATE TABLE emp_audit(
4680 operation char(
1) NOT NULL,
4681 stamp timestamp NOT NULL,
4682 userid text NOT NULL,
4683 empname text NOT NULL,
4687 CREATE OR REPLACE FUNCTION process_emp_audit() RETURNS TRIGGER AS $emp_audit$
4690 -- Create rows in emp_audit to reflect the operations performed on emp,
4691 -- making use of the special variable TG_OP to work out the operation.
4693 IF (TG_OP = 'DELETE') THEN
4694 INSERT INTO emp_audit
4695 SELECT 'D', now(), current_user, o.* FROM old_table o;
4696 ELSIF (TG_OP = 'UPDATE') THEN
4697 INSERT INTO emp_audit
4698 SELECT 'U', now(), current_user, n.* FROM new_table n;
4699 ELSIF (TG_OP = 'INSERT') THEN
4700 INSERT INTO emp_audit
4701 SELECT 'I', now(), current_user, n.* FROM new_table n;
4703 RETURN NULL; -- result is ignored since this is an AFTER trigger
4705 $emp_audit$ LANGUAGE plpgsql;
4707 CREATE TRIGGER emp_audit_ins
4709 REFERENCING NEW TABLE AS new_table
4710 FOR EACH STATEMENT EXECUTE FUNCTION process_emp_audit();
4711 CREATE TRIGGER emp_audit_upd
4713 REFERENCING OLD TABLE AS old_table NEW TABLE AS new_table
4714 FOR EACH STATEMENT EXECUTE FUNCTION process_emp_audit();
4715 CREATE TRIGGER emp_audit_del
4717 REFERENCING OLD TABLE AS old_table
4718 FOR EACH STATEMENT EXECUTE FUNCTION process_emp_audit();
4724 <sect2 id=
"plpgsql-event-trigger">
4725 <title>Triggers on Events
</title>
4728 <application>PL/pgSQL
</application> can be used to define
4729 <link linkend=
"event-triggers">event triggers
</link>.
4730 <productname>PostgreSQL
</productname> requires that a function that
4731 is to be called as an event trigger must be declared as a function with
4732 no arguments and a return type of
<literal>event_trigger
</literal>.
4736 When a
<application>PL/pgSQL
</application> function is called as an
4737 event trigger, several special variables are created automatically
4738 in the top-level block. They are:
4741 <varlistentry id=
"plpgsql-event-trigger-tg-event">
4742 <term><varname>TG_EVENT
</varname> <type>text
</type></term>
4745 event the trigger is fired for.
4750 <varlistentry id=
"plpgsql-event-trigger-tg-tag">
4751 <term><varname>TG_TAG
</varname> <type>text
</type></term>
4754 command tag for which the trigger is fired.
4762 <xref linkend=
"plpgsql-event-trigger-example"/> shows an example of an
4763 event trigger function in
<application>PL/pgSQL
</application>.
4766 <example id=
"plpgsql-event-trigger-example">
4767 <title>A
<application>PL/pgSQL
</application> Event Trigger Function
</title>
4770 This example trigger simply raises a
<literal>NOTICE
</literal> message
4771 each time a supported command is executed.
4775 CREATE OR REPLACE FUNCTION snitch() RETURNS event_trigger AS $$
4777 RAISE NOTICE 'snitch: % %', tg_event, tg_tag;
4779 $$ LANGUAGE plpgsql;
4781 CREATE EVENT TRIGGER snitch ON ddl_command_start EXECUTE FUNCTION snitch();
4788 <sect1 id=
"plpgsql-implementation">
4789 <title><application>PL/pgSQL
</application> under the Hood
</title>
4792 This section discusses some implementation details that are
4793 frequently important for
<application>PL/pgSQL
</application> users to know.
4796 <sect2 id=
"plpgsql-var-subst">
4797 <title>Variable Substitution
</title>
4800 SQL statements and expressions within a
<application>PL/pgSQL
</application> function
4801 can refer to variables and parameters of the function. Behind the scenes,
4802 <application>PL/pgSQL
</application> substitutes query parameters for such references.
4803 Query parameters will only be substituted in places where they are
4804 syntactically permissible. As an extreme case, consider
4805 this example of poor programming style:
4807 INSERT INTO foo (foo) VALUES (foo(foo));
4809 The first occurrence of
<literal>foo
</literal> must syntactically be a table
4810 name, so it will not be substituted, even if the function has a variable
4811 named
<literal>foo
</literal>. The second occurrence must be the name of a
4812 column of that table, so it will not be substituted either. Likewise
4813 the third occurrence must be a function name, so it also will not be
4814 substituted for. Only the last occurrence is a candidate to be a
4815 reference to a variable of the
<application>PL/pgSQL
</application>
4820 Another way to understand this is that variable substitution can only
4821 insert data values into an SQL command; it cannot dynamically change which
4822 database objects are referenced by the command. (If you want to do
4823 that, you must build a command string dynamically, as explained in
4824 <xref linkend=
"plpgsql-statements-executing-dyn"/>.)
4828 Since the names of variables are syntactically no different from the names
4829 of table columns, there can be ambiguity in statements that also refer to
4830 tables: is a given name meant to refer to a table column, or a variable?
4831 Let's change the previous example to
4833 INSERT INTO dest (col) SELECT foo + bar FROM src;
4835 Here,
<literal>dest
</literal> and
<literal>src
</literal> must be table names, and
4836 <literal>col
</literal> must be a column of
<literal>dest
</literal>, but
<literal>foo
</literal>
4837 and
<literal>bar
</literal> might reasonably be either variables of the function
4838 or columns of
<literal>src
</literal>.
4842 By default,
<application>PL/pgSQL
</application> will report an error if a name
4843 in an SQL statement could refer to either a variable or a table column.
4844 You can fix such a problem by renaming the variable or column,
4845 or by qualifying the ambiguous reference, or by telling
4846 <application>PL/pgSQL
</application> which interpretation to prefer.
4850 The simplest solution is to rename the variable or column.
4851 A common coding rule is to use a
4852 different naming convention for
<application>PL/pgSQL
</application>
4853 variables than you use for column names. For example,
4854 if you consistently name function variables
4855 <literal>v_
<replaceable>something
</replaceable></literal> while none of your
4856 column names start with
<literal>v_
</literal>, no conflicts will occur.
4860 Alternatively you can qualify ambiguous references to make them clear.
4861 In the above example,
<literal>src.foo
</literal> would be an unambiguous reference
4862 to the table column. To create an unambiguous reference to a variable,
4863 declare it in a labeled block and use the block's label
4864 (see
<xref linkend=
"plpgsql-structure"/>). For example,
4866 <<block
>>
4871 INSERT INTO dest (col) SELECT block.foo + bar FROM src;
4873 Here
<literal>block.foo
</literal> means the variable even if there is a column
4874 <literal>foo
</literal> in
<literal>src
</literal>. Function parameters, as well as
4875 special variables such as
<literal>FOUND
</literal>, can be qualified by the
4876 function's name, because they are implicitly declared in an outer block
4877 labeled with the function's name.
4881 Sometimes it is impractical to fix all the ambiguous references in a
4882 large body of
<application>PL/pgSQL
</application> code. In such cases you can
4883 specify that
<application>PL/pgSQL
</application> should resolve ambiguous references
4884 as the variable (which is compatible with
<application>PL/pgSQL
</application>'s
4885 behavior before
<productname>PostgreSQL
</productname> 9.0), or as the
4886 table column (which is compatible with some other systems such as
4887 <productname>Oracle
</productname>).
4891 <primary><varname>plpgsql.variable_conflict
</varname> configuration parameter
</primary>
4895 To change this behavior on a system-wide basis, set the configuration
4896 parameter
<literal>plpgsql.variable_conflict
</literal> to one of
4897 <literal>error
</literal>,
<literal>use_variable
</literal>, or
4898 <literal>use_column
</literal> (where
<literal>error
</literal> is the factory default).
4899 This parameter affects subsequent compilations
4900 of statements in
<application>PL/pgSQL
</application> functions, but not statements
4901 already compiled in the current session.
4902 Because changing this setting
4903 can cause unexpected changes in the behavior of
<application>PL/pgSQL
</application>
4904 functions, it can only be changed by a superuser.
4908 You can also set the behavior on a function-by-function basis, by
4909 inserting one of these special commands at the start of the function
4912 #variable_conflict error
4913 #variable_conflict use_variable
4914 #variable_conflict use_column
4916 These commands affect only the function they are written in, and override
4917 the setting of
<literal>plpgsql.variable_conflict
</literal>. An example is
4919 CREATE FUNCTION stamp_user(id int, comment text) RETURNS void AS $$
4920 #variable_conflict use_variable
4922 curtime timestamp := now();
4924 UPDATE users SET last_modified = curtime, comment = comment
4925 WHERE users.id = id;
4927 $$ LANGUAGE plpgsql;
4929 In the
<literal>UPDATE
</literal> command,
<literal>curtime
</literal>,
<literal>comment
</literal>,
4930 and
<literal>id
</literal> will refer to the function's variable and parameters
4931 whether or not
<literal>users
</literal> has columns of those names. Notice
4932 that we had to qualify the reference to
<literal>users.id
</literal> in the
4933 <literal>WHERE
</literal> clause to make it refer to the table column.
4934 But we did not have to qualify the reference to
<literal>comment
</literal>
4935 as a target in the
<literal>UPDATE
</literal> list, because syntactically
4936 that must be a column of
<literal>users
</literal>. We could write the same
4937 function without depending on the
<literal>variable_conflict
</literal> setting
4940 CREATE FUNCTION stamp_user(id int, comment text) RETURNS void AS $$
4943 curtime timestamp := now();
4945 UPDATE users SET last_modified = fn.curtime, comment = stamp_user.comment
4946 WHERE users.id = stamp_user.id;
4948 $$ LANGUAGE plpgsql;
4953 Variable substitution does not happen in a command string given
4954 to
<command>EXECUTE
</command> or one of its variants. If you need to
4955 insert a varying value into such a command, do so as part of
4956 constructing the string value, or use
<literal>USING
</literal>, as illustrated in
4957 <xref linkend=
"plpgsql-statements-executing-dyn"/>.
4961 Variable substitution currently works only in
<command>SELECT
</command>,
4962 <command>INSERT
</command>,
<command>UPDATE
</command>,
4963 <command>DELETE
</command>, and commands containing one of
4964 these (such as
<command>EXPLAIN
</command> and
<command>CREATE TABLE
4965 ... AS SELECT
</command>),
4966 because the main SQL engine allows query parameters only in these
4967 commands. To use a non-constant name or value in other statement
4968 types (generically called utility statements), you must construct
4969 the utility statement as a string and
<command>EXECUTE
</command> it.
4974 <sect2 id=
"plpgsql-plan-caching">
4975 <title>Plan Caching
</title>
4978 The
<application>PL/pgSQL
</application> interpreter parses the function's source
4979 text and produces an internal binary instruction tree the first time the
4980 function is called (within each session). The instruction tree
4981 fully translates the
4982 <application>PL/pgSQL
</application> statement structure, but individual
4983 <acronym>SQL
</acronym> expressions and
<acronym>SQL
</acronym> commands
4984 used in the function are not translated immediately.
4989 <primary>preparing a query
</primary>
4990 <secondary>in PL/pgSQL
</secondary>
4992 As each expression and
<acronym>SQL
</acronym> command is first
4993 executed in the function, the
<application>PL/pgSQL
</application> interpreter
4994 parses and analyzes the command to create a prepared statement,
4995 using the
<acronym>SPI
</acronym> manager's
4996 <function>SPI_prepare
</function> function.
4997 Subsequent visits to that expression or command
4998 reuse the prepared statement. Thus, a function with conditional code
4999 paths that are seldom visited will never incur the overhead of
5000 analyzing those commands that are never executed within the current
5001 session. A disadvantage is that errors
5002 in a specific expression or command cannot be detected until that
5003 part of the function is reached in execution. (Trivial syntax
5004 errors will be detected during the initial parsing pass, but
5005 anything deeper will not be detected until execution.)
5009 <application>PL/pgSQL
</application> (or more precisely, the SPI manager) can
5010 furthermore attempt to cache the execution plan associated with any
5011 particular prepared statement. If a cached plan is not used, then
5012 a fresh execution plan is generated on each visit to the statement,
5013 and the current parameter values (that is,
<application>PL/pgSQL
</application>
5014 variable values) can be used to optimize the selected plan. If the
5015 statement has no parameters, or is executed many times, the SPI manager
5016 will consider creating a
<firstterm>generic
</firstterm> plan that is not dependent
5017 on specific parameter values, and caching that for re-use. Typically
5018 this will happen only if the execution plan is not very sensitive to
5019 the values of the
<application>PL/pgSQL
</application> variables referenced in it.
5020 If it is, generating a plan each time is a net win. See
<xref
5021 linkend=
"sql-prepare"/> for more information about the behavior of
5022 prepared statements.
5026 Because
<application>PL/pgSQL
</application> saves prepared statements
5027 and sometimes execution plans in this way,
5028 SQL commands that appear directly in a
5029 <application>PL/pgSQL
</application> function must refer to the
5030 same tables and columns on every execution; that is, you cannot use
5031 a parameter as the name of a table or column in an SQL command. To get
5032 around this restriction, you can construct dynamic commands using
5033 the
<application>PL/pgSQL
</application> <command>EXECUTE
</command>
5034 statement
— at the price of performing new parse analysis and
5035 constructing a new execution plan on every execution.
5039 The mutable nature of record variables presents another problem in this
5040 connection. When fields of a record variable are used in
5041 expressions or statements, the data types of the fields must not
5042 change from one call of the function to the next, since each
5043 expression will be analyzed using the data type that is present
5044 when the expression is first reached.
<command>EXECUTE
</command> can be
5045 used to get around this problem when necessary.
5049 If the same function is used as a trigger for more than one table,
5050 <application>PL/pgSQL
</application> prepares and caches statements
5051 independently for each such table
— that is, there is a cache
5052 for each trigger function and table combination, not just for each
5053 function. This alleviates some of the problems with varying
5054 data types; for instance, a trigger function will be able to work
5055 successfully with a column named
<literal>key
</literal> even if it happens
5056 to have different types in different tables.
5060 Likewise, functions having polymorphic argument types have a separate
5061 statement cache for each combination of actual argument types they have
5062 been invoked for, so that data type differences do not cause unexpected
5067 Statement caching can sometimes have surprising effects on the
5068 interpretation of time-sensitive values. For example there
5069 is a difference between what these two functions do:
5072 CREATE FUNCTION logfunc1(logtxt text) RETURNS void AS $$
5074 INSERT INTO logtable VALUES (logtxt, 'now');
5076 $$ LANGUAGE plpgsql;
5082 CREATE FUNCTION logfunc2(logtxt text) RETURNS void AS $$
5087 INSERT INTO logtable VALUES (logtxt, curtime);
5089 $$ LANGUAGE plpgsql;
5094 In the case of
<function>logfunc1
</function>, the
5095 <productname>PostgreSQL
</productname> main parser knows when
5096 analyzing the
<command>INSERT
</command> that the
5097 string
<literal>'now'
</literal> should be interpreted as
5098 <type>timestamp
</type>, because the target column of
5099 <classname>logtable
</classname> is of that type. Thus,
5100 <literal>'now'
</literal> will be converted to a
<type>timestamp
</type>
5102 <command>INSERT
</command> is analyzed, and then used in all
5103 invocations of
<function>logfunc1
</function> during the lifetime
5104 of the session. Needless to say, this isn't what the programmer
5105 wanted. A better idea is to use the
<literal>now()
</literal> or
5106 <literal>current_timestamp
</literal> function.
5110 In the case of
<function>logfunc2
</function>, the
5111 <productname>PostgreSQL
</productname> main parser does not know
5112 what type
<literal>'now'
</literal> should become and therefore
5113 it returns a data value of type
<type>text
</type> containing the string
5114 <literal>now
</literal>. During the ensuing assignment
5115 to the local variable
<varname>curtime
</varname>, the
5116 <application>PL/pgSQL
</application> interpreter casts this
5117 string to the
<type>timestamp
</type> type by calling the
5118 <function>textout
</function> and
<function>timestamp_in
</function>
5119 functions for the conversion. So, the computed time stamp is updated
5120 on each execution as the programmer expects. Even though this
5121 happens to work as expected, it's not terribly efficient, so
5122 use of the
<literal>now()
</literal> function would still be a better idea.
5129 <sect1 id=
"plpgsql-development-tips">
5130 <title>Tips for Developing in
<application>PL/pgSQL
</application></title>
5133 One good way to develop in
5134 <application>PL/pgSQL
</application> is to use the text editor of your
5135 choice to create your functions, and in another window, use
5136 <application>psql
</application> to load and test those functions.
5137 If you are doing it this way, it
5138 is a good idea to write the function using
<command>CREATE OR
5139 REPLACE FUNCTION
</command>. That way you can just reload the file to update
5140 the function definition. For example:
5142 CREATE OR REPLACE FUNCTION testfunc(integer) RETURNS integer AS $$
5144 $$ LANGUAGE plpgsql;
5149 While running
<application>psql
</application>, you can load or reload such
5150 a function definition file with:
5154 and then immediately issue SQL commands to test the function.
5158 Another good way to develop in
<application>PL/pgSQL
</application> is with a
5159 GUI database access tool that facilitates development in a
5160 procedural language. One example of such a tool is
5161 <application>pgAdmin
</application>, although others exist. These tools often
5162 provide convenient features such as escaping single quotes and
5163 making it easier to recreate and debug functions.
5166 <sect2 id=
"plpgsql-quote-tips">
5167 <title>Handling of Quotation Marks
</title>
5170 The code of a
<application>PL/pgSQL
</application> function is specified in
5171 <command>CREATE FUNCTION
</command> as a string literal. If you
5172 write the string literal in the ordinary way with surrounding
5173 single quotes, then any single quotes inside the function body
5174 must be doubled; likewise any backslashes must be doubled (assuming
5175 escape string syntax is used).
5176 Doubling quotes is at best tedious, and in more complicated cases
5177 the code can become downright incomprehensible, because you can
5178 easily find yourself needing half a dozen or more adjacent quote marks.
5179 It's recommended that you instead write the function body as a
5180 <quote>dollar-quoted
</quote> string literal (see
<xref
5181 linkend=
"sql-syntax-dollar-quoting"/>). In the dollar-quoting
5182 approach, you never double any quote marks, but instead take care to
5183 choose a different dollar-quoting delimiter for each level of
5184 nesting you need. For example, you might write the
<command>CREATE
5185 FUNCTION
</command> command as:
5187 CREATE OR REPLACE FUNCTION testfunc(integer) RETURNS integer AS $PROC$
5189 $PROC$ LANGUAGE plpgsql;
5191 Within this, you might use quote marks for simple literal strings in
5192 SQL commands and
<literal>$$
</literal> to delimit fragments of SQL commands
5193 that you are assembling as strings. If you need to quote text that
5194 includes
<literal>$$
</literal>, you could use
<literal>$Q$
</literal>, and so on.
5198 The following chart shows what you have to do when writing quote
5199 marks without dollar quoting. It might be useful when translating
5200 pre-dollar quoting code into something more comprehensible.
5204 <varlistentry id=
"plpgsql-quote-tips-1-quot">
5205 <term>1 quotation mark
</term>
5208 To begin and end the function body, for example:
5210 CREATE FUNCTION foo() RETURNS integer AS '
5214 Anywhere within a single-quoted function body, quote marks
5215 <emphasis>must
</emphasis> appear in pairs.
5220 <varlistentry id=
"plpgsql-quote-tips-2-quot">
5221 <term>2 quotation marks
</term>
5224 For string literals inside the function body, for example:
5226 a_output := ''Blah'';
5227 SELECT * FROM users WHERE f_name=''foobar'';
5229 In the dollar-quoting approach, you'd just write:
5232 SELECT * FROM users WHERE f_name='foobar';
5234 which is exactly what the
<application>PL/pgSQL
</application> parser would see
5240 <varlistentry id=
"plpgsql-quote-tips-4-quot">
5241 <term>4 quotation marks
</term>
5244 When you need a single quotation mark in a string constant inside the
5245 function body, for example:
5247 a_output := a_output || '' AND name LIKE ''''foobar'''' AND xyz''
5249 The value actually appended to
<literal>a_output
</literal> would be:
5250 <literal> AND name LIKE 'foobar' AND xyz
</literal>.
5253 In the dollar-quoting approach, you'd write:
5255 a_output := a_output || $$ AND name LIKE 'foobar' AND xyz$$
5257 being careful that any dollar-quote delimiters around this are not
5258 just
<literal>$$
</literal>.
5263 <varlistentry id=
"plpgsql-quote-tips-6-quot">
5264 <term>6 quotation marks
</term>
5267 When a single quotation mark in a string inside the function body is
5268 adjacent to the end of that string constant, for example:
5270 a_output := a_output || '' AND name LIKE ''''foobar''''''
5272 The value appended to
<literal>a_output
</literal> would then be:
5273 <literal> AND name LIKE 'foobar'
</literal>.
5276 In the dollar-quoting approach, this becomes:
5278 a_output := a_output || $$ AND name LIKE 'foobar'$$
5284 <varlistentry id=
"plpgsql-quote-tips-10-quot">
5285 <term>10 quotation marks
</term>
5288 When you want two single quotation marks in a string constant (which
5289 accounts for
8 quotation marks) and this is adjacent to the end of that
5290 string constant (
2 more). You will probably only need that if
5291 you are writing a function that generates other functions, as in
5292 <xref linkend=
"plpgsql-porting-ex2"/>.
5295 a_output := a_output || '' if v_'' ||
5296 referrer_keys.kind || '' like ''''''''''
5297 || referrer_keys.key_string || ''''''''''
5298 then return '''''' || referrer_keys.referrer_type
5299 || ''''''; end if;'';
5301 The value of
<literal>a_output
</literal> would then be:
5303 if v_... like ''...'' then return ''...''; end if;
5307 In the dollar-quoting approach, this becomes:
5309 a_output := a_output || $$ if v_$$ || referrer_keys.kind || $$ like '$$
5310 || referrer_keys.key_string || $$'
5311 then return '$$ || referrer_keys.referrer_type
5314 where we assume we only need to put single quote marks into
5315 <literal>a_output
</literal>, because it will be re-quoted before use.
5322 <sect2 id=
"plpgsql-extra-checks">
5323 <title>Additional Compile-Time and Run-Time Checks
</title>
5326 To aid the user in finding instances of simple but common problems before
5327 they cause harm,
<application>PL/pgSQL
</application> provides additional
5328 <replaceable>checks
</replaceable>. When enabled, depending on the configuration, they
5329 can be used to emit either a
<literal>WARNING
</literal> or an
<literal>ERROR
</literal>
5330 during the compilation of a function. A function which has received
5331 a
<literal>WARNING
</literal> can be executed without producing further messages,
5332 so you are advised to test in a separate development environment.
5336 Setting
<varname>plpgsql.extra_warnings
</varname>, or
5337 <varname>plpgsql.extra_errors
</varname>, as appropriate, to
<literal>"all"</literal>
5338 is encouraged in development and/or testing environments.
5342 These additional checks are enabled through the configuration variables
5343 <varname>plpgsql.extra_warnings
</varname> for warnings and
5344 <varname>plpgsql.extra_errors
</varname> for errors. Both can be set either to
5345 a comma-separated list of checks,
<literal>"none"</literal> or
5346 <literal>"all"</literal>. The default is
<literal>"none"</literal>. Currently
5347 the list of available checks includes:
5349 <varlistentry id=
"plpgsql-extra-checks-shadowed-variables">
5350 <term><varname>shadowed_variables
</varname></term>
5353 Checks if a declaration shadows a previously defined variable.
5358 <varlistentry id=
"plpgsql-extra-checks-strict-multi-assignment">
5359 <term><varname>strict_multi_assignment
</varname></term>
5362 Some
<application>PL/pgSQL
</application> commands allow assigning
5363 values to more than one variable at a time, such as
5364 <command>SELECT INTO
</command>. Typically, the number of target
5365 variables and the number of source variables should match, though
5366 <application>PL/pgSQL
</application> will use
<literal>NULL
</literal>
5367 for missing values and extra variables are ignored. Enabling this
5368 check will cause
<application>PL/pgSQL
</application> to throw a
5369 <literal>WARNING
</literal> or
<literal>ERROR
</literal> whenever the
5370 number of target variables and the number of source variables are
5376 <varlistentry id=
"plpgsql-extra-checks-too-many-rows">
5377 <term><varname>too_many_rows
</varname></term>
5380 Enabling this check will cause
<application>PL/pgSQL
</application> to
5381 check if a given query returns more than one row when an
5382 <literal>INTO
</literal> clause is used. As an
<literal>INTO
</literal>
5383 statement will only ever use one row, having a query return multiple
5384 rows is generally either inefficient and/or nondeterministic and
5385 therefore is likely an error.
5391 The following example shows the effect of
<varname>plpgsql.extra_warnings
</varname>
5392 set to
<varname>shadowed_variables
</varname>:
5394 SET plpgsql.extra_warnings TO 'shadowed_variables';
5396 CREATE FUNCTION foo(f1 int) RETURNS int AS $$
5402 $$ LANGUAGE plpgsql;
5403 WARNING: variable
"f1" shadows a previously defined variable
5408 The below example shows the effects of setting
5409 <varname>plpgsql.extra_warnings
</varname> to
5410 <varname>strict_multi_assignment
</varname>:
5412 SET plpgsql.extra_warnings TO 'strict_multi_assignment';
5414 CREATE OR REPLACE FUNCTION public.foo()
5423 SELECT
1,
2 INTO x, y;
5424 SELECT
1,
2,
3 INTO x, y;
5429 WARNING: number of source and target fields in assignment does not match
5430 DETAIL: strict_multi_assignment check of extra_warnings is active.
5431 HINT: Make sure the query returns the exact list of columns.
5432 WARNING: number of source and target fields in assignment does not match
5433 DETAIL: strict_multi_assignment check of extra_warnings is active.
5434 HINT: Make sure the query returns the exact list of columns.
5445 <!-- **** Porting from Oracle PL/SQL **** -->
5447 <sect1 id=
"plpgsql-porting">
5448 <title>Porting from
<productname>Oracle
</productname> PL/SQL
</title>
5450 <indexterm zone=
"plpgsql-porting">
5451 <primary>Oracle
</primary>
5452 <secondary>porting from PL/SQL to PL/pgSQL
</secondary>
5455 <indexterm zone=
"plpgsql-porting">
5456 <primary>PL/SQL (Oracle)
</primary>
5457 <secondary>porting to PL/pgSQL
</secondary>
5461 This section explains differences between
5462 <productname>PostgreSQL
</productname>'s
<application>PL/pgSQL
</application>
5463 language and Oracle's
<application>PL/SQL
</application> language,
5464 to help developers who port applications from
5465 <trademark class=
"registered">Oracle
</trademark> to
<productname>PostgreSQL
</productname>.
5469 <application>PL/pgSQL
</application> is similar to PL/SQL in many
5470 aspects. It is a block-structured, imperative language, and all
5471 variables have to be declared. Assignments, loops, and conditionals
5472 are similar. The main differences you should keep in mind when
5473 porting from
<application>PL/SQL
</application> to
5474 <application>PL/pgSQL
</application> are:
5479 If a name used in an SQL command could be either a column name of a
5480 table used in the command or a reference to a variable of the function,
5481 <application>PL/SQL
</application> treats it as a column name.
5482 By default,
<application>PL/pgSQL
</application> will throw an error
5483 complaining that the name is ambiguous. You can specify
5484 <literal>plpgsql.variable_conflict
</literal> =
<literal>use_column
</literal>
5485 to change this behavior to match
<application>PL/SQL
</application>,
5486 as explained in
<xref linkend=
"plpgsql-var-subst"/>.
5487 It's often best to avoid such ambiguities in the first place,
5488 but if you have to port a large amount of code that depends on
5489 this behavior, setting
<literal>variable_conflict
</literal> may be the
5496 In
<productname>PostgreSQL
</productname> the function body must be written as
5497 a string literal. Therefore you need to use dollar quoting or escape
5498 single quotes in the function body. (See
<xref
5499 linkend=
"plpgsql-quote-tips"/>.)
5505 Data type names often need translation. For example, in Oracle string
5506 values are commonly declared as being of type
<type>varchar2
</type>, which
5507 is a non-SQL-standard type. In
<productname>PostgreSQL
</productname>,
5508 use type
<type>varchar
</type> or
<type>text
</type> instead. Similarly, replace
5509 type
<type>number
</type> with
<type>numeric
</type>, or use some other numeric
5510 data type if there's a more appropriate one.
5516 Instead of packages, use schemas to organize your functions
5523 Since there are no packages, there are no package-level variables
5524 either. This is somewhat annoying. You can keep per-session state
5525 in temporary tables instead.
5531 Integer
<command>FOR
</command> loops with
<literal>REVERSE
</literal> work
5532 differently:
<application>PL/SQL
</application> counts down from the second
5533 number to the first, while
<application>PL/pgSQL
</application> counts down
5534 from the first number to the second, requiring the loop bounds
5535 to be swapped when porting. This incompatibility is unfortunate
5536 but is unlikely to be changed. (See
<xref
5537 linkend=
"plpgsql-integer-for"/>.)
5543 <command>FOR
</command> loops over queries (other than cursors) also work
5544 differently: the target variable(s) must have been declared,
5545 whereas
<application>PL/SQL
</application> always declares them implicitly.
5546 An advantage of this is that the variable values are still accessible
5547 after the loop exits.
5553 There are various notational differences for the use of cursor
5561 <sect2 id=
"plpgsql-porting-examples">
5562 <title>Porting Examples
</title>
5565 <xref linkend=
"pgsql-porting-ex1"/> shows how to port a simple
5566 function from
<application>PL/SQL
</application> to
<application>PL/pgSQL
</application>.
5569 <example id=
"pgsql-porting-ex1">
5570 <title>Porting a Simple Function from
<application>PL/SQL
</application> to
<application>PL/pgSQL
</application></title>
5573 Here is an
<productname>Oracle
</productname> <application>PL/SQL
</application> function:
5575 CREATE OR REPLACE FUNCTION cs_fmt_browser_version(v_name varchar2,
5579 IF v_version IS NULL THEN
5582 RETURN v_name || '/' || v_version;
5590 Let's go through this function and see the differences compared to
5591 <application>PL/pgSQL
</application>:
5596 The type name
<type>varchar2
</type> has to be changed to
<type>varchar
</type>
5597 or
<type>text
</type>. In the examples in this section, we'll
5598 use
<type>varchar
</type>, but
<type>text
</type> is often a better choice if
5599 you do not need specific string length limits.
5605 The
<literal>RETURN
</literal> key word in the function
5606 prototype (not the function body) becomes
5607 <literal>RETURNS
</literal> in
5608 <productname>PostgreSQL
</productname>.
5609 Also,
<literal>IS
</literal> becomes
<literal>AS
</literal>, and you need to
5610 add a
<literal>LANGUAGE
</literal> clause because
<application>PL/pgSQL
</application>
5611 is not the only possible function language.
5617 In
<productname>PostgreSQL
</productname>, the function body is considered
5618 to be a string literal, so you need to use quote marks or dollar
5619 quotes around it. This substitutes for the terminating
<literal>/
</literal>
5620 in the Oracle approach.
5626 The
<literal>show errors
</literal> command does not exist in
5627 <productname>PostgreSQL
</productname>, and is not needed since errors are
5628 reported automatically.
5635 This is how this function would look when ported to
5636 <productname>PostgreSQL
</productname>:
5639 CREATE OR REPLACE FUNCTION cs_fmt_browser_version(v_name varchar,
5641 RETURNS varchar AS $$
5643 IF v_version IS NULL THEN
5646 RETURN v_name || '/' || v_version;
5648 $$ LANGUAGE plpgsql;
5654 <xref linkend=
"plpgsql-porting-ex2"/> shows how to port a
5655 function that creates another function and how to handle the
5656 ensuing quoting problems.
5659 <example id=
"plpgsql-porting-ex2">
5660 <title>Porting a Function that Creates Another Function from
<application>PL/SQL
</application> to
<application>PL/pgSQL
</application></title>
5663 The following procedure grabs rows from a
5664 <command>SELECT
</command> statement and builds a large function
5665 with the results in
<literal>IF
</literal> statements, for the
5670 This is the Oracle version:
5672 CREATE OR REPLACE PROCEDURE cs_update_referrer_type_proc IS
5673 CURSOR referrer_keys IS
5674 SELECT * FROM cs_referrer_keys
5676 func_cmd VARCHAR(
4000);
5678 func_cmd := 'CREATE OR REPLACE FUNCTION cs_find_referrer_type(v_host IN VARCHAR2,
5679 v_domain IN VARCHAR2, v_url IN VARCHAR2) RETURN VARCHAR2 IS BEGIN';
5681 FOR referrer_key IN referrer_keys LOOP
5682 func_cmd := func_cmd ||
5683 ' IF v_' || referrer_key.kind
5684 || ' LIKE ''' || referrer_key.key_string
5685 || ''' THEN RETURN ''' || referrer_key.referrer_type
5689 func_cmd := func_cmd || ' RETURN NULL; END;';
5691 EXECUTE IMMEDIATE func_cmd;
5699 Here is how this function would end up in
<productname>PostgreSQL
</productname>:
5701 CREATE OR REPLACE PROCEDURE cs_update_referrer_type_proc() AS $func$
5703 referrer_keys CURSOR IS
5704 SELECT * FROM cs_referrer_keys
5709 func_body := 'BEGIN';
5711 FOR referrer_key IN referrer_keys LOOP
5712 func_body := func_body ||
5713 ' IF v_' || referrer_key.kind
5714 || ' LIKE ' || quote_literal(referrer_key.key_string)
5715 || ' THEN RETURN ' || quote_literal(referrer_key.referrer_type)
5719 func_body := func_body || ' RETURN NULL; END;';
5722 'CREATE OR REPLACE FUNCTION cs_find_referrer_type(v_host varchar,
5725 RETURNS varchar AS '
5726 || quote_literal(func_body)
5727 || ' LANGUAGE plpgsql;' ;
5731 $func$ LANGUAGE plpgsql;
5733 Notice how the body of the function is built separately and passed
5734 through
<literal>quote_literal
</literal> to double any quote marks in it. This
5735 technique is needed because we cannot safely use dollar quoting for
5736 defining the new function: we do not know for sure what strings will
5737 be interpolated from the
<structfield>referrer_key.key_string
</structfield> field.
5738 (We are assuming here that
<structfield>referrer_key.kind
</structfield> can be
5739 trusted to always be
<literal>host
</literal>,
<literal>domain
</literal>, or
5740 <literal>url
</literal>, but
<structfield>referrer_key.key_string
</structfield> might be
5741 anything, in particular it might contain dollar signs.) This function
5742 is actually an improvement on the Oracle original, because it will
5743 not generate broken code when
<structfield>referrer_key.key_string
</structfield> or
5744 <structfield>referrer_key.referrer_type
</structfield> contain quote marks.
5749 <xref linkend=
"plpgsql-porting-ex3"/> shows how to port a function
5750 with
<literal>OUT
</literal> parameters and string manipulation.
5751 <productname>PostgreSQL
</productname> does not have a built-in
5752 <function>instr
</function> function, but you can create one
5753 using a combination of other
5754 functions. In
<xref linkend=
"plpgsql-porting-appendix"/> there is a
5755 <application>PL/pgSQL
</application> implementation of
5756 <function>instr
</function> that you can use to make your porting
5760 <example id=
"plpgsql-porting-ex3">
5761 <title>Porting a Procedure With String Manipulation and
5762 <literal>OUT
</literal> Parameters from
<application>PL/SQL
</application> to
5763 <application>PL/pgSQL
</application></title>
5766 The following
<productname>Oracle
</productname> PL/SQL procedure is used
5767 to parse a URL and return several elements (host, path, and query).
5771 This is the Oracle version:
5773 CREATE OR REPLACE PROCEDURE cs_parse_url(
5775 v_host OUT VARCHAR2, -- This will be passed back
5776 v_path OUT VARCHAR2, -- This one too
5777 v_query OUT VARCHAR2) -- And this one
5785 a_pos1 := instr(v_url, '//');
5790 a_pos2 := instr(v_url, '/', a_pos1 +
2);
5792 v_host := substr(v_url, a_pos1 +
2);
5797 v_host := substr(v_url, a_pos1 +
2, a_pos2 - a_pos1 -
2);
5798 a_pos1 := instr(v_url, '?', a_pos2 +
1);
5801 v_path := substr(v_url, a_pos2);
5805 v_path := substr(v_url, a_pos2, a_pos1 - a_pos2);
5806 v_query := substr(v_url, a_pos1 +
1);
5814 Here is a possible translation into
<application>PL/pgSQL
</application>:
5816 CREATE OR REPLACE FUNCTION cs_parse_url(
5818 v_host OUT VARCHAR, -- This will be passed back
5819 v_path OUT VARCHAR, -- This one too
5820 v_query OUT VARCHAR) -- And this one
5829 a_pos1 := instr(v_url, '//');
5834 a_pos2 := instr(v_url, '/', a_pos1 +
2);
5836 v_host := substr(v_url, a_pos1 +
2);
5841 v_host := substr(v_url, a_pos1 +
2, a_pos2 - a_pos1 -
2);
5842 a_pos1 := instr(v_url, '?', a_pos2 +
1);
5845 v_path := substr(v_url, a_pos2);
5849 v_path := substr(v_url, a_pos2, a_pos1 - a_pos2);
5850 v_query := substr(v_url, a_pos1 +
1);
5852 $$ LANGUAGE plpgsql;
5855 This function could be used like this:
5857 SELECT * FROM cs_parse_url('http://foobar.com/query.cgi?baz');
5863 <xref linkend=
"plpgsql-porting-ex4"/> shows how to port a procedure
5864 that uses numerous features that are specific to Oracle.
5867 <example id=
"plpgsql-porting-ex4">
5868 <title>Porting a Procedure from
<application>PL/SQL
</application> to
<application>PL/pgSQL
</application></title>
5874 CREATE OR REPLACE PROCEDURE cs_create_job(v_job_id IN INTEGER) IS
5875 a_running_job_count INTEGER;
5877 LOCK TABLE cs_jobs IN EXCLUSIVE MODE;
5879 SELECT count(*) INTO a_running_job_count FROM cs_jobs WHERE end_stamp IS NULL;
5881 IF a_running_job_count
> 0 THEN
5882 COMMIT; -- free lock
5883 raise_application_error(-
20000,
5884 'Unable to create a new job: a job is currently running.');
5887 DELETE FROM cs_active_job;
5888 INSERT INTO cs_active_job(job_id) VALUES (v_job_id);
5891 INSERT INTO cs_jobs (job_id, start_stamp) VALUES (v_job_id, now());
5893 WHEN dup_val_on_index THEN NULL; -- don't worry if it already exists
5903 This is how we could port this procedure to
<application>PL/pgSQL
</application>:
5906 CREATE OR REPLACE PROCEDURE cs_create_job(v_job_id integer) AS $$
5908 a_running_job_count integer;
5910 LOCK TABLE cs_jobs IN EXCLUSIVE MODE;
5912 SELECT count(*) INTO a_running_job_count FROM cs_jobs WHERE end_stamp IS NULL;
5914 IF a_running_job_count
> 0 THEN
5915 COMMIT; -- free lock
5916 RAISE EXCEPTION 'Unable to create a new job: a job is currently running'; --
<co id=
"co.plpgsql-porting-raise"/>
5919 DELETE FROM cs_active_job;
5920 INSERT INTO cs_active_job(job_id) VALUES (v_job_id);
5923 INSERT INTO cs_jobs (job_id, start_stamp) VALUES (v_job_id, now());
5925 WHEN unique_violation THEN --
<co id=
"co.plpgsql-porting-exception"/>
5926 -- don't worry if it already exists
5930 $$ LANGUAGE plpgsql;
5934 <callout arearefs=
"co.plpgsql-porting-raise">
5936 The syntax of
<literal>RAISE
</literal> is considerably different from
5937 Oracle's statement, although the basic case
<literal>RAISE
</literal>
5938 <replaceable class=
"parameter">exception_name
</replaceable> works
5942 <callout arearefs=
"co.plpgsql-porting-exception">
5944 The exception names supported by
<application>PL/pgSQL
</application> are
5945 different from Oracle's. The set of built-in exception names
5946 is much larger (see
<xref linkend=
"errcodes-appendix"/>). There
5947 is not currently a way to declare user-defined exception names,
5948 although you can throw user-chosen SQLSTATE values instead.
5956 <sect2 id=
"plpgsql-porting-other">
5957 <title>Other Things to Watch For
</title>
5960 This section explains a few other things to watch for when porting
5961 Oracle
<application>PL/SQL
</application> functions to
5962 <productname>PostgreSQL
</productname>.
5965 <sect3 id=
"plpgsql-porting-exceptions">
5966 <title>Implicit Rollback after Exceptions
</title>
5969 In
<application>PL/pgSQL
</application>, when an exception is caught by an
5970 <literal>EXCEPTION
</literal> clause, all database changes since the block's
5971 <literal>BEGIN
</literal> are automatically rolled back. That is, the behavior
5972 is equivalent to what you'd get in Oracle with:
5988 If you are translating an Oracle procedure that uses
5989 <command>SAVEPOINT
</command> and
<command>ROLLBACK TO
</command> in this style,
5990 your task is easy: just omit the
<command>SAVEPOINT
</command> and
5991 <command>ROLLBACK TO
</command>. If you have a procedure that uses
5992 <command>SAVEPOINT
</command> and
<command>ROLLBACK TO
</command> in a different way
5993 then some actual thought will be required.
5997 <sect3 id=
"plpgsql-porting-other-execute">
5998 <title><command>EXECUTE
</command></title>
6001 The
<application>PL/pgSQL
</application> version of
6002 <command>EXECUTE
</command> works similarly to the
6003 <application>PL/SQL
</application> version, but you have to remember to use
6004 <function>quote_literal
</function> and
6005 <function>quote_ident
</function> as described in
<xref
6006 linkend=
"plpgsql-statements-executing-dyn"/>. Constructs of the
6007 type
<literal>EXECUTE 'SELECT * FROM $
1';
</literal> will not work
6008 reliably unless you use these functions.
6012 <sect3 id=
"plpgsql-porting-optimization">
6013 <title>Optimizing
<application>PL/pgSQL
</application> Functions
</title>
6016 <productname>PostgreSQL
</productname> gives you two function creation
6017 modifiers to optimize execution:
<quote>volatility
</quote> (whether
6018 the function always returns the same result when given the same
6019 arguments) and
<quote>strictness
</quote> (whether the function
6020 returns null if any argument is null). Consult the
<xref
6021 linkend=
"sql-createfunction"/>
6022 reference page for details.
6026 When making use of these optimization attributes, your
6027 <command>CREATE FUNCTION
</command> statement might look something
6031 CREATE FUNCTION foo(...) RETURNS integer AS $$
6033 $$ LANGUAGE plpgsql STRICT IMMUTABLE;
6039 <sect2 id=
"plpgsql-porting-appendix">
6040 <title>Appendix
</title>
6043 This section contains the code for a set of Oracle-compatible
6044 <function>instr
</function> functions that you can use to simplify
6045 your porting efforts.
6049 <primary><function>instr
</function> function
</primary>
6052 <programlisting><![CDATA[
6054 -- instr functions that mimic Oracle's counterpart
6055 -- Syntax: instr(string1, string2 [, n [, m]])
6056 -- where [] denotes optional parameters.
6058 -- Search string1, beginning at the nth character, for the mth occurrence
6059 -- of string2. If n is negative, search backwards, starting at the abs(n)'th
6060 -- character from the end of string1.
6061 -- If n is not passed, assume
1 (search starts at first character).
6062 -- If m is not passed, assume
1 (find first occurrence).
6063 -- Returns starting index of string2 in string1, or
0 if string2 is not found.
6066 CREATE FUNCTION instr(varchar, varchar) RETURNS integer AS $$
6068 RETURN instr($
1, $
2,
1);
6070 $$ LANGUAGE plpgsql STRICT IMMUTABLE;
6073 CREATE FUNCTION instr(string varchar, string_to_search_for varchar,
6075 RETURNS integer AS $$
6077 pos integer NOT NULL DEFAULT
0;
6083 IF beg_index
> 0 THEN
6084 temp_str := substring(string FROM beg_index);
6085 pos := position(string_to_search_for IN temp_str);
6090 RETURN pos + beg_index -
1;
6092 ELSIF beg_index <
0 THEN
6093 ss_length := char_length(string_to_search_for);
6094 length := char_length(string);
6095 beg := length +
1 + beg_index;
6098 temp_str := substring(string FROM beg FOR ss_length);
6099 IF string_to_search_for = temp_str THEN
6111 $$ LANGUAGE plpgsql STRICT IMMUTABLE;
6114 CREATE FUNCTION instr(string varchar, string_to_search_for varchar,
6115 beg_index integer, occur_index integer)
6116 RETURNS integer AS $$
6118 pos integer NOT NULL DEFAULT
0;
6119 occur_number integer NOT NULL DEFAULT
0;
6126 IF occur_index <=
0 THEN
6127 RAISE 'argument ''%'' is out of range', occur_index
6128 USING ERRCODE = '
22003';
6131 IF beg_index
> 0 THEN
6132 beg := beg_index -
1;
6133 FOR i IN
1..occur_index LOOP
6134 temp_str := substring(string FROM beg +
1);
6135 pos := position(string_to_search_for IN temp_str);
6143 ELSIF beg_index <
0 THEN
6144 ss_length := char_length(string_to_search_for);
6145 length := char_length(string);
6146 beg := length +
1 + beg_index;
6149 temp_str := substring(string FROM beg FOR ss_length);
6150 IF string_to_search_for = temp_str THEN
6151 occur_number := occur_number +
1;
6152 IF occur_number = occur_index THEN
6165 $$ LANGUAGE plpgsql STRICT IMMUTABLE;