1 <!-- doc/src/sgml/plpgsql.sgml -->
4 <title><application>PL/pgSQL</application> - <acronym>SQL</acronym> Procedural Language</title>
6 <indexterm zone="plpgsql">
7 <primary>PL/pgSQL</primary>
10 <sect1 id="plpgsql-overview">
11 <title>Overview</title>
14 <application>PL/pgSQL</application> is a loadable procedural
15 language for the <productname>PostgreSQL</productname> database
16 system. The design goals of <application>PL/pgSQL</> were to create
17 a loadable procedural language that
22 can be used to create functions and trigger procedures,
27 adds control structures to the <acronym>SQL</acronym> language,
32 can perform complex computations,
37 inherits all user-defined types, functions, and operators,
42 can be defined to be trusted by the server,
54 Functions created with <application>PL/pgSQL</application> can be
55 used anywhere that built-in functions could be used.
56 For example, it is possible to
57 create complex conditional computation functions and later use
58 them to define operators or use them in index expressions.
62 In <productname>PostgreSQL</> 9.0 and later,
63 <application>PL/pgSQL</application> is installed by default.
64 However it is still a loadable module, so especially security-conscious
65 administrators could choose to remove it.
68 <sect2 id="plpgsql-advantages">
69 <title>Advantages of Using <application>PL/pgSQL</application></title>
72 <acronym>SQL</acronym> is the language <productname>PostgreSQL</>
73 and most other relational databases use as query language. It's
74 portable and easy to learn. But every <acronym>SQL</acronym>
75 statement must be executed individually by the database server.
79 That means that your client application must send each query to
80 the database server, wait for it to be processed, receive and
81 process the results, do some computation, then send further
82 queries to the server. All this incurs interprocess
83 communication and will also incur network overhead if your client
84 is on a different machine than the database server.
88 With <application>PL/pgSQL</application> you can group a block of
89 computation and a series of queries <emphasis>inside</emphasis>
90 the database server, thus having the power of a procedural
91 language and the ease of use of SQL, but with considerable
92 savings of client/server communication overhead.
96 <listitem><para> Extra round trips between
97 client and server are eliminated </para></listitem>
99 <listitem><para> Intermediate results that the client does not
100 need do not have to be marshaled or transferred between server
101 and client </para></listitem>
103 <listitem><para> Multiple rounds of query
104 parsing can be avoided </para></listitem>
107 <para> This can result in a considerable performance increase as
108 compared to an application that does not use stored functions.
112 Also, with <application>PL/pgSQL</application> you can use all
113 the data types, operators and functions of SQL.
117 <sect2 id="plpgsql-args-results">
118 <title>Supported Argument and Result Data Types</title>
121 Functions written in <application>PL/pgSQL</application> can accept
122 as arguments any scalar or array data type supported by the server,
123 and they can return a result of any of these types. They can also
124 accept or return any composite type (row type) specified by name.
125 It is also possible to declare a <application>PL/pgSQL</application>
126 function as returning <type>record</>, which means that the result
127 is a row type whose columns are determined by specification in the
128 calling query, as discussed in <xref linkend="queries-tablefunctions">.
132 <application>PL/pgSQL</> functions can be declared to accept a variable
133 number of arguments by using the <literal>VARIADIC</> marker. This
134 works exactly the same way as for SQL functions, as discussed in
135 <xref linkend="xfunc-sql-variadic-functions">.
139 <application>PL/pgSQL</> functions can also be declared to accept
140 and return the polymorphic types
141 <type>anyelement</type>, <type>anyarray</type>, <type>anynonarray</type>,
142 and <type>anyenum</>. The actual
143 data types handled by a polymorphic function can vary from call to
144 call, as discussed in <xref linkend="extend-types-polymorphic">.
145 An example is shown in <xref linkend="plpgsql-declaration-parameters">.
149 <application>PL/pgSQL</> functions can also be declared to return
150 a <quote>set</> (or table) of any data type that can be returned as
151 a single instance. Such a function generates its output by executing
152 <command>RETURN NEXT</> for each desired element of the result
153 set, or by using <command>RETURN QUERY</> to output the result of
158 Finally, a <application>PL/pgSQL</> function can be declared to return
159 <type>void</> if it has no useful return value.
163 <application>PL/pgSQL</> functions can also be declared with output
164 parameters in place of an explicit specification of the return type.
165 This does not add any fundamental capability to the language, but
166 it is often convenient, especially for returning multiple values.
167 The <literal>RETURNS TABLE</> notation can also be used in place
168 of <literal>RETURNS SETOF</>.
172 Specific examples appear in
173 <xref linkend="plpgsql-declaration-parameters"> and
174 <xref linkend="plpgsql-statements-returning">.
179 <sect1 id="plpgsql-structure">
180 <title>Structure of <application>PL/pgSQL</application></title>
183 <application>PL/pgSQL</application> is a block-structured language.
184 The complete text of a function definition must be a
185 <firstterm>block</>. A block is defined as:
188 <optional> <<<replaceable>label</replaceable>>> </optional>
190 <replaceable>declarations</replaceable> </optional>
192 <replaceable>statements</replaceable>
193 END <optional> <replaceable>label</replaceable> </optional>;
198 Each declaration and each statement within a block is terminated
199 by a semicolon. A block that appears within another block must
200 have a semicolon after <literal>END</literal>, as shown above;
201 however the final <literal>END</literal> that
202 concludes a function body does not require a semicolon.
207 A common mistake is to write a semicolon immediately after
208 <literal>BEGIN</>. This is incorrect and will result in a syntax error.
213 A <replaceable>label</replaceable> is only needed if you want to
214 identify the block for use
215 in an <literal>EXIT</> statement, or to qualify the names of the
216 variables declared in the block. If a label is given after
217 <literal>END</>, it must match the label at the block's beginning.
221 All key words are case-insensitive.
222 Identifiers are implicitly converted to lower case
223 unless double-quoted, just as they are in ordinary SQL commands.
227 Comments work the same way in <application>PL/pgSQL</> code as in
228 ordinary SQL. A double dash (<literal>--</literal>) starts a comment
229 that extends to the end of the line. A <literal>/*</literal> starts a
230 block comment that extends to the matching occurrence of
231 <literal>*/</literal>. Block comments nest.
235 Any statement in the statement section of a block
236 can be a <firstterm>subblock</>. Subblocks can be used for
237 logical grouping or to localize variables to a small group
238 of statements. Variables declared in a subblock mask any
239 similarly-named variables of outer blocks for the duration
240 of the subblock; but you can access the outer variables anyway
241 if you qualify their names with their block's label. For example:
243 CREATE FUNCTION somefunc() RETURNS integer AS $$
244 << outerblock >>
246 quantity integer := 30;
248 RAISE NOTICE 'Quantity here is %', quantity; -- Prints 30
254 quantity integer := 80;
256 RAISE NOTICE 'Quantity here is %', quantity; -- Prints 80
257 RAISE NOTICE 'Outer quantity here is %', outerblock.quantity; -- Prints 50
260 RAISE NOTICE 'Quantity here is %', quantity; -- Prints 50
270 There is actually a hidden <quote>outer block</> surrounding the body
271 of any <application>PL/pgSQL</> function. This block provides the
272 declarations of the function's parameters (if any), as well as some
273 special variables such as <literal>FOUND</literal> (see
274 <xref linkend="plpgsql-statements-diagnostics">). The outer block is
275 labeled with the function's name, meaning that parameters and special
276 variables can be qualified with the function's name.
281 It is important not to confuse the use of
282 <command>BEGIN</>/<command>END</> for grouping statements in
283 <application>PL/pgSQL</> with the similarly-named SQL commands
285 control. <application>PL/pgSQL</>'s <command>BEGIN</>/<command>END</>
286 are only for grouping; they do not start or end a transaction.
287 Functions and trigger procedures are always executed within a transaction
288 established by an outer query — they cannot start or commit that
289 transaction, since there would be no context for them to execute in.
290 However, a block containing an <literal>EXCEPTION</> clause effectively
291 forms a subtransaction that can be rolled back without affecting the
292 outer transaction. For more about that see <xref
293 linkend="plpgsql-error-trapping">.
297 <sect1 id="plpgsql-declarations">
298 <title>Declarations</title>
301 All variables used in a block must be declared in the
302 declarations section of the block.
303 (The only exceptions are that the loop variable of a <literal>FOR</> loop
304 iterating over a range of integer values is automatically declared as an
305 integer variable, and likewise the loop variable of a <literal>FOR</> loop
306 iterating over a cursor's result is automatically declared as a
311 <application>PL/pgSQL</> variables can have any SQL data type, such as
312 <type>integer</type>, <type>varchar</type>, and
317 Here are some examples of variable declarations:
322 myrow tablename%ROWTYPE;
323 myfield tablename.columnname%TYPE;
329 The general syntax of a variable declaration is:
331 <replaceable>name</replaceable> <optional> CONSTANT </optional> <replaceable>type</replaceable> <optional> NOT NULL </optional> <optional> { DEFAULT | := } <replaceable>expression</replaceable> </optional>;
333 The <literal>DEFAULT</> clause, if given, specifies the initial value assigned
334 to the variable when the block is entered. If the <literal>DEFAULT</> clause
335 is not given then the variable is initialized to the
336 <acronym>SQL</acronym> null value.
337 The <literal>CONSTANT</> option prevents the variable from being
338 assigned to, so that its value will remain constant for the duration of
340 If <literal>NOT NULL</>
341 is specified, an assignment of a null value results in a run-time
342 error. All variables declared as <literal>NOT NULL</>
343 must have a nonnull default value specified.
347 A variable's default value is evaluated and assigned to the variable
348 each time the block is entered (not just once per function call).
349 So, for example, assigning <literal>now()</literal> to a variable of type
350 <type>timestamp</type> causes the variable to have the
351 time of the current function call, not the time when the function was
358 quantity integer DEFAULT 32;
359 url varchar := 'http://mysite.com';
360 user_id CONSTANT integer := 10;
364 <sect2 id="plpgsql-declaration-parameters">
365 <title>Declaring Function Parameters</title>
368 Parameters passed to functions are named with the identifiers
369 <literal>$1</literal>, <literal>$2</literal>,
370 etc. Optionally, aliases can be declared for
371 <literal>$<replaceable>n</replaceable></literal>
372 parameter names for increased readability. Either the alias or the
373 numeric identifier can then be used to refer to the parameter value.
377 There are two ways to create an alias. The preferred way is to give a
378 name to the parameter in the <command>CREATE FUNCTION</command> command,
381 CREATE FUNCTION sales_tax(subtotal real) RETURNS real AS $$
383 RETURN subtotal * 0.06;
387 The other way, which was the only way available before
388 <productname>PostgreSQL</productname> 8.0, is to explicitly
389 declare an alias, using the declaration syntax
392 <replaceable>name</replaceable> ALIAS FOR $<replaceable>n</replaceable>;
395 The same example in this style looks like:
397 CREATE FUNCTION sales_tax(real) RETURNS real AS $$
399 subtotal ALIAS FOR $1;
401 RETURN subtotal * 0.06;
409 These two examples are not perfectly equivalent. In the first case,
410 <literal>subtotal</> could be referenced as
411 <literal>sales_tax.subtotal</>, but in the second case it could not.
412 (Had we attached a label to the inner block, <literal>subtotal</> could
413 be qualified with that label, instead.)
420 CREATE FUNCTION instr(varchar, integer) RETURNS integer AS $$
422 v_string ALIAS FOR $1;
425 -- some computations using v_string and index here
430 CREATE FUNCTION concat_selected_fields(in_t sometablename) RETURNS text AS $$
432 RETURN in_t.f1 || in_t.f3 || in_t.f5 || in_t.f7;
439 When a <application>PL/pgSQL</application> function is declared
440 with output parameters, the output parameters are given
441 <literal>$<replaceable>n</replaceable></literal> names and optional
442 aliases in just the same way as the normal input parameters. An
443 output parameter is effectively a variable that starts out NULL;
444 it should be assigned to during the execution of the function.
445 The final value of the parameter is what is returned. For instance,
446 the sales-tax example could also be done this way:
449 CREATE FUNCTION sales_tax(subtotal real, OUT tax real) AS $$
451 tax := subtotal * 0.06;
456 Notice that we omitted <literal>RETURNS real</> — we could have
457 included it, but it would be redundant.
461 Output parameters are most useful when returning multiple values.
462 A trivial example is:
465 CREATE FUNCTION sum_n_product(x int, y int, OUT sum int, OUT prod int) AS $$
473 As discussed in <xref linkend="xfunc-output-parameters">, this
474 effectively creates an anonymous record type for the function's
475 results. If a <literal>RETURNS</> clause is given, it must say
476 <literal>RETURNS record</>.
480 Another way to declare a <application>PL/pgSQL</application> function
481 is with <literal>RETURNS TABLE</>, for example:
484 CREATE FUNCTION extended_sales(p_itemno int)
485 RETURNS TABLE(quantity int, total numeric) AS $$
487 RETURN QUERY SELECT quantity, quantity * price FROM sales
488 WHERE itemno = p_itemno;
493 This is exactly equivalent to declaring one or more <literal>OUT</>
494 parameters and specifying <literal>RETURNS SETOF
495 <replaceable>sometype</></literal>.
499 When the return type of a <application>PL/pgSQL</application>
500 function is declared as a polymorphic type (<type>anyelement</type>,
501 <type>anyarray</type>, <type>anynonarray</type>, or <type>anyenum</>),
502 a special parameter <literal>$0</literal>
503 is created. Its data type is the actual return type of the function,
504 as deduced from the actual input types (see <xref
505 linkend="extend-types-polymorphic">).
506 This allows the function to access its actual return type
507 as shown in <xref linkend="plpgsql-declaration-type">.
508 <literal>$0</literal> is initialized to null and can be modified by
509 the function, so it can be used to hold the return value if desired,
510 though that is not required. <literal>$0</literal> can also be
511 given an alias. For example, this function works on any data type
512 that has a <literal>+</> operator:
515 CREATE FUNCTION add_three_values(v1 anyelement, v2 anyelement, v3 anyelement)
516 RETURNS anyelement AS $$
520 result := v1 + v2 + v3;
528 The same effect can be had by declaring one or more output parameters as
529 polymorphic types. In this case the
530 special <literal>$0</literal> parameter is not used; the output
531 parameters themselves serve the same purpose. For example:
534 CREATE FUNCTION add_three_values(v1 anyelement, v2 anyelement, v3 anyelement,
545 <sect2 id="plpgsql-declaration-alias">
546 <title><literal>ALIAS</></title>
549 <replaceable>newname</> ALIAS FOR <replaceable>oldname</>;
553 The <literal>ALIAS</> syntax is more general than is suggested in the
554 previous section: you can declare an alias for any variable, not just
555 function parameters. The main practical use for this is to assign
556 a different name for variables with predetermined names, such as
557 <varname>NEW</varname> or <varname>OLD</varname> within
566 updated ALIAS FOR new;
571 Since <literal>ALIAS</> creates two different ways to name the same
572 object, unrestricted use can be confusing. It's best to use it only
573 for the purpose of overriding predetermined names.
577 <sect2 id="plpgsql-declaration-type">
578 <title>Copying Types</title>
581 <replaceable>variable</replaceable>%TYPE
585 <literal>%TYPE</literal> provides the data type of a variable or
586 table column. You can use this to declare variables that will hold
587 database values. For example, let's say you have a column named
588 <literal>user_id</literal> in your <literal>users</literal>
589 table. To declare a variable with the same data type as
590 <literal>users.user_id</> you write:
592 user_id users.user_id%TYPE;
597 By using <literal>%TYPE</literal> you don't need to know the data
598 type of the structure you are referencing, and most importantly,
599 if the data type of the referenced item changes in the future (for
600 instance: you change the type of <literal>user_id</>
601 from <type>integer</type> to <type>real</type>), you might not need
602 to change your function definition.
606 <literal>%TYPE</literal> is particularly valuable in polymorphic
607 functions, since the data types needed for internal variables can
608 change from one call to the next. Appropriate variables can be
609 created by applying <literal>%TYPE</literal> to the function's
610 arguments or result placeholders.
615 <sect2 id="plpgsql-declaration-rowtypes">
616 <title>Row Types</title>
619 <replaceable>name</replaceable> <replaceable>table_name</replaceable><literal>%ROWTYPE</literal>;
620 <replaceable>name</replaceable> <replaceable>composite_type_name</replaceable>;
624 A variable of a composite type is called a <firstterm>row</>
625 variable (or <firstterm>row-type</> variable). Such a variable
626 can hold a whole row of a <command>SELECT</> or <command>FOR</>
627 query result, so long as that query's column set matches the
628 declared type of the variable.
629 The individual fields of the row value
630 are accessed using the usual dot notation, for example
631 <literal>rowvar.field</literal>.
635 A row variable can be declared to have the same type as the rows of
636 an existing table or view, by using the
637 <replaceable>table_name</replaceable><literal>%ROWTYPE</literal>
638 notation; or it can be declared by giving a composite type's name.
639 (Since every table has an associated composite type of the same name,
640 it actually does not matter in <productname>PostgreSQL</> whether you
641 write <literal>%ROWTYPE</literal> or not. But the form with
642 <literal>%ROWTYPE</literal> is more portable.)
646 Parameters to a function can be
647 composite types (complete table rows). In that case, the
648 corresponding identifier <literal>$<replaceable>n</replaceable></> will be a row variable, and fields can
649 be selected from it, for example <literal>$1.user_id</literal>.
653 Only the user-defined columns of a table row are accessible in a
654 row-type variable, not the OID or other system columns (because the
655 row could be from a view). The fields of the row type inherit the
656 table's field size or precision for data types such as
657 <type>char(<replaceable>n</>)</type>.
661 Here is an example of using composite types. <structname>table1</>
662 and <structname>table2</> are existing tables having at least the
666 CREATE FUNCTION merge_fields(t_row table1) RETURNS text AS $$
668 t2_row table2%ROWTYPE;
670 SELECT * INTO t2_row FROM table2 WHERE ... ;
671 RETURN t_row.f1 || t2_row.f3 || t_row.f5 || t2_row.f7;
675 SELECT merge_fields(t.*) FROM table1 t WHERE ... ;
680 <sect2 id="plpgsql-declaration-records">
681 <title>Record Types</title>
684 <replaceable>name</replaceable> RECORD;
688 Record variables are similar to row-type variables, but they have no
689 predefined structure. They take on the actual row structure of the
690 row they are assigned during a <command>SELECT</> or <command>FOR</> command. The substructure
691 of a record variable can change each time it is assigned to.
692 A consequence of this is that until a record variable is first assigned
693 to, it has no substructure, and any attempt to access a
694 field in it will draw a run-time error.
698 Note that <literal>RECORD</> is not a true data type, only a placeholder.
699 One should also realize that when a <application>PL/pgSQL</application>
700 function is declared to return type <type>record</>, this is not quite the
701 same concept as a record variable, even though such a function might
702 use a record variable to hold its result. In both cases the actual row
703 structure is unknown when the function is written, but for a function
704 returning <type>record</> the actual structure is determined when the
705 calling query is parsed, whereas a record variable can change its row
706 structure on-the-fly.
711 <sect1 id="plpgsql-expressions">
712 <title>Expressions</title>
715 All expressions used in <application>PL/pgSQL</application>
716 statements are processed using the server's main
717 <acronym>SQL</acronym> executor. For example, when you write
718 a <application>PL/pgSQL</application> statement like
720 IF <replaceable>expression</replaceable> THEN ...
722 <application>PL/pgSQL</application> will evaluate the expression by
725 SELECT <replaceable>expression</replaceable>
727 to the main SQL engine. While forming the <command>SELECT</> command,
728 any occurrences of <application>PL/pgSQL</application> variable names
729 are replaced by parameters, as discussed in detail in
730 <xref linkend="plpgsql-var-subst">.
731 This allows the query plan for the <command>SELECT</command> to
732 be prepared just once and then reused for subsequent
733 evaluations with different values of the variables. Thus, what
734 really happens on first use of an expression is essentially a
735 <command>PREPARE</> command. For example, if we have declared
736 two integer variables <literal>x</> and <literal>y</>, and we write
740 what happens behind the scenes is equivalent to
742 PREPARE <replaceable>statement_name</>(integer, integer) AS SELECT $1 < $2;
744 and then this prepared statement is <command>EXECUTE</>d for each
745 execution of the <command>IF</> statement, with the current values
746 of the <application>PL/pgSQL</application> variables supplied as
748 The query plan prepared in this way is saved for the life of the database
749 connection, as described in
750 <xref linkend="plpgsql-plan-caching">. Normally these details are
751 not important to a <application>PL/pgSQL</application> user, but
752 they are useful to know when trying to diagnose a problem.
756 <sect1 id="plpgsql-statements">
757 <title>Basic Statements</title>
760 In this section and the following ones, we describe all the statement
761 types that are explicitly understood by
762 <application>PL/pgSQL</application>.
763 Anything not recognized as one of these statement types is presumed
764 to be an SQL command and is sent to the main database engine to execute,
765 as described in <xref linkend="plpgsql-statements-sql-noresult">
766 and <xref linkend="plpgsql-statements-sql-onerow">.
769 <sect2 id="plpgsql-statements-assignment">
770 <title>Assignment</title>
773 An assignment of a value to a <application>PL/pgSQL</application>
774 variable is written as:
776 <replaceable>variable</replaceable> := <replaceable>expression</replaceable>;
778 As explained previously, the expression in such a statement is evaluated
779 by means of an SQL <command>SELECT</> command sent to the main
780 database engine. The expression must yield a single value (possibly
781 a row value, if the variable is a row or record variable). The target
782 variable can be a simple variable (optionally qualified with a block
783 name), a field of a row or record variable, or an element of an array
784 that is a simple variable or field.
788 If the expression's result data type doesn't match the variable's
789 data type, or the variable has a specific size/precision
790 (like <type>char(20)</type>), the result value will be implicitly
791 converted by the <application>PL/pgSQL</application> interpreter using
792 the result type's output-function and
793 the variable type's input-function. Note that this could potentially
794 result in run-time errors generated by the input function, if the
795 string form of the result value is not acceptable to the input function.
801 tax := subtotal * 0.06;
802 my_record.user_id := 20;
807 <sect2 id="plpgsql-statements-sql-noresult">
808 <title>Executing a Command With No Result</title>
811 For any SQL command that does not return rows, for example
812 <command>INSERT</> without a <literal>RETURNING</> clause, you can
813 execute the command within a <application>PL/pgSQL</application> function
814 just by writing the command.
818 Any <application>PL/pgSQL</application> variable name appearing
819 in the command text is treated as a parameter, and then the
820 current value of the variable is provided as the parameter value
821 at run time. This is exactly like the processing described earlier
822 for expressions; for details see <xref linkend="plpgsql-var-subst">.
826 When executing a SQL command in this way,
827 <application>PL/pgSQL</application> plans the command just once
828 and re-uses the plan on subsequent executions, for the life of
829 the database connection. The implications of this are discussed
830 in detail in <xref linkend="plpgsql-plan-caching">.
834 Sometimes it is useful to evaluate an expression or <command>SELECT</>
835 query but discard the result, for example when calling a function
836 that has side-effects but no useful result value. To do
837 this in <application>PL/pgSQL</application>, use the
838 <command>PERFORM</command> statement:
841 PERFORM <replaceable>query</replaceable>;
844 This executes <replaceable>query</replaceable> and discards the
845 result. Write the <replaceable>query</replaceable> the same
846 way you would write an SQL <command>SELECT</> command, but replace the
847 initial keyword <command>SELECT</> with <command>PERFORM</command>.
848 <application>PL/pgSQL</application> variables will be
849 substituted into the query just as for commands that return no result,
850 and the plan is cached in the same way. Also, the special variable
851 <literal>FOUND</literal> is set to true if the query produced at
852 least one row, or false if it produced no rows (see
853 <xref linkend="plpgsql-statements-diagnostics">).
858 One might expect that writing <command>SELECT</command> directly
859 would accomplish this result, but at
860 present the only accepted way to do it is
861 <command>PERFORM</command>. A SQL command that can return rows,
862 such as <command>SELECT</command>, will be rejected as an error
863 unless it has an <literal>INTO</> clause as discussed in the
871 PERFORM create_mv('cs_session_page_requests_mv', my_query);
876 <sect2 id="plpgsql-statements-sql-onerow">
877 <title>Executing a Query with a Single-Row Result</title>
879 <indexterm zone="plpgsql-statements-sql-onerow">
880 <primary>SELECT INTO</primary>
881 <secondary>in PL/pgSQL</secondary>
884 <indexterm zone="plpgsql-statements-sql-onerow">
885 <primary>RETURNING INTO</primary>
886 <secondary>in PL/pgSQL</secondary>
890 The result of a SQL command yielding a single row (possibly of multiple
891 columns) can be assigned to a record variable, row-type variable, or list
892 of scalar variables. This is done by writing the base SQL command and
893 adding an <literal>INTO</> clause. For example,
896 SELECT <replaceable>select_expressions</replaceable> INTO <optional>STRICT</optional> <replaceable>target</replaceable> FROM ...;
897 INSERT ... RETURNING <replaceable>expressions</replaceable> INTO <optional>STRICT</optional> <replaceable>target</replaceable>;
898 UPDATE ... RETURNING <replaceable>expressions</replaceable> INTO <optional>STRICT</optional> <replaceable>target</replaceable>;
899 DELETE ... RETURNING <replaceable>expressions</replaceable> INTO <optional>STRICT</optional> <replaceable>target</replaceable>;
902 where <replaceable>target</replaceable> can be a record variable, a row
903 variable, or a comma-separated list of simple variables and
905 <application>PL/pgSQL</application> variables will be
906 substituted into the rest of the query, and the plan is cached,
907 just as described above for commands that do not return rows.
908 This works for <command>SELECT</>,
909 <command>INSERT</>/<command>UPDATE</>/<command>DELETE</> with
910 <literal>RETURNING</>, and utility commands that return row-set
911 results (such as <command>EXPLAIN</>).
912 Except for the <literal>INTO</> clause, the SQL command is the same
913 as it would be written outside <application>PL/pgSQL</application>.
918 Note that this interpretation of <command>SELECT</> with <literal>INTO</>
919 is quite different from <productname>PostgreSQL</>'s regular
920 <command>SELECT INTO</command> command, wherein the <literal>INTO</>
921 target is a newly created table. If you want to create a table from a
922 <command>SELECT</> result inside a
923 <application>PL/pgSQL</application> function, use the syntax
924 <command>CREATE TABLE ... AS SELECT</command>.
929 If a row or a variable list is used as target, the query's result columns
930 must exactly match the structure of the target as to number and data
931 types, or else a run-time error
932 occurs. When a record variable is the target, it automatically
933 configures itself to the row type of the query result columns.
937 The <literal>INTO</> clause can appear almost anywhere in the SQL
938 command. Customarily it is written either just before or just after
939 the list of <replaceable>select_expressions</replaceable> in a
940 <command>SELECT</> command, or at the end of the command for other
941 command types. It is recommended that you follow this convention
942 in case the <application>PL/pgSQL</application> parser becomes
943 stricter in future versions.
947 If <literal>STRICT</literal> is not specified in the <literal>INTO</>
948 clause, then <replaceable>target</replaceable> will be set to the first
949 row returned by the query, or to nulls if the query returned no rows.
950 (Note that <quote>the first row</> is not
951 well-defined unless you've used <literal>ORDER BY</>.) Any result rows
952 after the first row are discarded.
953 You can check the special <literal>FOUND</literal> variable (see
954 <xref linkend="plpgsql-statements-diagnostics">) to
955 determine whether a row was returned:
958 SELECT * INTO myrec FROM emp WHERE empname = myname;
960 RAISE EXCEPTION 'employee % not found', myname;
964 If the <literal>STRICT</literal> option is specified, the query must
965 return exactly one row or a run-time error will be reported, either
966 <literal>NO_DATA_FOUND</> (no rows) or <literal>TOO_MANY_ROWS</>
967 (more than one row). You can use an exception block if you wish
968 to catch the error, for example:
972 SELECT * INTO STRICT myrec FROM emp WHERE empname = myname;
974 WHEN NO_DATA_FOUND THEN
975 RAISE EXCEPTION 'employee % not found', myname;
976 WHEN TOO_MANY_ROWS THEN
977 RAISE EXCEPTION 'employee % not unique', myname;
980 Successful execution of a command with <literal>STRICT</>
981 always sets <literal>FOUND</literal> to true.
985 For <command>INSERT</>/<command>UPDATE</>/<command>DELETE</> with
986 <literal>RETURNING</>, <application>PL/pgSQL</application> reports
987 an error for more than one returned row, even when
988 <literal>STRICT</literal> is not specified. This is because there
989 is no option such as <literal>ORDER BY</> with which to determine
990 which affected row should be returned.
995 The <literal>STRICT</> option matches the behavior of
996 Oracle PL/SQL's <command>SELECT INTO</command> and related statements.
1001 To handle cases where you need to process multiple result rows
1002 from a SQL query, see <xref linkend="plpgsql-records-iterating">.
1007 <sect2 id="plpgsql-statements-executing-dyn">
1008 <title>Executing Dynamic Commands</title>
1011 Oftentimes you will want to generate dynamic commands inside your
1012 <application>PL/pgSQL</application> functions, that is, commands
1013 that will involve different tables or different data types each
1014 time they are executed. <application>PL/pgSQL</application>'s
1015 normal attempts to cache plans for commands (as discussed in
1016 <xref linkend="plpgsql-plan-caching">) will not work in such
1017 scenarios. To handle this sort of problem, the
1018 <command>EXECUTE</command> statement is provided:
1021 EXECUTE <replaceable class="command">command-string</replaceable> <optional> INTO <optional>STRICT</optional> <replaceable>target</replaceable> </optional> <optional> USING <replaceable>expression</replaceable> <optional>, ... </optional> </optional>;
1024 where <replaceable>command-string</replaceable> is an expression
1025 yielding a string (of type <type>text</type>) containing the
1026 command to be executed. The optional <replaceable>target</replaceable>
1027 is a record variable, a row variable, or a comma-separated list of
1028 simple variables and record/row fields, into which the results of
1029 the command will be stored. The optional <literal>USING</> expressions
1030 supply values to be inserted into the command.
1034 No substitution of <application>PL/pgSQL</> variables is done on the
1035 computed command string. Any required variable values must be inserted
1036 in the command string as it is constructed; or you can use parameters
1041 Also, there is no plan caching for commands executed via
1042 <command>EXECUTE</command>. Instead, the
1043 command is prepared each time the statement is run. Thus the command
1044 string can be dynamically created within the function to perform
1045 actions on different tables and columns.
1049 The <literal>INTO</literal> clause specifies where the results of
1050 a SQL command returning rows should be assigned. If a row
1051 or variable list is provided, it must exactly match the structure
1052 of the query's results (when a
1053 record variable is used, it will configure itself to match the
1054 result structure automatically). If multiple rows are returned,
1055 only the first will be assigned to the <literal>INTO</literal>
1056 variable. If no rows are returned, NULL is assigned to the
1057 <literal>INTO</literal> variable(s). If no <literal>INTO</literal>
1058 clause is specified, the query results are discarded.
1062 If the <literal>STRICT</> option is given, an error is reported
1063 unless the query produces exactly one row.
1067 The command string can use parameter values, which are referenced
1068 in the command as <literal>$1</>, <literal>$2</>, etc.
1069 These symbols refer to values supplied in the <literal>USING</>
1070 clause. This method is often preferable to inserting data values
1071 into the command string as text: it avoids run-time overhead of
1072 converting the values to text and back, and it is much less prone
1073 to SQL-injection attacks since there is no need for quoting or escaping.
1076 EXECUTE 'SELECT count(*) FROM mytable WHERE inserted_by = $1 AND inserted <= $2'
1078 USING checked_user, checked_date;
1083 Note that parameter symbols can only be used for data values
1084 — if you want to use dynamically determined table or column
1085 names, you must insert them into the command string textually.
1086 For example, if the preceding query needed to be done against a
1087 dynamically selected table, you could do this:
1089 EXECUTE 'SELECT count(*) FROM '
1090 || tabname::regclass
1091 || ' WHERE inserted_by = $1 AND inserted <= $2'
1093 USING checked_user, checked_date;
1095 Another restriction on parameter symbols is that they only work in
1096 <command>SELECT</>, <command>INSERT</>, <command>UPDATE</>, and
1097 <command>DELETE</> commands. In other statement
1098 types (generically called utility statements), you must insert
1099 values textually even if they are just data values.
1103 An <command>EXECUTE</> with a simple constant command string and some
1104 <literal>USING</> parameters, as in the first example above, is
1105 functionally equivalent to just writing the command directly in
1106 <application>PL/pgSQL</application> and allowing replacement of
1107 <application>PL/pgSQL</application> variables to happen automatically.
1108 The important difference is that <command>EXECUTE</> will re-plan
1109 the command on each execution, generating a plan that is specific
1110 to the current parameter values; whereas
1111 <application>PL/pgSQL</application> normally creates a generic plan
1112 and caches it for re-use. In situations where the best plan depends
1113 strongly on the parameter values, <command>EXECUTE</> can be
1114 significantly faster; while when the plan is not sensitive to parameter
1115 values, re-planning will be a waste.
1119 <command>SELECT INTO</command> is not currently supported within
1120 <command>EXECUTE</command>; instead, execute a plain <command>SELECT</>
1121 command and specify <literal>INTO</> as part of the <command>EXECUTE</>
1127 The <application>PL/pgSQL</application>
1128 <command>EXECUTE</command> statement is not related to the
1129 <xref linkend="sql-execute"> SQL
1130 statement supported by the
1131 <productname>PostgreSQL</productname> server. The server's
1132 <command>EXECUTE</command> statement cannot be used directly within
1133 <application>PL/pgSQL</> functions (and is not needed).
1137 <example id="plpgsql-quote-literal-example">
1138 <title>Quoting values in dynamic queries</title>
1141 <primary>quote_ident</primary>
1142 <secondary>use in PL/pgSQL</secondary>
1146 <primary>quote_literal</primary>
1147 <secondary>use in PL/pgSQL</secondary>
1151 <primary>quote_nullable</primary>
1152 <secondary>use in PL/pgSQL</secondary>
1156 <primary>format</primary>
1157 <secondary>use in PL/pgSQL</secondary>
1161 When working with dynamic commands you will often have to handle escaping
1162 of single quotes. The recommended method for quoting fixed text in your
1163 function body is dollar quoting. (If you have legacy code that does
1164 not use dollar quoting, please refer to the
1165 overview in <xref linkend="plpgsql-quote-tips">, which can save you
1166 some effort when translating said code to a more reasonable scheme.)
1170 Dynamic values that are to be inserted into the constructed
1171 query require careful handling since they might themselves contain
1173 An example (this assumes that you are using dollar quoting for the
1174 function as a whole, so the quote marks need not be doubled):
1176 EXECUTE 'UPDATE tbl SET '
1177 || quote_ident(colname)
1179 || quote_literal(newvalue)
1181 || quote_literal(keyvalue);
1186 This example demonstrates the use of the
1187 <function>quote_ident</function> and
1188 <function>quote_literal</function> functions (see <xref
1189 linkend="functions-string">). For safety, expressions containing column
1190 or table identifiers should be passed through
1191 <function>quote_ident</function> before insertion in a dynamic query.
1192 Expressions containing values that should be literal strings in the
1193 constructed command should be passed through <function>quote_literal</>.
1194 These functions take the appropriate steps to return the input text
1195 enclosed in double or single quotes respectively, with any embedded
1196 special characters properly escaped.
1200 Because <function>quote_literal</function> is labelled
1201 <literal>STRICT</literal>, it will always return null when called with a
1202 null argument. In the above example, if <literal>newvalue</> or
1203 <literal>keyvalue</> were null, the entire dynamic query string would
1204 become null, leading to an error from <command>EXECUTE</command>.
1205 You can avoid this problem by using the <function>quote_nullable</>
1206 function, which works the same as <function>quote_literal</> except that
1207 when called with a null argument it returns the string <literal>NULL</>.
1210 EXECUTE 'UPDATE tbl SET '
1211 || quote_ident(colname)
1213 || quote_nullable(newvalue)
1215 || quote_nullable(keyvalue);
1217 If you are dealing with values that might be null, you should usually
1218 use <function>quote_nullable</> in place of <function>quote_literal</>.
1222 As always, care must be taken to ensure that null values in a query do
1223 not deliver unintended results. For example the <literal>WHERE</> clause
1225 'WHERE key = ' || quote_nullable(keyvalue)
1227 will never succeed if <literal>keyvalue</> is null, because the
1228 result of using the equality operator <literal>=</> with a null operand
1229 is always null. If you wish null to work like an ordinary key value,
1230 you would need to rewrite the above as
1232 'WHERE key IS NOT DISTINCT FROM ' || quote_nullable(keyvalue)
1234 (At present, <literal>IS NOT DISTINCT FROM</> is handled much less
1235 efficiently than <literal>=</>, so don't do this unless you must.
1236 See <xref linkend="functions-comparison"> for
1237 more information on nulls and <literal>IS DISTINCT</>.)
1241 Note that dollar quoting is only useful for quoting fixed text.
1242 It would be a very bad idea to try to write this example as:
1244 EXECUTE 'UPDATE tbl SET '
1245 || quote_ident(colname)
1248 || '$$ WHERE key = '
1249 || quote_literal(keyvalue);
1251 because it would break if the contents of <literal>newvalue</>
1252 happened to contain <literal>$$</>. The same objection would
1253 apply to any other dollar-quoting delimiter you might pick.
1254 So, to safely quote text that is not known in advance, you
1255 <emphasis>must</> use <function>quote_literal</>,
1256 <function>quote_nullable</>, or <function>quote_ident</>, as appropriate.
1260 Dynamic SQL statements can also be safely constructed using the
1261 <function>format</function> function (see <xref
1262 linkend="functions-string">). For example:
1264 EXECUTE format('UPDATE tbl SET %I = %L WHERE key = %L', colname, newvalue, keyvalue);
1266 The <function>format</function> function can be used in conjunction with
1267 the <literal>USING</literal> clause:
1269 EXECUTE format('UPDATE tbl SET %I = $1 WHERE key = $2', colname)
1270 USING newvalue, keyvalue;
1272 This form is more efficient, because the parameters
1273 <literal>newvalue</literal> and <literal>keyvalue</literal> are not
1279 A much larger example of a dynamic command and
1280 <command>EXECUTE</command> can be seen in <xref
1281 linkend="plpgsql-porting-ex2">, which builds and executes a
1282 <command>CREATE FUNCTION</> command to define a new function.
1286 <sect2 id="plpgsql-statements-diagnostics">
1287 <title>Obtaining the Result Status</title>
1290 There are several ways to determine the effect of a command. The
1291 first method is to use the <command>GET DIAGNOSTICS</command>
1292 command, which has the form:
1295 GET DIAGNOSTICS <replaceable>variable</replaceable> = <replaceable>item</replaceable> <optional> , ... </optional>;
1298 This command allows retrieval of system status indicators. Each
1299 <replaceable>item</replaceable> is a key word identifying a state
1300 value to be assigned to the specified variable (which should be
1301 of the right data type to receive it). The currently available
1302 status items are <varname>ROW_COUNT</>, the number of rows
1303 processed by the last <acronym>SQL</acronym> command sent to
1304 the <acronym>SQL</acronym> engine, and <varname>RESULT_OID</>,
1305 the OID of the last row inserted by the most recent
1306 <acronym>SQL</acronym> command. Note that <varname>RESULT_OID</>
1307 is only useful after an <command>INSERT</command> command into a
1308 table containing OIDs.
1314 GET DIAGNOSTICS integer_var = ROW_COUNT;
1319 The second method to determine the effects of a command is to check the
1320 special variable named <literal>FOUND</literal>, which is of
1321 type <type>boolean</type>. <literal>FOUND</literal> starts out
1322 false within each <application>PL/pgSQL</application> function call.
1323 It is set by each of the following types of statements:
1328 A <command>SELECT INTO</command> statement sets
1329 <literal>FOUND</literal> true if a row is assigned, false if no
1335 A <command>PERFORM</> statement sets <literal>FOUND</literal>
1336 true if it produces (and discards) one or more rows, false if
1342 <command>UPDATE</>, <command>INSERT</>, and <command>DELETE</>
1343 statements set <literal>FOUND</literal> true if at least one
1344 row is affected, false if no row is affected.
1349 A <command>FETCH</> statement sets <literal>FOUND</literal>
1350 true if it returns a row, false if no row is returned.
1355 A <command>MOVE</> statement sets <literal>FOUND</literal>
1356 true if it successfully repositions the cursor, false otherwise.
1362 A <command>FOR</> statement sets <literal>FOUND</literal> true
1363 if it iterates one or more times, else false. This applies to
1364 all four variants of the <command>FOR</> statement (integer
1365 <command>FOR</> loops, record-set <command>FOR</> loops,
1366 dynamic record-set <command>FOR</> loops, and cursor
1367 <command>FOR</> loops).
1368 <literal>FOUND</literal> is set this way when the
1369 <command>FOR</> loop exits; inside the execution of the loop,
1370 <literal>FOUND</literal> is not modified by the
1371 <command>FOR</> statement, although it might be changed by the
1372 execution of other statements within the loop body.
1377 <command>RETURN QUERY</command> and <command>RETURN QUERY
1378 EXECUTE</command> statements set <literal>FOUND</literal>
1379 true if the query returns at least one row, false if no row
1385 Other <application>PL/pgSQL</application> statements do not change
1386 the state of <literal>FOUND</literal>.
1387 Note in particular that <command>EXECUTE</command>
1388 changes the output of <command>GET DIAGNOSTICS</command>, but
1389 does not change <literal>FOUND</literal>.
1393 <literal>FOUND</literal> is a local variable within each
1394 <application>PL/pgSQL</application> function; any changes to it
1395 affect only the current function.
1400 <sect2 id="plpgsql-statements-null">
1401 <title>Doing Nothing At All</title>
1404 Sometimes a placeholder statement that does nothing is useful.
1405 For example, it can indicate that one arm of an if/then/else
1406 chain is deliberately empty. For this purpose, use the
1407 <command>NULL</command> statement:
1415 For example, the following two fragments of code are equivalent:
1420 WHEN division_by_zero THEN
1421 NULL; -- ignore the error
1429 WHEN division_by_zero THEN -- ignore the error
1432 Which is preferable is a matter of taste.
1437 In Oracle's PL/SQL, empty statement lists are not allowed, and so
1438 <command>NULL</> statements are <emphasis>required</> for situations
1439 such as this. <application>PL/pgSQL</application> allows you to
1440 just write nothing, instead.
1447 <sect1 id="plpgsql-control-structures">
1448 <title>Control Structures</title>
1451 Control structures are probably the most useful (and
1452 important) part of <application>PL/pgSQL</>. With
1453 <application>PL/pgSQL</>'s control structures,
1454 you can manipulate <productname>PostgreSQL</> data in a very
1455 flexible and powerful way.
1458 <sect2 id="plpgsql-statements-returning">
1459 <title>Returning From a Function</title>
1462 There are two commands available that allow you to return data
1463 from a function: <command>RETURN</command> and <command>RETURN
1468 <title><command>RETURN</></title>
1471 RETURN <replaceable>expression</replaceable>;
1475 <command>RETURN</command> with an expression terminates the
1476 function and returns the value of
1477 <replaceable>expression</replaceable> to the caller. This form
1478 is used for <application>PL/pgSQL</> functions that do
1483 When returning a scalar type, any expression can be used. The
1484 expression's result will be automatically cast into the
1485 function's return type as described for assignments. To return a
1486 composite (row) value, you must write a record or row variable
1487 as the <replaceable>expression</replaceable>.
1491 If you declared the function with output parameters, write just
1492 <command>RETURN</command> with no expression. The current values
1493 of the output parameter variables will be returned.
1497 If you declared the function to return <type>void</type>, a
1498 <command>RETURN</command> statement can be used to exit the function
1499 early; but do not write an expression following
1500 <command>RETURN</command>.
1504 The return value of a function cannot be left undefined. If
1505 control reaches the end of the top-level block of the function
1506 without hitting a <command>RETURN</command> statement, a run-time
1507 error will occur. This restriction does not apply to functions
1508 with output parameters and functions returning <type>void</type>,
1509 however. In those cases a <command>RETURN</command> statement is
1510 automatically executed if the top-level block finishes.
1515 <title><command>RETURN NEXT</> and <command>RETURN QUERY</command></title>
1517 <primary>RETURN NEXT</primary>
1518 <secondary>in PL/pgSQL</secondary>
1521 <primary>RETURN QUERY</primary>
1522 <secondary>in PL/pgSQL</secondary>
1526 RETURN NEXT <replaceable>expression</replaceable>;
1527 RETURN QUERY <replaceable>query</replaceable>;
1528 RETURN QUERY EXECUTE <replaceable class="command">command-string</replaceable> <optional> USING <replaceable>expression</replaceable> <optional>, ... </optional> </optional>;
1532 When a <application>PL/pgSQL</> function is declared to return
1533 <literal>SETOF <replaceable>sometype</></literal>, the procedure
1534 to follow is slightly different. In that case, the individual
1535 items to return are specified by a sequence of <command>RETURN
1536 NEXT</command> or <command>RETURN QUERY</command> commands, and
1537 then a final <command>RETURN</command> command with no argument
1538 is used to indicate that the function has finished executing.
1539 <command>RETURN NEXT</command> can be used with both scalar and
1540 composite data types; with a composite result type, an entire
1541 <quote>table</quote> of results will be returned.
1542 <command>RETURN QUERY</command> appends the results of executing
1543 a query to the function's result set. <command>RETURN
1544 NEXT</command> and <command>RETURN QUERY</command> can be freely
1545 intermixed in a single set-returning function, in which case
1546 their results will be concatenated.
1550 <command>RETURN NEXT</command> and <command>RETURN
1551 QUERY</command> do not actually return from the function —
1552 they simply append zero or more rows to the function's result
1553 set. Execution then continues with the next statement in the
1554 <application>PL/pgSQL</> function. As successive
1555 <command>RETURN NEXT</command> or <command>RETURN
1556 QUERY</command> commands are executed, the result set is built
1557 up. A final <command>RETURN</command>, which should have no
1558 argument, causes control to exit the function (or you can just
1559 let control reach the end of the function).
1563 <command>RETURN QUERY</command> has a variant
1564 <command>RETURN QUERY EXECUTE</command>, which specifies the
1565 query to be executed dynamically. Parameter expressions can
1566 be inserted into the computed query string via <literal>USING</>,
1567 in just the same way as in the <command>EXECUTE</> command.
1571 If you declared the function with output parameters, write just
1572 <command>RETURN NEXT</command> with no expression. On each
1573 execution, the current values of the output parameter
1574 variable(s) will be saved for eventual return as a row of the
1575 result. Note that you must declare the function as returning
1576 <literal>SETOF record</literal> when there are multiple output
1577 parameters, or <literal>SETOF <replaceable>sometype</></literal>
1578 when there is just one output parameter of type
1579 <replaceable>sometype</>, in order to create a set-returning
1580 function with output parameters.
1584 Here is an example of a function using <command>RETURN
1588 CREATE TABLE foo (fooid INT, foosubid INT, fooname TEXT);
1589 INSERT INTO foo VALUES (1, 2, 'three');
1590 INSERT INTO foo VALUES (4, 5, 'six');
1592 CREATE OR REPLACE FUNCTION getAllFoo() RETURNS SETOF foo AS
1597 FOR r IN SELECT * FROM foo
1600 -- can do some processing here
1601 RETURN NEXT r; -- return current row of SELECT
1606 LANGUAGE 'plpgsql' ;
1608 SELECT * FROM getallfoo();
1614 The current implementation of <command>RETURN NEXT</command>
1615 and <command>RETURN QUERY</command> stores the entire result set
1616 before returning from the function, as discussed above. That
1617 means that if a <application>PL/pgSQL</> function produces a
1618 very large result set, performance might be poor: data will be
1619 written to disk to avoid memory exhaustion, but the function
1620 itself will not return until the entire result set has been
1621 generated. A future version of <application>PL/pgSQL</> might
1622 allow users to define set-returning functions
1623 that do not have this limitation. Currently, the point at
1624 which data begins being written to disk is controlled by the
1625 <xref linkend="guc-work-mem">
1626 configuration variable. Administrators who have sufficient
1627 memory to store larger result sets in memory should consider
1628 increasing this parameter.
1634 <sect2 id="plpgsql-conditionals">
1635 <title>Conditionals</title>
1638 <command>IF</> and <command>CASE</> statements let you execute
1639 alternative commands based on certain conditions.
1640 <application>PL/pgSQL</> has three forms of <command>IF</>:
1643 <para><literal>IF ... THEN</></>
1646 <para><literal>IF ... THEN ... ELSE</></>
1649 <para><literal>IF ... THEN ... ELSIF ... THEN ... ELSE</></>
1653 and two forms of <command>CASE</>:
1656 <para><literal>CASE ... WHEN ... THEN ... ELSE ... END CASE</></>
1659 <para><literal>CASE WHEN ... THEN ... ELSE ... END CASE</></>
1665 <title><literal>IF-THEN</></title>
1668 IF <replaceable>boolean-expression</replaceable> THEN
1669 <replaceable>statements</replaceable>
1674 <literal>IF-THEN</literal> statements are the simplest form of
1675 <literal>IF</literal>. The statements between
1676 <literal>THEN</literal> and <literal>END IF</literal> will be
1677 executed if the condition is true. Otherwise, they are
1684 IF v_user_id <> 0 THEN
1685 UPDATE users SET email = v_email WHERE user_id = v_user_id;
1692 <title><literal>IF-THEN-ELSE</></title>
1695 IF <replaceable>boolean-expression</replaceable> THEN
1696 <replaceable>statements</replaceable>
1698 <replaceable>statements</replaceable>
1703 <literal>IF-THEN-ELSE</literal> statements add to
1704 <literal>IF-THEN</literal> by letting you specify an
1705 alternative set of statements that should be executed if the
1706 condition is not true. (Note this includes the case where the
1707 condition evaluates to NULL.)
1713 IF parentid IS NULL OR parentid = ''
1717 RETURN hp_true_filename(parentid) || '/' || fullname;
1722 IF v_count > 0 THEN
1723 INSERT INTO users_count (count) VALUES (v_count);
1733 <title><literal>IF-THEN-ELSIF</></title>
1736 IF <replaceable>boolean-expression</replaceable> THEN
1737 <replaceable>statements</replaceable>
1738 <optional> ELSIF <replaceable>boolean-expression</replaceable> THEN
1739 <replaceable>statements</replaceable>
1740 <optional> ELSIF <replaceable>boolean-expression</replaceable> THEN
1741 <replaceable>statements</replaceable>
1746 <replaceable>statements</replaceable> </optional>
1751 Sometimes there are more than just two alternatives.
1752 <literal>IF-THEN-ELSIF</> provides a convenient
1753 method of checking several alternatives in turn.
1754 The <literal>IF</> conditions are tested successively
1755 until the first one that is true is found. Then the
1756 associated statement(s) are executed, after which control
1757 passes to the next statement after <literal>END IF</>.
1758 (Any subsequent <literal>IF</> conditions are <emphasis>not</>
1759 tested.) If none of the <literal>IF</> conditions is true,
1760 then the <literal>ELSE</> block (if any) is executed.
1769 ELSIF number > 0 THEN
1770 result := 'positive';
1771 ELSIF number < 0 THEN
1772 result := 'negative';
1774 -- hmm, the only other possibility is that number is null
1781 The key word <literal>ELSIF</> can also be spelled
1786 An alternative way of accomplishing the same task is to nest
1787 <literal>IF-THEN-ELSE</literal> statements, as in the
1791 IF demo_row.sex = 'm' THEN
1792 pretty_sex := 'man';
1794 IF demo_row.sex = 'f' THEN
1795 pretty_sex := 'woman';
1802 However, this method requires writing a matching <literal>END IF</>
1803 for each <literal>IF</>, so it is much more cumbersome than
1804 using <literal>ELSIF</> when there are many alternatives.
1809 <title>Simple <literal>CASE</></title>
1812 CASE <replaceable>search-expression</replaceable>
1813 WHEN <replaceable>expression</replaceable> <optional>, <replaceable>expression</replaceable> <optional> ... </optional></optional> THEN
1814 <replaceable>statements</replaceable>
1815 <optional> WHEN <replaceable>expression</replaceable> <optional>, <replaceable>expression</replaceable> <optional> ... </optional></optional> THEN
1816 <replaceable>statements</replaceable>
1819 <replaceable>statements</replaceable> </optional>
1824 The simple form of <command>CASE</> provides conditional execution
1825 based on equality of operands. The <replaceable>search-expression</>
1826 is evaluated (once) and successively compared to each
1827 <replaceable>expression</> in the <literal>WHEN</> clauses.
1828 If a match is found, then the corresponding
1829 <replaceable>statements</replaceable> are executed, and then control
1830 passes to the next statement after <literal>END CASE</>. (Subsequent
1831 <literal>WHEN</> expressions are not evaluated.) If no match is
1832 found, the <literal>ELSE</> <replaceable>statements</replaceable> are
1833 executed; but if <literal>ELSE</> is not present, then a
1834 <literal>CASE_NOT_FOUND</literal> exception is raised.
1838 Here is a simple example:
1843 msg := 'one or two';
1845 msg := 'other value than one or two';
1852 <title>Searched <literal>CASE</></title>
1856 WHEN <replaceable>boolean-expression</replaceable> THEN
1857 <replaceable>statements</replaceable>
1858 <optional> WHEN <replaceable>boolean-expression</replaceable> THEN
1859 <replaceable>statements</replaceable>
1862 <replaceable>statements</replaceable> </optional>
1867 The searched form of <command>CASE</> provides conditional execution
1868 based on truth of Boolean expressions. Each <literal>WHEN</> clause's
1869 <replaceable>boolean-expression</replaceable> is evaluated in turn,
1870 until one is found that yields <literal>true</>. Then the
1871 corresponding <replaceable>statements</replaceable> are executed, and
1872 then control passes to the next statement after <literal>END CASE</>.
1873 (Subsequent <literal>WHEN</> expressions are not evaluated.)
1874 If no true result is found, the <literal>ELSE</>
1875 <replaceable>statements</replaceable> are executed;
1876 but if <literal>ELSE</> is not present, then a
1877 <literal>CASE_NOT_FOUND</literal> exception is raised.
1885 WHEN x BETWEEN 0 AND 10 THEN
1886 msg := 'value is between zero and ten';
1887 WHEN x BETWEEN 11 AND 20 THEN
1888 msg := 'value is between eleven and twenty';
1894 This form of <command>CASE</> is entirely equivalent to
1895 <literal>IF-THEN-ELSIF</>, except for the rule that reaching
1896 an omitted <literal>ELSE</> clause results in an error rather
1903 <sect2 id="plpgsql-control-structures-loops">
1904 <title>Simple Loops</title>
1906 <indexterm zone="plpgsql-control-structures-loops">
1907 <primary>loop</primary>
1908 <secondary>in PL/pgSQL</secondary>
1912 With the <literal>LOOP</>, <literal>EXIT</>,
1913 <literal>CONTINUE</>, <literal>WHILE</>, and <literal>FOR</>
1914 statements, you can arrange for your <application>PL/pgSQL</>
1915 function to repeat a series of commands.
1919 <title><literal>LOOP</></title>
1922 <optional> <<<replaceable>label</replaceable>>> </optional>
1924 <replaceable>statements</replaceable>
1925 END LOOP <optional> <replaceable>label</replaceable> </optional>;
1929 <literal>LOOP</> defines an unconditional loop that is repeated
1930 indefinitely until terminated by an <literal>EXIT</> or
1931 <command>RETURN</command> statement. The optional
1932 <replaceable>label</replaceable> can be used by <literal>EXIT</>
1933 and <literal>CONTINUE</literal> statements within nested loops to
1934 specify which loop those statements refer to.
1939 <title><literal>EXIT</></title>
1942 <primary>EXIT</primary>
1943 <secondary>in PL/pgSQL</secondary>
1947 EXIT <optional> <replaceable>label</replaceable> </optional> <optional> WHEN <replaceable>boolean-expression</replaceable> </optional>;
1951 If no <replaceable>label</replaceable> is given, the innermost
1952 loop is terminated and the statement following <literal>END
1953 LOOP</> is executed next. If <replaceable>label</replaceable>
1954 is given, it must be the label of the current or some outer
1955 level of nested loop or block. Then the named loop or block is
1956 terminated and control continues with the statement after the
1957 loop's/block's corresponding <literal>END</>.
1961 If <literal>WHEN</> is specified, the loop exit occurs only if
1962 <replaceable>boolean-expression</> is true. Otherwise, control passes
1963 to the statement after <literal>EXIT</>.
1967 <literal>EXIT</> can be used with all types of loops; it is
1968 not limited to use with unconditional loops.
1973 <literal>BEGIN</literal> block, <literal>EXIT</literal> passes
1974 control to the next statement after the end of the block.
1975 Note that a label must be used for this purpose; an unlabelled
1976 <literal>EXIT</literal> is never considered to match a
1977 <literal>BEGIN</literal> block. (This is a change from
1978 pre-8.4 releases of <productname>PostgreSQL</productname>, which
1979 would allow an unlabelled <literal>EXIT</literal> to match
1980 a <literal>BEGIN</literal> block.)
1987 -- some computations
1988 IF count > 0 THEN
1994 -- some computations
1995 EXIT WHEN count > 0; -- same result as previous example
1998 <<ablock>>
2000 -- some computations
2001 IF stocks > 100000 THEN
2002 EXIT ablock; -- causes exit from the BEGIN block
2004 -- computations here will be skipped when stocks > 100000
2011 <title><literal>CONTINUE</></title>
2014 <primary>CONTINUE</primary>
2015 <secondary>in PL/pgSQL</secondary>
2019 CONTINUE <optional> <replaceable>label</replaceable> </optional> <optional> WHEN <replaceable>boolean-expression</replaceable> </optional>;
2023 If no <replaceable>label</> is given, the next iteration of
2024 the innermost loop is begun. That is, all statements remaining
2025 in the loop body are skipped, and control returns
2026 to the loop control expression (if any) to determine whether
2027 another loop iteration is needed.
2028 If <replaceable>label</> is present, it
2029 specifies the label of the loop whose execution will be
2034 If <literal>WHEN</> is specified, the next iteration of the
2035 loop is begun only if <replaceable>boolean-expression</> is
2036 true. Otherwise, control passes to the statement after
2037 <literal>CONTINUE</>.
2041 <literal>CONTINUE</> can be used with all types of loops; it
2042 is not limited to use with unconditional loops.
2049 -- some computations
2050 EXIT WHEN count > 100;
2051 CONTINUE WHEN count < 50;
2052 -- some computations for count IN [50 .. 100]
2060 <title><literal>WHILE</></title>
2063 <primary>WHILE</primary>
2064 <secondary>in PL/pgSQL</secondary>
2068 <optional> <<<replaceable>label</replaceable>>> </optional>
2069 WHILE <replaceable>boolean-expression</replaceable> LOOP
2070 <replaceable>statements</replaceable>
2071 END LOOP <optional> <replaceable>label</replaceable> </optional>;
2075 The <literal>WHILE</> statement repeats a
2076 sequence of statements so long as the
2077 <replaceable>boolean-expression</replaceable>
2078 evaluates to true. The expression is checked just before
2079 each entry to the loop body.
2085 WHILE amount_owed > 0 AND gift_certificate_balance > 0 LOOP
2086 -- some computations here
2090 -- some computations here
2096 <sect3 id="plpgsql-integer-for">
2097 <title><literal>FOR</> (integer variant)</title>
2100 <optional> <<<replaceable>label</replaceable>>> </optional>
2101 FOR <replaceable>name</replaceable> IN <optional> REVERSE </optional> <replaceable>expression</replaceable> .. <replaceable>expression</replaceable> <optional> BY <replaceable>expression</replaceable> </optional> LOOP
2102 <replaceable>statements</replaceable>
2103 END LOOP <optional> <replaceable>label</replaceable> </optional>;
2107 This form of <literal>FOR</> creates a loop that iterates over a range
2108 of integer values. The variable
2109 <replaceable>name</replaceable> is automatically defined as type
2110 <type>integer</> and exists only inside the loop (any existing
2111 definition of the variable name is ignored within the loop).
2112 The two expressions giving
2113 the lower and upper bound of the range are evaluated once when entering
2114 the loop. If the <literal>BY</> clause isn't specified the iteration
2115 step is 1, otherwise it's the value specified in the <literal>BY</>
2116 clause, which again is evaluated once on loop entry.
2117 If <literal>REVERSE</> is specified then the step value is
2118 subtracted, rather than added, after each iteration.
2122 Some examples of integer <literal>FOR</> loops:
2125 -- i will take on the values 1,2,3,4,5,6,7,8,9,10 within the loop
2128 FOR i IN REVERSE 10..1 LOOP
2129 -- i will take on the values 10,9,8,7,6,5,4,3,2,1 within the loop
2132 FOR i IN REVERSE 10..1 BY 2 LOOP
2133 -- i will take on the values 10,8,6,4,2 within the loop
2139 If the lower bound is greater than the upper bound (or less than,
2140 in the <literal>REVERSE</> case), the loop body is not
2141 executed at all. No error is raised.
2145 If a <replaceable>label</replaceable> is attached to the
2146 <literal>FOR</> loop then the integer loop variable can be
2147 referenced with a qualified name, using that
2148 <replaceable>label</replaceable>.
2153 <sect2 id="plpgsql-records-iterating">
2154 <title>Looping Through Query Results</title>
2157 Using a different type of <literal>FOR</> loop, you can iterate through
2158 the results of a query and manipulate that data
2159 accordingly. The syntax is:
2161 <optional> <<<replaceable>label</replaceable>>> </optional>
2162 FOR <replaceable>target</replaceable> IN <replaceable>query</replaceable> LOOP
2163 <replaceable>statements</replaceable>
2164 END LOOP <optional> <replaceable>label</replaceable> </optional>;
2166 The <replaceable>target</replaceable> is a record variable, row variable,
2167 or comma-separated list of scalar variables.
2168 The <replaceable>target</replaceable> is successively assigned each row
2169 resulting from the <replaceable>query</replaceable> and the loop body is
2170 executed for each row. Here is an example:
2172 CREATE FUNCTION cs_refresh_mviews() RETURNS integer AS $$
2176 PERFORM cs_log('Refreshing materialized views...');
2178 FOR mviews IN SELECT * FROM cs_materialized_views ORDER BY sort_key LOOP
2180 -- Now "mviews" has one record from cs_materialized_views
2182 PERFORM cs_log('Refreshing materialized view '
2183 || quote_ident(mviews.mv_name) || ' ...');
2184 EXECUTE 'TRUNCATE TABLE ' || quote_ident(mviews.mv_name);
2185 EXECUTE 'INSERT INTO '
2186 || quote_ident(mviews.mv_name) || ' '
2190 PERFORM cs_log('Done refreshing materialized views.');
2193 $$ LANGUAGE plpgsql;
2196 If the loop is terminated by an <literal>EXIT</> statement, the last
2197 assigned row value is still accessible after the loop.
2201 The <replaceable>query</replaceable> used in this type of <literal>FOR</>
2202 statement can be any SQL command that returns rows to the caller:
2203 <command>SELECT</> is the most common case,
2204 but you can also use <command>INSERT</>, <command>UPDATE</>, or
2205 <command>DELETE</> with a <literal>RETURNING</> clause. Some utility
2206 commands such as <command>EXPLAIN</> will work too.
2210 <application>PL/pgSQL</> variables are substituted into the query text,
2211 and the query plan is cached for possible re-use, as discussed in
2212 detail in <xref linkend="plpgsql-var-subst"> and
2213 <xref linkend="plpgsql-plan-caching">.
2217 The <literal>FOR-IN-EXECUTE</> statement is another way to iterate over
2220 <optional> <<<replaceable>label</replaceable>>> </optional>
2221 FOR <replaceable>target</replaceable> IN EXECUTE <replaceable>text_expression</replaceable> <optional> USING <replaceable>expression</replaceable> <optional>, ... </optional> </optional> LOOP
2222 <replaceable>statements</replaceable>
2223 END LOOP <optional> <replaceable>label</replaceable> </optional>;
2225 This is like the previous form, except that the source query
2226 is specified as a string expression, which is evaluated and replanned
2227 on each entry to the <literal>FOR</> loop. This allows the programmer to
2228 choose the speed of a preplanned query or the flexibility of a dynamic
2229 query, just as with a plain <command>EXECUTE</command> statement.
2230 As with <command>EXECUTE</command>, parameter values can be inserted
2231 into the dynamic command via <literal>USING</>.
2235 Another way to specify the query whose results should be iterated
2236 through is to declare it as a cursor. This is described in
2237 <xref linkend="plpgsql-cursor-for-loop">.
2241 <sect2 id="plpgsql-error-trapping">
2242 <title>Trapping Errors</title>
2245 <primary>exceptions</primary>
2246 <secondary>in PL/pgSQL</secondary>
2250 By default, any error occurring in a <application>PL/pgSQL</>
2251 function aborts execution of the function, and indeed of the
2252 surrounding transaction as well. You can trap errors and recover
2253 from them by using a <command>BEGIN</> block with an
2254 <literal>EXCEPTION</> clause. The syntax is an extension of the
2255 normal syntax for a <command>BEGIN</> block:
2258 <optional> <<<replaceable>label</replaceable>>> </optional>
2260 <replaceable>declarations</replaceable> </optional>
2262 <replaceable>statements</replaceable>
2264 WHEN <replaceable>condition</replaceable> <optional> OR <replaceable>condition</replaceable> ... </optional> THEN
2265 <replaceable>handler_statements</replaceable>
2266 <optional> WHEN <replaceable>condition</replaceable> <optional> OR <replaceable>condition</replaceable> ... </optional> THEN
2267 <replaceable>handler_statements</replaceable>
2274 If no error occurs, this form of block simply executes all the
2275 <replaceable>statements</replaceable>, and then control passes
2276 to the next statement after <literal>END</>. But if an error
2277 occurs within the <replaceable>statements</replaceable>, further
2278 processing of the <replaceable>statements</replaceable> is
2279 abandoned, and control passes to the <literal>EXCEPTION</> list.
2280 The list is searched for the first <replaceable>condition</replaceable>
2281 matching the error that occurred. If a match is found, the
2282 corresponding <replaceable>handler_statements</replaceable> are
2283 executed, and then control passes to the next statement after
2284 <literal>END</>. If no match is found, the error propagates out
2285 as though the <literal>EXCEPTION</> clause were not there at all:
2286 the error can be caught by an enclosing block with
2287 <literal>EXCEPTION</>, or if there is none it aborts processing
2292 The <replaceable>condition</replaceable> names can be any of
2293 those shown in <xref linkend="errcodes-appendix">. A category
2294 name matches any error within its category. The special
2295 condition name <literal>OTHERS</> matches every error type except
2296 <literal>QUERY_CANCELED</>. (It is possible, but often unwise,
2297 to trap <literal>QUERY_CANCELED</> by name.) Condition names are
2298 not case-sensitive. Also, an error condition can be specified
2299 by <literal>SQLSTATE</> code; for example these are equivalent:
2301 WHEN division_by_zero THEN ...
2302 WHEN SQLSTATE '22012' THEN ...
2307 If a new error occurs within the selected
2308 <replaceable>handler_statements</replaceable>, it cannot be caught
2309 by this <literal>EXCEPTION</> clause, but is propagated out.
2310 A surrounding <literal>EXCEPTION</> clause could catch it.
2314 When an error is caught by an <literal>EXCEPTION</> clause,
2315 the local variables of the <application>PL/pgSQL</> function
2316 remain as they were when the error occurred, but all changes
2317 to persistent database state within the block are rolled back.
2318 As an example, consider this fragment:
2321 INSERT INTO mytab(firstname, lastname) VALUES('Tom', 'Jones');
2323 UPDATE mytab SET firstname = 'Joe' WHERE lastname = 'Jones';
2327 WHEN division_by_zero THEN
2328 RAISE NOTICE 'caught division_by_zero';
2333 When control reaches the assignment to <literal>y</>, it will
2334 fail with a <literal>division_by_zero</> error. This will be caught by
2335 the <literal>EXCEPTION</> clause. The value returned in the
2336 <command>RETURN</> statement will be the incremented value of
2337 <literal>x</>, but the effects of the <command>UPDATE</> command will
2338 have been rolled back. The <command>INSERT</> command preceding the
2339 block is not rolled back, however, so the end result is that the database
2340 contains <literal>Tom Jones</> not <literal>Joe Jones</>.
2345 A block containing an <literal>EXCEPTION</> clause is significantly
2346 more expensive to enter and exit than a block without one. Therefore,
2347 don't use <literal>EXCEPTION</> without need.
2352 Within an exception handler, the <varname>SQLSTATE</varname>
2353 variable contains the error code that corresponds to the
2354 exception that was raised (refer to <xref
2355 linkend="errcodes-table"> for a list of possible error
2356 codes). The <varname>SQLERRM</varname> variable contains the
2357 error message associated with the exception. These variables are
2358 undefined outside exception handlers.
2361 <example id="plpgsql-upsert-example">
2362 <title>Exceptions with <command>UPDATE</>/<command>INSERT</></title>
2365 This example uses exception handling to perform either
2366 <command>UPDATE</> or <command>INSERT</>, as appropriate:
2369 CREATE TABLE db (a INT PRIMARY KEY, b TEXT);
2371 CREATE FUNCTION merge_db(key INT, data TEXT) RETURNS VOID AS
2375 -- first try to update the key
2376 UPDATE db SET b = data WHERE a = key;
2380 -- not there, so try to insert the key
2381 -- if someone else inserts the same key concurrently,
2382 -- we could get a unique-key failure
2384 INSERT INTO db(a,b) VALUES (key, data);
2386 EXCEPTION WHEN unique_violation THEN
2387 -- do nothing, and loop to try the UPDATE again
2394 SELECT merge_db(1, 'david');
2395 SELECT merge_db(1, 'dennis');
2403 <sect1 id="plpgsql-cursors">
2404 <title>Cursors</title>
2406 <indexterm zone="plpgsql-cursors">
2407 <primary>cursor</primary>
2408 <secondary>in PL/pgSQL</secondary>
2412 Rather than executing a whole query at once, it is possible to set
2413 up a <firstterm>cursor</> that encapsulates the query, and then read
2414 the query result a few rows at a time. One reason for doing this is
2415 to avoid memory overrun when the result contains a large number of
2416 rows. (However, <application>PL/pgSQL</> users do not normally need
2417 to worry about that, since <literal>FOR</> loops automatically use a cursor
2418 internally to avoid memory problems.) A more interesting usage is to
2419 return a reference to a cursor that a function has created, allowing the
2420 caller to read the rows. This provides an efficient way to return
2421 large row sets from functions.
2424 <sect2 id="plpgsql-cursor-declarations">
2425 <title>Declaring Cursor Variables</title>
2428 All access to cursors in <application>PL/pgSQL</> goes through
2429 cursor variables, which are always of the special data type
2430 <type>refcursor</>. One way to create a cursor variable
2431 is just to declare it as a variable of type <type>refcursor</>.
2432 Another way is to use the cursor declaration syntax,
2433 which in general is:
2435 <replaceable>name</replaceable> <optional> <optional> NO </optional> SCROLL </optional> CURSOR <optional> ( <replaceable>arguments</replaceable> ) </optional> FOR <replaceable>query</replaceable>;
2437 (<literal>FOR</> can be replaced by <literal>IS</> for
2438 <productname>Oracle</productname> compatibility.)
2439 If <literal>SCROLL</> is specified, the cursor will be capable of
2440 scrolling backward; if <literal>NO SCROLL</> is specified, backward
2441 fetches will be rejected; if neither specification appears, it is
2442 query-dependent whether backward fetches will be allowed.
2443 <replaceable>arguments</replaceable>, if specified, is a
2444 comma-separated list of pairs <literal><replaceable>name</replaceable>
2445 <replaceable>datatype</replaceable></literal> that define names to be
2446 replaced by parameter values in the given query. The actual
2447 values to substitute for these names will be specified later,
2448 when the cursor is opened.
2455 curs2 CURSOR FOR SELECT * FROM tenk1;
2456 curs3 CURSOR (key integer) IS SELECT * FROM tenk1 WHERE unique1 = key;
2458 All three of these variables have the data type <type>refcursor</>,
2459 but the first can be used with any query, while the second has
2460 a fully specified query already <firstterm>bound</> to it, and the last
2461 has a parameterized query bound to it. (<literal>key</> will be
2462 replaced by an integer parameter value when the cursor is opened.)
2463 The variable <literal>curs1</>
2464 is said to be <firstterm>unbound</> since it is not bound to
2465 any particular query.
2469 <sect2 id="plpgsql-cursor-opening">
2470 <title>Opening Cursors</title>
2473 Before a cursor can be used to retrieve rows, it must be
2474 <firstterm>opened</>. (This is the equivalent action to the SQL
2475 command <command>DECLARE CURSOR</>.) <application>PL/pgSQL</> has
2476 three forms of the <command>OPEN</> statement, two of which use unbound
2477 cursor variables while the third uses a bound cursor variable.
2482 Bound cursor variables can also be used without explicitly opening the cursor,
2483 via the <command>FOR</> statement described in
2484 <xref linkend="plpgsql-cursor-for-loop">.
2489 <title><command>OPEN FOR</command> <replaceable>query</replaceable></title>
2492 OPEN <replaceable>unbound_cursorvar</replaceable> <optional> <optional> NO </optional> SCROLL </optional> FOR <replaceable>query</replaceable>;
2496 The cursor variable is opened and given the specified query to
2497 execute. The cursor cannot be open already, and it must have been
2498 declared as an unbound cursor variable (that is, as a simple
2499 <type>refcursor</> variable). The query must be a
2500 <command>SELECT</command>, or something else that returns rows
2501 (such as <command>EXPLAIN</>). The query
2502 is treated in the same way as other SQL commands in
2503 <application>PL/pgSQL</>: <application>PL/pgSQL</>
2504 variable names are substituted, and the query plan is cached for
2505 possible reuse. When a <application>PL/pgSQL</>
2506 variable is substituted into the cursor query, the value that is
2507 substituted is the one it has at the time of the <command>OPEN</>;
2508 subsequent changes to the variable will not affect the cursor's
2510 The <literal>SCROLL</> and <literal>NO SCROLL</>
2511 options have the same meanings as for a bound cursor.
2517 OPEN curs1 FOR SELECT * FROM foo WHERE key = mykey;
2523 <title><command>OPEN FOR EXECUTE</command></title>
2526 OPEN <replaceable>unbound_cursorvar</replaceable> <optional> <optional> NO </optional> SCROLL </optional> FOR EXECUTE <replaceable class="command">query_string</replaceable>
2527 <optional> USING <replaceable>expression</replaceable> <optional>, ... </optional> </optional>;
2531 The cursor variable is opened and given the specified query to
2532 execute. The cursor cannot be open already, and it must have been
2533 declared as an unbound cursor variable (that is, as a simple
2534 <type>refcursor</> variable). The query is specified as a string
2535 expression, in the same way as in the <command>EXECUTE</command>
2536 command. As usual, this gives flexibility so the query plan can vary
2537 from one run to the next (see <xref linkend="plpgsql-plan-caching">),
2538 and it also means that variable substitution is not done on the
2539 command string. As with <command>EXECUTE</command>, parameter values
2540 can be inserted into the dynamic command via <literal>USING</>.
2541 The <literal>SCROLL</> and
2542 <literal>NO SCROLL</> options have the same meanings as for a bound
2549 OPEN curs1 FOR EXECUTE 'SELECT * FROM ' || quote_ident(tabname)
2550 || ' WHERE col1 = $1' USING keyvalue;
2552 In this example, the table name is inserted into the query textually,
2553 so use of <function>quote_ident()</> is recommended to guard against
2554 SQL injection. The comparison value for <literal>col1</> is inserted
2555 via a <literal>USING</> parameter, so it needs no quoting.
2560 <title>Opening a Bound Cursor</title>
2563 OPEN <replaceable>bound_cursorvar</replaceable> <optional> ( <replaceable>argument_values</replaceable> ) </optional>;
2567 This form of <command>OPEN</command> is used to open a cursor
2568 variable whose query was bound to it when it was declared. The
2569 cursor cannot be open already. A list of actual argument value
2570 expressions must appear if and only if the cursor was declared to
2571 take arguments. These values will be substituted in the query.
2572 The query plan for a bound cursor is always considered cacheable;
2573 there is no equivalent of <command>EXECUTE</command> in this case.
2574 Notice that <literal>SCROLL</> and
2575 <literal>NO SCROLL</> cannot be specified, as the cursor's scrolling
2576 behavior was already determined.
2580 Note that because variable substitution is done on the bound
2581 cursor's query, there are two ways to pass values into the cursor:
2582 either with an explicit argument to <command>OPEN</>, or
2583 implicitly by referencing a <application>PL/pgSQL</> variable
2584 in the query. However, only variables declared before the bound
2585 cursor was declared will be substituted into it. In either case
2586 the value to be passed is determined at the time of the
2600 <sect2 id="plpgsql-cursor-using">
2601 <title>Using Cursors</title>
2604 Once a cursor has been opened, it can be manipulated with the
2605 statements described here.
2609 These manipulations need not occur in the same function that
2610 opened the cursor to begin with. You can return a <type>refcursor</>
2611 value out of a function and let the caller operate on the cursor.
2612 (Internally, a <type>refcursor</> value is simply the string name
2613 of a so-called portal containing the active query for the cursor. This name
2614 can be passed around, assigned to other <type>refcursor</> variables,
2615 and so on, without disturbing the portal.)
2619 All portals are implicitly closed at transaction end. Therefore
2620 a <type>refcursor</> value is usable to reference an open cursor
2621 only until the end of the transaction.
2625 <title><literal>FETCH</></title>
2628 FETCH <optional> <replaceable>direction</replaceable> { FROM | IN } </optional> <replaceable>cursor</replaceable> INTO <replaceable>target</replaceable>;
2632 <command>FETCH</command> retrieves the next row from the
2633 cursor into a target, which might be a row variable, a record
2634 variable, or a comma-separated list of simple variables, just like
2635 <command>SELECT INTO</command>. If there is no next row, the
2636 target is set to NULL(s). As with <command>SELECT
2637 INTO</command>, the special variable <literal>FOUND</literal> can
2638 be checked to see whether a row was obtained or not.
2642 The <replaceable>direction</replaceable> clause can be any of the
2643 variants allowed in the SQL <xref linkend="sql-fetch">
2644 command except the ones that can fetch
2645 more than one row; namely, it can be
2650 <literal>ABSOLUTE</> <replaceable>count</replaceable>,
2651 <literal>RELATIVE</> <replaceable>count</replaceable>,
2652 <literal>FORWARD</>, or
2653 <literal>BACKWARD</>.
2654 Omitting <replaceable>direction</replaceable> is the same
2655 as specifying <literal>NEXT</>.
2656 <replaceable>direction</replaceable> values that require moving
2657 backward are likely to fail unless the cursor was declared or opened
2658 with the <literal>SCROLL</> option.
2662 <replaceable>cursor</replaceable> must be the name of a <type>refcursor</>
2663 variable that references an open cursor portal.
2669 FETCH curs1 INTO rowvar;
2670 FETCH curs2 INTO foo, bar, baz;
2671 FETCH LAST FROM curs3 INTO x, y;
2672 FETCH RELATIVE -2 FROM curs4 INTO x;
2678 <title><literal>MOVE</></title>
2681 MOVE <optional> <replaceable>direction</replaceable> { FROM | IN } </optional> <replaceable>cursor</replaceable>;
2685 <command>MOVE</command> repositions a cursor without retrieving
2686 any data. <command>MOVE</command> works exactly like the
2687 <command>FETCH</command> command, except it only repositions the
2688 cursor and does not return the row moved to. As with <command>SELECT
2689 INTO</command>, the special variable <literal>FOUND</literal> can
2690 be checked to see whether there was a next row to move to.
2694 The <replaceable>direction</replaceable> clause can be any of the
2695 variants allowed in the SQL <xref linkend="sql-fetch">
2701 <literal>ABSOLUTE</> <replaceable>count</replaceable>,
2702 <literal>RELATIVE</> <replaceable>count</replaceable>,
2704 <literal>FORWARD</> <optional> <replaceable>count</replaceable> | <literal>ALL</> </optional>, or
2705 <literal>BACKWARD</> <optional> <replaceable>count</replaceable> | <literal>ALL</> </optional>.
2706 Omitting <replaceable>direction</replaceable> is the same
2707 as specifying <literal>NEXT</>.
2708 <replaceable>direction</replaceable> values that require moving
2709 backward are likely to fail unless the cursor was declared or opened
2710 with the <literal>SCROLL</> option.
2717 MOVE LAST FROM curs3;
2718 MOVE RELATIVE -2 FROM curs4;
2719 MOVE FORWARD 2 FROM curs4;
2725 <title><literal>UPDATE/DELETE WHERE CURRENT OF</></title>
2728 UPDATE <replaceable>table</replaceable> SET ... WHERE CURRENT OF <replaceable>cursor</replaceable>;
2729 DELETE FROM <replaceable>table</replaceable> WHERE CURRENT OF <replaceable>cursor</replaceable>;
2733 When a cursor is positioned on a table row, that row can be updated
2734 or deleted using the cursor to identify the row. There are
2735 restrictions on what the cursor's query can be (in particular,
2736 no grouping) and it's best to use <literal>FOR UPDATE</> in the
2737 cursor. For more information see the
2738 <xref linkend="sql-declare">
2745 UPDATE foo SET dataval = myval WHERE CURRENT OF curs1;
2751 <title><literal>CLOSE</></title>
2754 CLOSE <replaceable>cursor</replaceable>;
2758 <command>CLOSE</command> closes the portal underlying an open
2759 cursor. This can be used to release resources earlier than end of
2760 transaction, or to free up the cursor variable to be opened again.
2772 <title>Returning Cursors</title>
2775 <application>PL/pgSQL</> functions can return cursors to the
2776 caller. This is useful to return multiple rows or columns,
2777 especially with very large result sets. To do this, the function
2778 opens the cursor and returns the cursor name to the caller (or simply
2779 opens the cursor using a portal name specified by or otherwise known
2780 to the caller). The caller can then fetch rows from the cursor. The
2781 cursor can be closed by the caller, or it will be closed automatically
2782 when the transaction closes.
2786 The portal name used for a cursor can be specified by the
2787 programmer or automatically generated. To specify a portal name,
2788 simply assign a string to the <type>refcursor</> variable before
2789 opening it. The string value of the <type>refcursor</> variable
2790 will be used by <command>OPEN</> as the name of the underlying portal.
2791 However, if the <type>refcursor</> variable is null,
2792 <command>OPEN</> automatically generates a name that does not
2793 conflict with any existing portal, and assigns it to the
2794 <type>refcursor</> variable.
2799 A bound cursor variable is initialized to the string value
2800 representing its name, so that the portal name is the same as
2801 the cursor variable name, unless the programmer overrides it
2802 by assignment before opening the cursor. But an unbound cursor
2803 variable defaults to the null value initially, so it will receive
2804 an automatically-generated unique name, unless overridden.
2809 The following example shows one way a cursor name can be supplied by
2813 CREATE TABLE test (col text);
2814 INSERT INTO test VALUES ('123');
2816 CREATE FUNCTION reffunc(refcursor) RETURNS refcursor AS '
2818 OPEN $1 FOR SELECT col FROM test;
2824 SELECT reffunc('funccursor');
2825 FETCH ALL IN funccursor;
2831 The following example uses automatic cursor name generation:
2834 CREATE FUNCTION reffunc2() RETURNS refcursor AS '
2838 OPEN ref FOR SELECT col FROM test;
2843 -- need to be in a transaction to use cursors.
2848 --------------------
2849 <unnamed cursor 1>
2852 FETCH ALL IN "<unnamed cursor 1>";
2858 The following example shows one way to return multiple cursors
2859 from a single function:
2862 CREATE FUNCTION myfunc(refcursor, refcursor) RETURNS SETOF refcursor AS $$
2864 OPEN $1 FOR SELECT * FROM table_1;
2866 OPEN $2 FOR SELECT * FROM table_2;
2869 $$ LANGUAGE plpgsql;
2871 -- need to be in a transaction to use cursors.
2874 SELECT * FROM myfunc('a', 'b');
2884 <sect2 id="plpgsql-cursor-for-loop">
2885 <title>Looping Through a Cursor's Result</title>
2888 There is a variant of the <command>FOR</> statement that allows
2889 iterating through the rows returned by a cursor. The syntax is:
2892 <optional> <<<replaceable>label</replaceable>>> </optional>
2893 FOR <replaceable>recordvar</replaceable> IN <replaceable>bound_cursorvar</replaceable> <optional> ( <replaceable>argument_values</replaceable> ) </optional> LOOP
2894 <replaceable>statements</replaceable>
2895 END LOOP <optional> <replaceable>label</replaceable> </optional>;
2898 The cursor variable must have been bound to some query when it was
2899 declared, and it <emphasis>cannot</> be open already. The
2900 <command>FOR</> statement automatically opens the cursor, and it closes
2901 the cursor again when the loop exits. A list of actual argument value
2902 expressions must appear if and only if the cursor was declared to take
2903 arguments. These values will be substituted in the query, in just
2904 the same way as during an <command>OPEN</>.
2905 The variable <replaceable>recordvar</replaceable> is automatically
2906 defined as type <type>record</> and exists only inside the loop (any
2907 existing definition of the variable name is ignored within the loop).
2908 Each row returned by the cursor is successively assigned to this
2909 record variable and the loop body is executed.
2915 <sect1 id="plpgsql-errors-and-messages">
2916 <title>Errors and Messages</title>
2919 <primary>RAISE</primary>
2923 <primary>reporting errors</primary>
2924 <secondary>in PL/pgSQL</secondary>
2928 Use the <command>RAISE</command> statement to report messages and
2932 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>;
2933 RAISE <optional> <replaceable class="parameter">level</replaceable> </optional> <replaceable class="parameter">condition_name</> <optional> USING <replaceable class="parameter">option</replaceable> = <replaceable class="parameter">expression</replaceable> <optional>, ... </optional> </optional>;
2934 RAISE <optional> <replaceable class="parameter">level</replaceable> </optional> SQLSTATE '<replaceable class="parameter">sqlstate</>' <optional> USING <replaceable class="parameter">option</replaceable> = <replaceable class="parameter">expression</replaceable> <optional>, ... </optional> </optional>;
2935 RAISE <optional> <replaceable class="parameter">level</replaceable> </optional> USING <replaceable class="parameter">option</replaceable> = <replaceable class="parameter">expression</replaceable> <optional>, ... </optional>;
2939 The <replaceable class="parameter">level</replaceable> option specifies
2940 the error severity. Allowed levels are <literal>DEBUG</literal>,
2941 <literal>LOG</literal>, <literal>INFO</literal>,
2942 <literal>NOTICE</literal>, <literal>WARNING</literal>,
2943 and <literal>EXCEPTION</literal>, with <literal>EXCEPTION</literal>
2945 <literal>EXCEPTION</literal> raises an error (which normally aborts the
2946 current transaction); the other levels only generate messages of different
2948 Whether messages of a particular priority are reported to the client,
2949 written to the server log, or both is controlled by the
2950 <xref linkend="guc-log-min-messages"> and
2951 <xref linkend="guc-client-min-messages"> configuration
2952 variables. See <xref linkend="runtime-config"> for more
2957 After <replaceable class="parameter">level</replaceable> if any,
2958 you can write a <replaceable class="parameter">format</replaceable>
2959 (which must be a simple string literal, not an expression). The
2960 format string specifies the error message text to be reported.
2961 The format string can be followed
2962 by optional argument expressions to be inserted into the message.
2963 Inside the format string, <literal>%</literal> is replaced by the
2964 string representation of the next optional argument's value. Write
2965 <literal>%%</literal> to emit a literal <literal>%</literal>.
2969 In this example, the value of <literal>v_job_id</> will replace the
2970 <literal>%</literal> in the string:
2972 RAISE NOTICE 'Calling cs_create_job(%)', v_job_id;
2977 You can attach additional information to the error report by writing
2978 <literal>USING</> followed by <replaceable
2979 class="parameter">option</replaceable> = <replaceable
2980 class="parameter">expression</replaceable> items. The allowed
2981 <replaceable class="parameter">option</replaceable> keywords are
2982 <literal>MESSAGE</>, <literal>DETAIL</>, <literal>HINT</>, and
2983 <literal>ERRCODE</>, while each <replaceable
2984 class="parameter">expression</replaceable> can be any string-valued
2986 <literal>MESSAGE</> sets the error message text (this option can't
2987 be used in the form of <command>RAISE</> that includes a format
2988 string before <literal>USING</>).
2989 <literal>DETAIL</> supplies an error detail message, while
2990 <literal>HINT</> supplies a hint message.
2991 <literal>ERRCODE</> specifies the error code (SQLSTATE) to report,
2992 either by condition name as shown in <xref linkend="errcodes-appendix">,
2993 or directly as a five-character SQLSTATE code.
2997 This example will abort the transaction with the given error message
3000 RAISE EXCEPTION 'Nonexistent ID --> %', user_id
3001 USING HINT = 'Please check your user id';
3006 These two examples show equivalent ways of setting the SQLSTATE:
3008 RAISE 'Duplicate user ID: %', user_id USING ERRCODE = 'unique_violation';
3009 RAISE 'Duplicate user ID: %', user_id USING ERRCODE = '23505';
3014 There is a second <command>RAISE</> syntax in which the main argument
3015 is the condition name or SQLSTATE to be reported, for example:
3017 RAISE division_by_zero;
3018 RAISE SQLSTATE '22012';
3020 In this syntax, <literal>USING</> can be used to supply a custom
3021 error message, detail, or hint. Another way to do the earlier
3024 RAISE unique_violation USING MESSAGE = 'Duplicate user ID: ' || user_id;
3029 Still another variant is to write <literal>RAISE USING</> or <literal>RAISE
3030 <replaceable class="parameter">level</replaceable> USING</> and put
3031 everything else into the <literal>USING</> list.
3035 The last variant of <command>RAISE</> has no parameters at all.
3036 This form can only be used inside a <literal>BEGIN</> block's
3037 <literal>EXCEPTION</> clause;
3038 it causes the error currently being handled to be re-thrown.
3043 Before <productname>PostgreSQL</> 9.1, <command>RAISE</> without
3044 parameters was interpreted as re-throwing the error from the block
3045 containing the active exception handler. Thus an <literal>EXCEPTION</>
3046 clause nested within that handler could not catch it, even if the
3047 <command>RAISE</> was within the nested <literal>EXCEPTION</> clause's
3048 block. This was deemed surprising as well as being incompatible with
3054 If no condition name nor SQLSTATE is specified in a
3055 <command>RAISE EXCEPTION</command> command, the default is to use
3056 <literal>RAISE_EXCEPTION</> (<literal>P0001</>). If no message
3057 text is specified, the default is to use the condition name or
3058 SQLSTATE as message text.
3063 When specifying an error code by SQLSTATE code, you are not
3064 limited to the predefined error codes, but can select any
3065 error code consisting of five digits and/or upper-case ASCII
3066 letters, other than <literal>00000</>. It is recommended that
3067 you avoid throwing error codes that end in three zeroes, because
3068 these are category codes and can only be trapped by trapping
3075 <sect1 id="plpgsql-trigger">
3076 <title>Trigger Procedures</title>
3078 <indexterm zone="plpgsql-trigger">
3079 <primary>trigger</primary>
3080 <secondary>in PL/pgSQL</secondary>
3084 <application>PL/pgSQL</application> can be used to define trigger
3085 procedures. A trigger procedure is created with the
3086 <command>CREATE FUNCTION</> command, declaring it as a function with
3087 no arguments and a return type of <type>trigger</type>. Note that
3088 the function must be declared with no arguments even if it expects
3089 to receive arguments specified in <command>CREATE TRIGGER</> —
3090 trigger arguments are passed via <varname>TG_ARGV</>, as described
3095 When a <application>PL/pgSQL</application> function is called as a
3096 trigger, several special variables are created automatically in the
3097 top-level block. They are:
3101 <term><varname>NEW</varname></term>
3104 Data type <type>RECORD</type>; variable holding the new
3105 database row for <command>INSERT</>/<command>UPDATE</> operations in row-level
3106 triggers. This variable is <symbol>NULL</symbol> in statement-level triggers
3107 and for <command>DELETE</command> operations.
3113 <term><varname>OLD</varname></term>
3116 Data type <type>RECORD</type>; variable holding the old
3117 database row for <command>UPDATE</>/<command>DELETE</> operations in row-level
3118 triggers. This variable is <symbol>NULL</symbol> in statement-level triggers
3119 and for <command>INSERT</command> operations.
3125 <term><varname>TG_NAME</varname></term>
3128 Data type <type>name</type>; variable that contains the name of the trigger actually
3135 <term><varname>TG_WHEN</varname></term>
3138 Data type <type>text</type>; a string of
3139 <literal>BEFORE</literal>, <literal>AFTER</literal>, or
3140 <literal>INSTEAD OF</literal>, depending on the trigger's definition.
3146 <term><varname>TG_LEVEL</varname></term>
3149 Data type <type>text</type>; a string of either
3150 <literal>ROW</literal> or <literal>STATEMENT</literal>
3151 depending on the trigger's definition.
3157 <term><varname>TG_OP</varname></term>
3160 Data type <type>text</type>; a string of
3161 <literal>INSERT</literal>, <literal>UPDATE</literal>,
3162 <literal>DELETE</literal>, or <literal>TRUNCATE</>
3163 telling for which operation the trigger was fired.
3169 <term><varname>TG_RELID</varname></term>
3172 Data type <type>oid</type>; the object ID of the table that caused the
3179 <term><varname>TG_RELNAME</varname></term>
3182 Data type <type>name</type>; the name of the table that caused the trigger
3183 invocation. This is now deprecated, and could disappear in a future
3184 release. Use <literal>TG_TABLE_NAME</> instead.
3190 <term><varname>TG_TABLE_NAME</varname></term>
3193 Data type <type>name</type>; the name of the table that
3194 caused the trigger invocation.
3200 <term><varname>TG_TABLE_SCHEMA</varname></term>
3203 Data type <type>name</type>; the name of the schema of the
3204 table that caused the trigger invocation.
3210 <term><varname>TG_NARGS</varname></term>
3213 Data type <type>integer</type>; the number of arguments given to the trigger
3214 procedure in the <command>CREATE TRIGGER</command> statement.
3220 <term><varname>TG_ARGV[]</varname></term>
3223 Data type array of <type>text</type>; the arguments from
3224 the <command>CREATE TRIGGER</command> statement.
3225 The index counts from 0. Invalid
3226 indexes (less than 0 or greater than or equal to <varname>tg_nargs</>)
3227 result in a null value.
3235 A trigger function must return either <symbol>NULL</symbol> or a
3236 record/row value having exactly the structure of the table the
3237 trigger was fired for.
3241 Row-level triggers fired <literal>BEFORE</> can return null to signal the
3242 trigger manager to skip the rest of the operation for this row
3243 (i.e., subsequent triggers are not fired, and the
3244 <command>INSERT</>/<command>UPDATE</>/<command>DELETE</> does not occur
3245 for this row). If a nonnull
3246 value is returned then the operation proceeds with that row value.
3247 Returning a row value different from the original value
3248 of <varname>NEW</> alters the row that will be inserted or
3249 updated. Thus, if the trigger function wants the triggering
3250 action to succeed normally without altering the row
3251 value, <varname>NEW</varname> (or a value equal thereto) has to be
3252 returned. To alter the row to be stored, it is possible to
3253 replace single values directly in <varname>NEW</> and return the
3254 modified <varname>NEW</>, or to build a complete new record/row to
3255 return. In the case of a before-trigger
3256 on <command>DELETE</command>, the returned value has no direct
3257 effect, but it has to be nonnull to allow the trigger action to
3258 proceed. Note that <varname>NEW</varname> is null
3259 in <command>DELETE</command> triggers, so returning that is
3260 usually not sensible. The usual idiom in <command>DELETE</command>
3261 triggers is to return <varname>OLD</varname>.
3265 <literal>INSTEAD OF</> triggers (which are always row-level triggers,
3266 and may only be used on views) can return null to signal that they did
3267 not perform any updates, and that the rest of the operation for this
3268 row should be skipped (i.e., subsequent triggers are not fired, and the
3269 row is not counted in the rows-affected status for the surrounding
3270 <command>INSERT</>/<command>UPDATE</>/<command>DELETE</>).
3271 Otherwise a nonnull value should be returned, to signal
3272 that the trigger performed the requested operation. For
3273 <command>INSERT</> and <command>UPDATE</> operations, the return value
3274 should be <varname>NEW</>, which the trigger function may modify to
3275 support <command>INSERT RETURNING</> and <command>UPDATE RETURNING</>
3276 (this will also affect the row value passed to any subsequent triggers).
3277 For <command>DELETE</> operations, the return value should be
3282 The return value of a row-level trigger
3283 fired <literal>AFTER</literal> or a statement-level trigger
3284 fired <literal>BEFORE</> or <literal>AFTER</> is
3285 always ignored; it might as well be null. However, any of these types of
3286 triggers might still abort the entire operation by raising an error.
3290 <xref linkend="plpgsql-trigger-example"> shows an example of a
3291 trigger procedure in <application>PL/pgSQL</application>.
3294 <example id="plpgsql-trigger-example">
3295 <title>A <application>PL/pgSQL</application> Trigger Procedure</title>
3298 This example trigger ensures that any time a row is inserted or updated
3299 in the table, the current user name and time are stamped into the
3300 row. And it checks that an employee's name is given and that the
3301 salary is a positive value.
3308 last_date timestamp,
3312 CREATE FUNCTION emp_stamp() RETURNS trigger AS $emp_stamp$
3314 -- Check that empname and salary are given
3315 IF NEW.empname IS NULL THEN
3316 RAISE EXCEPTION 'empname cannot be null';
3318 IF NEW.salary IS NULL THEN
3319 RAISE EXCEPTION '% cannot have null salary', NEW.empname;
3322 -- Who works for us when she must pay for it?
3323 IF NEW.salary < 0 THEN
3324 RAISE EXCEPTION '% cannot have a negative salary', NEW.empname;
3327 -- Remember who changed the payroll when
3328 NEW.last_date := current_timestamp;
3329 NEW.last_user := current_user;
3332 $emp_stamp$ LANGUAGE plpgsql;
3334 CREATE TRIGGER emp_stamp BEFORE INSERT OR UPDATE ON emp
3335 FOR EACH ROW EXECUTE PROCEDURE emp_stamp();
3340 Another way to log changes to a table involves creating a new table that
3341 holds a row for each insert, update, or delete that occurs. This approach
3342 can be thought of as auditing changes to a table.
3343 <xref linkend="plpgsql-trigger-audit-example"> shows an example of an
3344 audit trigger procedure in <application>PL/pgSQL</application>.
3347 <example id="plpgsql-trigger-audit-example">
3348 <title>A <application>PL/pgSQL</application> Trigger Procedure For Auditing</title>
3351 This example trigger ensures that any insert, update or delete of a row
3352 in the <literal>emp</literal> table is recorded (i.e., audited) in the <literal>emp_audit</literal> table.
3353 The current time and user name are stamped into the row, together with
3354 the type of operation performed on it.
3359 empname text NOT NULL,
3363 CREATE TABLE emp_audit(
3364 operation char(1) NOT NULL,
3365 stamp timestamp NOT NULL,
3366 userid text NOT NULL,
3367 empname text NOT NULL,
3371 CREATE OR REPLACE FUNCTION process_emp_audit() RETURNS TRIGGER AS $emp_audit$
3374 -- Create a row in emp_audit to reflect the operation performed on emp,
3375 -- make use of the special variable TG_OP to work out the operation.
3377 IF (TG_OP = 'DELETE') THEN
3378 INSERT INTO emp_audit SELECT 'D', now(), user, OLD.*;
3380 ELSIF (TG_OP = 'UPDATE') THEN
3381 INSERT INTO emp_audit SELECT 'U', now(), user, NEW.*;
3383 ELSIF (TG_OP = 'INSERT') THEN
3384 INSERT INTO emp_audit SELECT 'I', now(), user, NEW.*;
3387 RETURN NULL; -- result is ignored since this is an AFTER trigger
3389 $emp_audit$ LANGUAGE plpgsql;
3391 CREATE TRIGGER emp_audit
3392 AFTER INSERT OR UPDATE OR DELETE ON emp
3393 FOR EACH ROW EXECUTE PROCEDURE process_emp_audit();
3398 A variation of the previous example uses a view joining the main table
3399 to the audit table, to show when each entry was last modified. This
3400 approach still records the full audit trail of changes to the table,
3401 but also presents a simplified view of the audit trail, showing just
3402 the last modified timestamp derived from the audit trail for each entry.
3403 <xref linkend="plpgsql-view-trigger-audit-example"> shows an example
3404 of an audit trigger on a view in <application>PL/pgSQL</application>.
3407 <example id="plpgsql-view-trigger-audit-example">
3408 <title>A <application>PL/pgSQL</application> View Trigger Procedure For Auditing</title>
3411 This example uses a trigger on the view to make it updatable, and
3412 ensure that any insert, update or delete of a row in the view is
3413 recorded (i.e., audited) in the emp_audit table. The current time
3414 and user name are recorded, together with the type of operation
3415 performed, and the view displays the last modified time of each row.
3420 empname text PRIMARY KEY,
3424 CREATE TABLE emp_audit(
3425 operation char(1) NOT NULL,
3426 userid text NOT NULL,
3427 empname text NOT NULL,
3429 stamp timestamp NOT NULL
3432 CREATE VIEW emp_view AS
3435 max(ea.stamp) AS last_updated
3437 LEFT JOIN emp_audit ea ON ea.empname = e.empname
3440 CREATE OR REPLACE FUNCTION update_emp_view() RETURNS TRIGGER AS $$
3443 -- Perform the required operation on emp, and create a row in emp_audit
3444 -- to reflect the change made to emp.
3446 IF (TG_OP = 'DELETE') THEN
3447 DELETE FROM emp WHERE empname = OLD.empname;
3448 IF NOT FOUND THEN RETURN NULL; END IF;
3450 OLD.last_updated = now();
3451 INSERT INTO emp_audit VALUES('D', user, OLD.*);
3453 ELSIF (TG_OP = 'UPDATE') THEN
3454 UPDATE emp SET salary = NEW.salary WHERE empname = OLD.empname;
3455 IF NOT FOUND THEN RETURN NULL; END IF;
3457 NEW.last_updated = now();
3458 INSERT INTO emp_audit VALUES('U', user, NEW.*);
3460 ELSIF (TG_OP = 'INSERT') THEN
3461 INSERT INTO emp VALUES(NEW.empname, NEW.salary);
3463 NEW.last_updated = now();
3464 INSERT INTO emp_audit VALUES('I', user, NEW.*);
3468 $$ LANGUAGE plpgsql;
3470 CREATE TRIGGER emp_audit
3471 INSTEAD OF INSERT OR UPDATE OR DELETE ON emp_view
3472 FOR EACH ROW EXECUTE PROCEDURE update_emp_view();
3477 One use of triggers is to maintain a summary table
3478 of another table. The resulting summary can be used in place of the
3479 original table for certain queries — often with vastly reduced run
3481 This technique is commonly used in Data Warehousing, where the tables
3482 of measured or observed data (called fact tables) might be extremely large.
3483 <xref linkend="plpgsql-trigger-summary-example"> shows an example of a
3484 trigger procedure in <application>PL/pgSQL</application> that maintains
3485 a summary table for a fact table in a data warehouse.
3489 <example id="plpgsql-trigger-summary-example">
3490 <title>A <application>PL/pgSQL</application> Trigger Procedure For Maintaining A Summary Table</title>
3493 The schema detailed here is partly based on the <emphasis>Grocery Store
3494 </emphasis> example from <emphasis>The Data Warehouse Toolkit</emphasis>
3500 -- Main tables - time dimension and sales fact.
3502 CREATE TABLE time_dimension (
3503 time_key integer NOT NULL,
3504 day_of_week integer NOT NULL,
3505 day_of_month integer NOT NULL,
3506 month integer NOT NULL,
3507 quarter integer NOT NULL,
3508 year integer NOT NULL
3510 CREATE UNIQUE INDEX time_dimension_key ON time_dimension(time_key);
3512 CREATE TABLE sales_fact (
3513 time_key integer NOT NULL,
3514 product_key integer NOT NULL,
3515 store_key integer NOT NULL,
3516 amount_sold numeric(12,2) NOT NULL,
3517 units_sold integer NOT NULL,
3518 amount_cost numeric(12,2) NOT NULL
3520 CREATE INDEX sales_fact_time ON sales_fact(time_key);
3523 -- Summary table - sales by time.
3525 CREATE TABLE sales_summary_bytime (
3526 time_key integer NOT NULL,
3527 amount_sold numeric(15,2) NOT NULL,
3528 units_sold numeric(12) NOT NULL,
3529 amount_cost numeric(15,2) NOT NULL
3531 CREATE UNIQUE INDEX sales_summary_bytime_key ON sales_summary_bytime(time_key);
3534 -- Function and trigger to amend summarized column(s) on UPDATE, INSERT, DELETE.
3536 CREATE OR REPLACE FUNCTION maint_sales_summary_bytime() RETURNS TRIGGER
3537 AS $maint_sales_summary_bytime$
3539 delta_time_key integer;
3540 delta_amount_sold numeric(15,2);
3541 delta_units_sold numeric(12);
3542 delta_amount_cost numeric(15,2);
3545 -- Work out the increment/decrement amount(s).
3546 IF (TG_OP = 'DELETE') THEN
3548 delta_time_key = OLD.time_key;
3549 delta_amount_sold = -1 * OLD.amount_sold;
3550 delta_units_sold = -1 * OLD.units_sold;
3551 delta_amount_cost = -1 * OLD.amount_cost;
3553 ELSIF (TG_OP = 'UPDATE') THEN
3555 -- forbid updates that change the time_key -
3556 -- (probably not too onerous, as DELETE + INSERT is how most
3557 -- changes will be made).
3558 IF ( OLD.time_key != NEW.time_key) THEN
3559 RAISE EXCEPTION 'Update of time_key : % -> % not allowed',
3560 OLD.time_key, NEW.time_key;
3563 delta_time_key = OLD.time_key;
3564 delta_amount_sold = NEW.amount_sold - OLD.amount_sold;
3565 delta_units_sold = NEW.units_sold - OLD.units_sold;
3566 delta_amount_cost = NEW.amount_cost - OLD.amount_cost;
3568 ELSIF (TG_OP = 'INSERT') THEN
3570 delta_time_key = NEW.time_key;
3571 delta_amount_sold = NEW.amount_sold;
3572 delta_units_sold = NEW.units_sold;
3573 delta_amount_cost = NEW.amount_cost;
3578 -- Insert or update the summary row with the new values.
3579 <<insert_update>>
3581 UPDATE sales_summary_bytime
3582 SET amount_sold = amount_sold + delta_amount_sold,
3583 units_sold = units_sold + delta_units_sold,
3584 amount_cost = amount_cost + delta_amount_cost
3585 WHERE time_key = delta_time_key;
3587 EXIT insert_update WHEN found;
3590 INSERT INTO sales_summary_bytime (
3605 WHEN UNIQUE_VIOLATION THEN
3608 END LOOP insert_update;
3613 $maint_sales_summary_bytime$ LANGUAGE plpgsql;
3615 CREATE TRIGGER maint_sales_summary_bytime
3616 AFTER INSERT OR UPDATE OR DELETE ON sales_fact
3617 FOR EACH ROW EXECUTE PROCEDURE maint_sales_summary_bytime();
3619 INSERT INTO sales_fact VALUES(1,1,1,10,3,15);
3620 INSERT INTO sales_fact VALUES(1,2,1,20,5,35);
3621 INSERT INTO sales_fact VALUES(2,2,1,40,15,135);
3622 INSERT INTO sales_fact VALUES(2,3,1,10,1,13);
3623 SELECT * FROM sales_summary_bytime;
3624 DELETE FROM sales_fact WHERE product_key = 1;
3625 SELECT * FROM sales_summary_bytime;
3626 UPDATE sales_fact SET units_sold = units_sold * 2;
3627 SELECT * FROM sales_summary_bytime;
3633 <sect1 id="plpgsql-implementation">
3634 <title><application>PL/pgSQL</> Under the Hood</title>
3637 This section discusses some implementation details that are
3638 frequently important for <application>PL/pgSQL</> users to know.
3641 <sect2 id="plpgsql-var-subst">
3642 <title>Variable Substitution</title>
3645 SQL statements and expressions within a <application>PL/pgSQL</> function
3646 can refer to variables and parameters of the function. Behind the scenes,
3647 <application>PL/pgSQL</> substitutes query parameters for such references.
3648 Parameters will only be substituted in places where a parameter or
3649 column reference is syntactically allowed. As an extreme case, consider
3650 this example of poor programming style:
3652 INSERT INTO foo (foo) VALUES (foo);
3654 The first occurrence of <literal>foo</> must syntactically be a table
3655 name, so it will not be substituted, even if the function has a variable
3656 named <literal>foo</>. The second occurrence must be the name of a
3657 column of the table, so it will not be substituted either. Only the
3658 third occurrence is a candidate to be a reference to the function's
3664 <productname>PostgreSQL</productname> versions before 9.0 would try
3665 to substitute the variable in all three cases, leading to syntax errors.
3670 Since the names of variables are syntactically no different from the names
3671 of table columns, there can be ambiguity in statements that also refer to
3672 tables: is a given name meant to refer to a table column, or a variable?
3673 Let's change the previous example to
3675 INSERT INTO dest (col) SELECT foo + bar FROM src;
3677 Here, <literal>dest</> and <literal>src</> must be table names, and
3678 <literal>col</> must be a column of <literal>dest</>, but <literal>foo</>
3679 and <literal>bar</> might reasonably be either variables of the function
3680 or columns of <literal>src</>.
3684 By default, <application>PL/pgSQL</> will report an error if a name
3685 in a SQL statement could refer to either a variable or a table column.
3686 You can fix such a problem by renaming the variable or column,
3687 or by qualifying the ambiguous reference, or by telling
3688 <application>PL/pgSQL</> which interpretation to prefer.
3692 The simplest solution is to rename the variable or column.
3693 A common coding rule is to use a
3694 different naming convention for <application>PL/pgSQL</application>
3695 variables than you use for column names. For example,
3696 if you consistently name function variables
3697 <literal>v_<replaceable>something</></literal> while none of your
3698 column names start with <literal>v_</>, no conflicts will occur.
3702 Alternatively you can qualify ambiguous references to make them clear.
3703 In the above example, <literal>src.foo</> would be an unambiguous reference
3704 to the table column. To create an unambiguous reference to a variable,
3705 declare it in a labeled block and use the block's label
3706 (see <xref linkend="plpgsql-structure">). For example,
3708 <<block>>
3713 INSERT INTO dest (col) SELECT block.foo + bar FROM src;
3715 Here <literal>block.foo</> means the variable even if there is a column
3716 <literal>foo</> in <literal>src</>. Function parameters, as well as
3717 special variables such as <literal>FOUND</>, can be qualified by the
3718 function's name, because they are implicitly declared in an outer block
3719 labeled with the function's name.
3723 Sometimes it is impractical to fix all the ambiguous references in a
3724 large body of <application>PL/pgSQL</> code. In such cases you can
3725 specify that <application>PL/pgSQL</> should resolve ambiguous references
3726 as the variable (which is compatible with <application>PL/pgSQL</>'s
3727 behavior before <productname>PostgreSQL</productname> 9.0), or as the
3728 table column (which is compatible with some other systems such as
3729 <productname>Oracle</productname>).
3733 <primary><varname>plpgsql.variable_conflict</> configuration parameter</primary>
3737 To change this behavior on a system-wide basis, set the configuration
3738 parameter <literal>plpgsql.variable_conflict</> to one of
3739 <literal>error</>, <literal>use_variable</>, or
3740 <literal>use_column</> (where <literal>error</> is the factory default).
3741 This parameter affects subsequent compilations
3742 of statements in <application>PL/pgSQL</> functions, but not statements
3743 already compiled in the current session. To set the parameter before
3744 <application>PL/pgSQL</> has been loaded, it is necessary to have added
3745 <quote><literal>plpgsql</></> to the <xref
3746 linkend="guc-custom-variable-classes"> list in
3747 <filename>postgresql.conf</filename>. Because changing this setting
3748 can cause unexpected changes in the behavior of <application>PL/pgSQL</>
3749 functions, it can only be changed by a superuser.
3753 You can also set the behavior on a function-by-function basis, by
3754 inserting one of these special commands at the start of the function
3757 #variable_conflict error
3758 #variable_conflict use_variable
3759 #variable_conflict use_column
3761 These commands affect only the function they are written in, and override
3762 the setting of <literal>plpgsql.variable_conflict</>. An example is
3764 CREATE FUNCTION stamp_user(id int, comment text) RETURNS void AS $$
3765 #variable_conflict use_variable
3767 curtime timestamp := now();
3769 UPDATE users SET last_modified = curtime, comment = comment
3770 WHERE users.id = id;
3772 $$ LANGUAGE plpgsql;
3774 In the <literal>UPDATE</> command, <literal>curtime</>, <literal>comment</>,
3775 and <literal>id</> will refer to the function's variable and parameters
3776 whether or not <literal>users</> has columns of those names. Notice
3777 that we had to qualify the reference to <literal>users.id</> in the
3778 <literal>WHERE</> clause to make it refer to the table column.
3779 But we did not have to qualify the reference to <literal>comment</>
3780 as a target in the <literal>UPDATE</> list, because syntactically
3781 that must be a column of <literal>users</>. We could write the same
3782 function without depending on the <literal>variable_conflict</> setting
3785 CREATE FUNCTION stamp_user(id int, comment text) RETURNS void AS $$
3788 curtime timestamp := now();
3790 UPDATE users SET last_modified = fn.curtime, comment = stamp_user.comment
3791 WHERE users.id = stamp_user.id;
3793 $$ LANGUAGE plpgsql;
3798 Variable substitution does not happen in the command string given
3799 to <command>EXECUTE</> or one of its variants. If you need to
3800 insert a varying value into such a command, do so as part of
3801 constructing the string value, or use <literal>USING</>, as illustrated in
3802 <xref linkend="plpgsql-statements-executing-dyn">.
3806 Variable substitution currently works only in <command>SELECT</>,
3807 <command>INSERT</>, <command>UPDATE</>, and <command>DELETE</> commands,
3808 because the main SQL engine allows query parameters only in these
3809 commands. To use a non-constant name or value in other statement
3810 types (generically called utility statements), you must construct
3811 the utility statement as a string and <command>EXECUTE</> it.
3816 <sect2 id="plpgsql-plan-caching">
3817 <title>Plan Caching</title>
3820 The <application>PL/pgSQL</> interpreter parses the function's source
3821 text and produces an internal binary instruction tree the first time the
3822 function is called (within each session). The instruction tree
3823 fully translates the
3824 <application>PL/pgSQL</> statement structure, but individual
3825 <acronym>SQL</acronym> expressions and <acronym>SQL</acronym> commands
3826 used in the function are not translated immediately.
3830 As each expression and <acronym>SQL</acronym> command is first
3831 executed in the function, the <application>PL/pgSQL</> interpreter
3832 creates a prepared execution plan (using the
3833 <acronym>SPI</acronym> manager's <function>SPI_prepare</function>
3834 and <function>SPI_saveplan</function>
3835 functions).<indexterm><primary>preparing a query</><secondary>in
3836 PL/pgSQL</></> Subsequent visits to that expression or command
3837 reuse the prepared plan. Thus, a function with conditional code
3838 that contains many statements for which execution plans might be
3839 required will only prepare and save those plans that are really
3840 used during the lifetime of the database connection. This can
3841 substantially reduce the total amount of time required to parse
3842 and generate execution plans for the statements in a
3843 <application>PL/pgSQL</> function. A disadvantage is that errors
3844 in a specific expression or command cannot be detected until that
3845 part of the function is reached in execution. (Trivial syntax
3846 errors will be detected during the initial parsing pass, but
3847 anything deeper will not be detected until execution.)
3851 A saved plan will be re-planned automatically if there is any schema
3852 change to any table used in the query, or if any user-defined function
3853 used in the query is redefined. This makes the re-use of prepared plans
3854 transparent in most cases, but there are corner cases where a stale plan
3855 might be re-used. An example is that dropping and re-creating a
3856 user-defined operator won't affect already-cached plans; they'll continue
3857 to call the original operator's underlying function, if that has not been
3858 changed. When necessary, the cache can be flushed by starting a fresh
3863 Because <application>PL/pgSQL</application> saves execution plans
3864 in this way, SQL commands that appear directly in a
3865 <application>PL/pgSQL</application> function must refer to the
3866 same tables and columns on every execution; that is, you cannot use
3867 a parameter as the name of a table or column in an SQL command. To get
3868 around this restriction, you can construct dynamic commands using
3869 the <application>PL/pgSQL</application> <command>EXECUTE</command>
3870 statement — at the price of constructing a new execution plan on
3875 Another important point is that the prepared plans are parameterized
3876 to allow the values of <application>PL/pgSQL</application> variables
3877 to change from one use to the next, as discussed in detail above.
3878 Sometimes this means that a plan is less efficient than it would be
3879 if generated for a specific variable value. As an example, consider
3881 SELECT * INTO myrec FROM dictionary WHERE word LIKE search_term;
3883 where <literal>search_term</> is a <application>PL/pgSQL</application>
3884 variable. The cached plan for this query will never use an index on
3885 <structfield>word</>, since the planner cannot assume that the
3886 <literal>LIKE</> pattern will be left-anchored at run time. To use
3887 an index the query must be planned with a specific constant
3888 <literal>LIKE</> pattern provided. This is another situation where
3889 <command>EXECUTE</command> can be used to force a new plan to be
3890 generated for each execution.
3894 The mutable nature of record variables presents another problem in this
3895 connection. When fields of a record variable are used in
3896 expressions or statements, the data types of the fields must not
3897 change from one call of the function to the next, since each
3898 expression will be planned using the data type that is present
3899 when the expression is first reached. <command>EXECUTE</command> can be
3900 used to get around this problem when necessary.
3904 If the same function is used as a trigger for more than one table,
3905 <application>PL/pgSQL</application> prepares and caches plans
3906 independently for each such table — that is, there is a cache
3907 for each trigger function and table combination, not just for each
3908 function. This alleviates some of the problems with varying
3909 data types; for instance, a trigger function will be able to work
3910 successfully with a column named <literal>key</> even if it happens
3911 to have different types in different tables.
3915 Likewise, functions having polymorphic argument types have a separate
3916 plan cache for each combination of actual argument types they have been
3917 invoked for, so that data type differences do not cause unexpected
3922 Plan caching can sometimes have surprising effects on the interpretation
3923 of time-sensitive values. For example there
3924 is a difference between what these two functions do:
3927 CREATE FUNCTION logfunc1(logtxt text) RETURNS void AS $$
3929 INSERT INTO logtable VALUES (logtxt, 'now');
3931 $$ LANGUAGE plpgsql;
3937 CREATE FUNCTION logfunc2(logtxt text) RETURNS void AS $$
3942 INSERT INTO logtable VALUES (logtxt, curtime);
3944 $$ LANGUAGE plpgsql;
3949 In the case of <function>logfunc1</function>, the
3950 <productname>PostgreSQL</productname> main parser knows when
3951 preparing the plan for the <command>INSERT</command> that the
3952 string <literal>'now'</literal> should be interpreted as
3953 <type>timestamp</type>, because the target column of
3954 <classname>logtable</classname> is of that type. Thus,
3955 <literal>'now'</literal> will be converted to a constant when the
3956 <command>INSERT</command> is planned, and then used in all
3957 invocations of <function>logfunc1</function> during the lifetime
3958 of the session. Needless to say, this isn't what the programmer
3963 In the case of <function>logfunc2</function>, the
3964 <productname>PostgreSQL</productname> main parser does not know
3965 what type <literal>'now'</literal> should become and therefore
3966 it returns a data value of type <type>text</type> containing the string
3967 <literal>now</literal>. During the ensuing assignment
3968 to the local variable <varname>curtime</varname>, the
3969 <application>PL/pgSQL</application> interpreter casts this
3970 string to the <type>timestamp</type> type by calling the
3971 <function>text_out</function> and <function>timestamp_in</function>
3972 functions for the conversion. So, the computed time stamp is updated
3973 on each execution as the programmer expects.
3980 <sect1 id="plpgsql-development-tips">
3981 <title>Tips for Developing in <application>PL/pgSQL</application></title>
3984 One good way to develop in
3985 <application>PL/pgSQL</> is to use the text editor of your
3986 choice to create your functions, and in another window, use
3987 <application>psql</application> to load and test those functions.
3988 If you are doing it this way, it
3989 is a good idea to write the function using <command>CREATE OR
3990 REPLACE FUNCTION</>. That way you can just reload the file to update
3991 the function definition. For example:
3993 CREATE OR REPLACE FUNCTION testfunc(integer) RETURNS integer AS $$
3995 $$ LANGUAGE plpgsql;
4000 While running <application>psql</application>, you can load or reload such
4001 a function definition file with:
4005 and then immediately issue SQL commands to test the function.
4009 Another good way to develop in <application>PL/pgSQL</> is with a
4010 GUI database access tool that facilitates development in a
4011 procedural language. One example of such a tool is
4012 <application>pgAdmin</>, although others exist. These tools often
4013 provide convenient features such as escaping single quotes and
4014 making it easier to recreate and debug functions.
4017 <sect2 id="plpgsql-quote-tips">
4018 <title>Handling of Quotation Marks</title>
4021 The code of a <application>PL/pgSQL</> function is specified in
4022 <command>CREATE FUNCTION</command> as a string literal. If you
4023 write the string literal in the ordinary way with surrounding
4024 single quotes, then any single quotes inside the function body
4025 must be doubled; likewise any backslashes must be doubled (assuming
4026 escape string syntax is used).
4027 Doubling quotes is at best tedious, and in more complicated cases
4028 the code can become downright incomprehensible, because you can
4029 easily find yourself needing half a dozen or more adjacent quote marks.
4030 It's recommended that you instead write the function body as a
4031 <quote>dollar-quoted</> string literal (see <xref
4032 linkend="sql-syntax-dollar-quoting">). In the dollar-quoting
4033 approach, you never double any quote marks, but instead take care to
4034 choose a different dollar-quoting delimiter for each level of
4035 nesting you need. For example, you might write the <command>CREATE
4036 FUNCTION</command> command as:
4038 CREATE OR REPLACE FUNCTION testfunc(integer) RETURNS integer AS $PROC$
4040 $PROC$ LANGUAGE plpgsql;
4042 Within this, you might use quote marks for simple literal strings in
4043 SQL commands and <literal>$$</> to delimit fragments of SQL commands
4044 that you are assembling as strings. If you need to quote text that
4045 includes <literal>$$</>, you could use <literal>$Q$</>, and so on.
4049 The following chart shows what you have to do when writing quote
4050 marks without dollar quoting. It might be useful when translating
4051 pre-dollar quoting code into something more comprehensible.
4056 <term>1 quotation mark</term>
4059 To begin and end the function body, for example:
4061 CREATE FUNCTION foo() RETURNS integer AS '
4065 Anywhere within a single-quoted function body, quote marks
4066 <emphasis>must</> appear in pairs.
4072 <term>2 quotation marks</term>
4075 For string literals inside the function body, for example:
4077 a_output := ''Blah'';
4078 SELECT * FROM users WHERE f_name=''foobar'';
4080 In the dollar-quoting approach, you'd just write:
4083 SELECT * FROM users WHERE f_name='foobar';
4085 which is exactly what the <application>PL/pgSQL</> parser would see
4092 <term>4 quotation marks</term>
4095 When you need a single quotation mark in a string constant inside the
4096 function body, for example:
4098 a_output := a_output || '' AND name LIKE ''''foobar'''' AND xyz''
4100 The value actually appended to <literal>a_output</literal> would be:
4101 <literal> AND name LIKE 'foobar' AND xyz</literal>.
4104 In the dollar-quoting approach, you'd write:
4106 a_output := a_output || $$ AND name LIKE 'foobar' AND xyz$$
4108 being careful that any dollar-quote delimiters around this are not
4109 just <literal>$$</>.
4115 <term>6 quotation marks</term>
4118 When a single quotation mark in a string inside the function body is
4119 adjacent to the end of that string constant, for example:
4121 a_output := a_output || '' AND name LIKE ''''foobar''''''
4123 The value appended to <literal>a_output</literal> would then be:
4124 <literal> AND name LIKE 'foobar'</literal>.
4127 In the dollar-quoting approach, this becomes:
4129 a_output := a_output || $$ AND name LIKE 'foobar'$$
4136 <term>10 quotation marks</term>
4139 When you want two single quotation marks in a string constant (which
4140 accounts for 8 quotation marks) and this is adjacent to the end of that
4141 string constant (2 more). You will probably only need that if
4142 you are writing a function that generates other functions, as in
4143 <xref linkend="plpgsql-porting-ex2">.
4146 a_output := a_output || '' if v_'' ||
4147 referrer_keys.kind || '' like ''''''''''
4148 || referrer_keys.key_string || ''''''''''
4149 then return '''''' || referrer_keys.referrer_type
4150 || ''''''; end if;'';
4152 The value of <literal>a_output</literal> would then be:
4154 if v_... like ''...'' then return ''...''; end if;
4158 In the dollar-quoting approach, this becomes:
4160 a_output := a_output || $$ if v_$$ || referrer_keys.kind || $$ like '$$
4161 || referrer_keys.key_string || $$'
4162 then return '$$ || referrer_keys.referrer_type
4165 where we assume we only need to put single quote marks into
4166 <literal>a_output</literal>, because it will be re-quoted before use.
4175 <!-- **** Porting from Oracle PL/SQL **** -->
4177 <sect1 id="plpgsql-porting">
4178 <title>Porting from <productname>Oracle</productname> PL/SQL</title>
4180 <indexterm zone="plpgsql-porting">
4181 <primary>Oracle</primary>
4182 <secondary>porting from PL/SQL to PL/pgSQL</secondary>
4185 <indexterm zone="plpgsql-porting">
4186 <primary>PL/SQL (Oracle)</primary>
4187 <secondary>porting to PL/pgSQL</secondary>
4191 This section explains differences between
4192 <productname>PostgreSQL</>'s <application>PL/pgSQL</application>
4193 language and Oracle's <application>PL/SQL</application> language,
4194 to help developers who port applications from
4195 <trademark class="registered">Oracle</> to <productname>PostgreSQL</>.
4199 <application>PL/pgSQL</application> is similar to PL/SQL in many
4200 aspects. It is a block-structured, imperative language, and all
4201 variables have to be declared. Assignments, loops, conditionals
4202 are similar. The main differences you should keep in mind when
4203 porting from <application>PL/SQL</> to
4204 <application>PL/pgSQL</application> are:
4209 If a name used in a SQL command could be either a column name of a
4210 table or a reference to a variable of the function,
4211 <application>PL/SQL</> treats it as a column name. This corresponds
4212 to <application>PL/pgSQL</>'s
4213 <literal>plpgsql.variable_conflict</> = <literal>use_column</>
4214 behavior, which is not the default,
4215 as explained in <xref linkend="plpgsql-var-subst">.
4216 It's often best to avoid such ambiguities in the first place,
4217 but if you have to port a large amount of code that depends on
4218 this behavior, setting <literal>variable_conflict</> may be the
4225 In <productname>PostgreSQL</> the function body must be written as
4226 a string literal. Therefore you need to use dollar quoting or escape
4227 single quotes in the function body. (See <xref
4228 linkend="plpgsql-quote-tips">.)
4234 Instead of packages, use schemas to organize your functions
4241 Since there are no packages, there are no package-level variables
4242 either. This is somewhat annoying. You can keep per-session state
4243 in temporary tables instead.
4249 Integer <command>FOR</> loops with <literal>REVERSE</> work
4250 differently: <application>PL/SQL</> counts down from the second
4251 number to the first, while <application>PL/pgSQL</> counts down
4252 from the first number to the second, requiring the loop bounds
4253 to be swapped when porting. This incompatibility is unfortunate
4254 but is unlikely to be changed. (See <xref
4255 linkend="plpgsql-integer-for">.)
4261 <command>FOR</> loops over queries (other than cursors) also work
4262 differently: the target variable(s) must have been declared,
4263 whereas <application>PL/SQL</> always declares them implicitly.
4264 An advantage of this is that the variable values are still accessible
4265 after the loop exits.
4271 There are various notational differences for the use of cursor
4280 <title>Porting Examples</title>
4283 <xref linkend="pgsql-porting-ex1"> shows how to port a simple
4284 function from <application>PL/SQL</> to <application>PL/pgSQL</>.
4287 <example id="pgsql-porting-ex1">
4288 <title>Porting a Simple Function from <application>PL/SQL</> to <application>PL/pgSQL</></title>
4291 Here is an <productname>Oracle</productname> <application>PL/SQL</> function:
4293 CREATE OR REPLACE FUNCTION cs_fmt_browser_version(v_name varchar,
4297 IF v_version IS NULL THEN
4300 RETURN v_name || '/' || v_version;
4308 Let's go through this function and see the differences compared to
4309 <application>PL/pgSQL</>:
4314 The <literal>RETURN</literal> key word in the function
4315 prototype (not the function body) becomes
4316 <literal>RETURNS</literal> in
4317 <productname>PostgreSQL</productname>.
4318 Also, <literal>IS</> becomes <literal>AS</>, and you need to
4319 add a <literal>LANGUAGE</> clause because <application>PL/pgSQL</>
4320 is not the only possible function language.
4326 In <productname>PostgreSQL</>, the function body is considered
4327 to be a string literal, so you need to use quote marks or dollar
4328 quotes around it. This substitutes for the terminating <literal>/</>
4329 in the Oracle approach.
4335 The <literal>show errors</literal> command does not exist in
4336 <productname>PostgreSQL</>, and is not needed since errors are
4337 reported automatically.
4344 This is how this function would look when ported to
4345 <productname>PostgreSQL</>:
4348 CREATE OR REPLACE FUNCTION cs_fmt_browser_version(v_name varchar,
4350 RETURNS varchar AS $$
4352 IF v_version IS NULL THEN
4355 RETURN v_name || '/' || v_version;
4357 $$ LANGUAGE plpgsql;
4363 <xref linkend="plpgsql-porting-ex2"> shows how to port a
4364 function that creates another function and how to handle the
4365 ensuing quoting problems.
4368 <example id="plpgsql-porting-ex2">
4369 <title>Porting a Function that Creates Another Function from <application>PL/SQL</> to <application>PL/pgSQL</></title>
4372 The following procedure grabs rows from a
4373 <command>SELECT</command> statement and builds a large function
4374 with the results in <literal>IF</literal> statements, for the
4379 This is the Oracle version:
4381 CREATE OR REPLACE PROCEDURE cs_update_referrer_type_proc IS
4382 CURSOR referrer_keys IS
4383 SELECT * FROM cs_referrer_keys
4385 func_cmd VARCHAR(4000);
4387 func_cmd := 'CREATE OR REPLACE FUNCTION cs_find_referrer_type(v_host IN VARCHAR,
4388 v_domain IN VARCHAR, v_url IN VARCHAR) RETURN VARCHAR IS BEGIN';
4390 FOR referrer_key IN referrer_keys LOOP
4391 func_cmd := func_cmd ||
4392 ' IF v_' || referrer_key.kind
4393 || ' LIKE ''' || referrer_key.key_string
4394 || ''' THEN RETURN ''' || referrer_key.referrer_type
4398 func_cmd := func_cmd || ' RETURN NULL; END;';
4400 EXECUTE IMMEDIATE func_cmd;
4408 Here is how this function would end up in <productname>PostgreSQL</>:
4410 CREATE OR REPLACE FUNCTION cs_update_referrer_type_proc() RETURNS void AS $func$
4412 referrer_keys CURSOR IS
4413 SELECT * FROM cs_referrer_keys
4418 func_body := 'BEGIN';
4420 FOR referrer_key IN referrer_keys LOOP
4421 func_body := func_body ||
4422 ' IF v_' || referrer_key.kind
4423 || ' LIKE ' || quote_literal(referrer_key.key_string)
4424 || ' THEN RETURN ' || quote_literal(referrer_key.referrer_type)
4428 func_body := func_body || ' RETURN NULL; END;';
4431 'CREATE OR REPLACE FUNCTION cs_find_referrer_type(v_host varchar,
4434 RETURNS varchar AS '
4435 || quote_literal(func_body)
4436 || ' LANGUAGE plpgsql;' ;
4440 $func$ LANGUAGE plpgsql;
4442 Notice how the body of the function is built separately and passed
4443 through <literal>quote_literal</> to double any quote marks in it. This
4444 technique is needed because we cannot safely use dollar quoting for
4445 defining the new function: we do not know for sure what strings will
4446 be interpolated from the <structfield>referrer_key.key_string</> field.
4447 (We are assuming here that <structfield>referrer_key.kind</> can be
4448 trusted to always be <literal>host</>, <literal>domain</>, or
4449 <literal>url</>, but <structfield>referrer_key.key_string</> might be
4450 anything, in particular it might contain dollar signs.) This function
4451 is actually an improvement on the Oracle original, because it will
4452 not generate broken code when <structfield>referrer_key.key_string</> or
4453 <structfield>referrer_key.referrer_type</> contain quote marks.
4458 <xref linkend="plpgsql-porting-ex3"> shows how to port a function
4459 with <literal>OUT</> parameters and string manipulation.
4460 <productname>PostgreSQL</> does not have a built-in
4461 <function>instr</function> function, but you can create one
4462 using a combination of other
4463 functions.<indexterm><primary>instr</></indexterm> In <xref
4464 linkend="plpgsql-porting-appendix"> there is a
4465 <application>PL/pgSQL</application> implementation of
4466 <function>instr</function> that you can use to make your porting
4470 <example id="plpgsql-porting-ex3">
4471 <title>Porting a Procedure With String Manipulation and
4472 <literal>OUT</> Parameters from <application>PL/SQL</> to
4473 <application>PL/pgSQL</></title>
4476 The following <productname>Oracle</productname> PL/SQL procedure is used
4477 to parse a URL and return several elements (host, path, and query).
4481 This is the Oracle version:
4483 CREATE OR REPLACE PROCEDURE cs_parse_url(
4485 v_host OUT VARCHAR, -- This will be passed back
4486 v_path OUT VARCHAR, -- This one too
4487 v_query OUT VARCHAR) -- And this one
4495 a_pos1 := instr(v_url, '//');
4500 a_pos2 := instr(v_url, '/', a_pos1 + 2);
4502 v_host := substr(v_url, a_pos1 + 2);
4507 v_host := substr(v_url, a_pos1 + 2, a_pos2 - a_pos1 - 2);
4508 a_pos1 := instr(v_url, '?', a_pos2 + 1);
4511 v_path := substr(v_url, a_pos2);
4515 v_path := substr(v_url, a_pos2, a_pos1 - a_pos2);
4516 v_query := substr(v_url, a_pos1 + 1);
4524 Here is a possible translation into <application>PL/pgSQL</>:
4526 CREATE OR REPLACE FUNCTION cs_parse_url(
4528 v_host OUT VARCHAR, -- This will be passed back
4529 v_path OUT VARCHAR, -- This one too
4530 v_query OUT VARCHAR) -- And this one
4539 a_pos1 := instr(v_url, '//');
4544 a_pos2 := instr(v_url, '/', a_pos1 + 2);
4546 v_host := substr(v_url, a_pos1 + 2);
4551 v_host := substr(v_url, a_pos1 + 2, a_pos2 - a_pos1 - 2);
4552 a_pos1 := instr(v_url, '?', a_pos2 + 1);
4555 v_path := substr(v_url, a_pos2);
4559 v_path := substr(v_url, a_pos2, a_pos1 - a_pos2);
4560 v_query := substr(v_url, a_pos1 + 1);
4562 $$ LANGUAGE plpgsql;
4565 This function could be used like this:
4567 SELECT * FROM cs_parse_url('http://foobar.com/query.cgi?baz');
4573 <xref linkend="plpgsql-porting-ex4"> shows how to port a procedure
4574 that uses numerous features that are specific to Oracle.
4577 <example id="plpgsql-porting-ex4">
4578 <title>Porting a Procedure from <application>PL/SQL</> to <application>PL/pgSQL</></title>
4584 CREATE OR REPLACE PROCEDURE cs_create_job(v_job_id IN INTEGER) IS
4585 a_running_job_count INTEGER;
4586 PRAGMA AUTONOMOUS_TRANSACTION;<co id="co.plpgsql-porting-pragma">
4588 LOCK TABLE cs_jobs IN EXCLUSIVE MODE;<co id="co.plpgsql-porting-locktable">
4590 SELECT count(*) INTO a_running_job_count FROM cs_jobs WHERE end_stamp IS NULL;
4592 IF a_running_job_count > 0 THEN
4593 COMMIT; -- free lock<co id="co.plpgsql-porting-commit">
4594 raise_application_error(-20000,
4595 'Unable to create a new job: a job is currently running.');
4598 DELETE FROM cs_active_job;
4599 INSERT INTO cs_active_job(job_id) VALUES (v_job_id);
4602 INSERT INTO cs_jobs (job_id, start_stamp) VALUES (v_job_id, sysdate);
4604 WHEN dup_val_on_index THEN NULL; -- don't worry if it already exists
4614 Procedures like this can easily be converted into <productname>PostgreSQL</>
4615 functions returning <type>void</type>. This procedure in
4616 particular is interesting because it can teach us some things:
4619 <callout arearefs="co.plpgsql-porting-pragma">
4621 There is no <literal>PRAGMA</literal> statement in <productname>PostgreSQL</>.
4625 <callout arearefs="co.plpgsql-porting-locktable">
4627 If you do a <command>LOCK TABLE</command> in <application>PL/pgSQL</>,
4628 the lock will not be released until the calling transaction is
4633 <callout arearefs="co.plpgsql-porting-commit">
4635 You cannot issue <command>COMMIT</> in a
4636 <application>PL/pgSQL</application> function. The function is
4637 running within some outer transaction and so <command>COMMIT</>
4638 would imply terminating the function's execution. However, in
4639 this particular case it is not necessary anyway, because the lock
4640 obtained by the <command>LOCK TABLE</command> will be released when
4648 This is how we could port this procedure to <application>PL/pgSQL</>:
4651 CREATE OR REPLACE FUNCTION cs_create_job(v_job_id integer) RETURNS void AS $$
4653 a_running_job_count integer;
4655 LOCK TABLE cs_jobs IN EXCLUSIVE MODE;
4657 SELECT count(*) INTO a_running_job_count FROM cs_jobs WHERE end_stamp IS NULL;
4659 IF a_running_job_count > 0 THEN
4660 RAISE EXCEPTION 'Unable to create a new job: a job is currently running';<co id="co.plpgsql-porting-raise">
4663 DELETE FROM cs_active_job;
4664 INSERT INTO cs_active_job(job_id) VALUES (v_job_id);
4667 INSERT INTO cs_jobs (job_id, start_stamp) VALUES (v_job_id, now());
4669 WHEN unique_violation THEN <co id="co.plpgsql-porting-exception">
4670 -- don't worry if it already exists
4673 $$ LANGUAGE plpgsql;
4677 <callout arearefs="co.plpgsql-porting-raise">
4679 The syntax of <literal>RAISE</> is considerably different from
4680 Oracle's statement, although the basic case <literal>RAISE</>
4681 <replaceable class="parameter">exception_name</replaceable> works
4685 <callout arearefs="co.plpgsql-porting-exception">
4687 The exception names supported by <application>PL/pgSQL</> are
4688 different from Oracle's. The set of built-in exception names
4689 is much larger (see <xref linkend="errcodes-appendix">). There
4690 is not currently a way to declare user-defined exception names,
4691 although you can throw user-chosen SQLSTATE values instead.
4696 The main functional difference between this procedure and the
4697 Oracle equivalent is that the exclusive lock on the <literal>cs_jobs</>
4698 table will be held until the calling transaction completes. Also, if
4699 the caller later aborts (for example due to an error), the effects of
4700 this procedure will be rolled back.
4705 <sect2 id="plpgsql-porting-other">
4706 <title>Other Things to Watch For</title>
4709 This section explains a few other things to watch for when porting
4710 Oracle <application>PL/SQL</> functions to
4711 <productname>PostgreSQL</productname>.
4714 <sect3 id="plpgsql-porting-exceptions">
4715 <title>Implicit Rollback after Exceptions</title>
4718 In <application>PL/pgSQL</>, when an exception is caught by an
4719 <literal>EXCEPTION</> clause, all database changes since the block's
4720 <literal>BEGIN</> are automatically rolled back. That is, the behavior
4721 is equivalent to what you'd get in Oracle with:
4737 If you are translating an Oracle procedure that uses
4738 <command>SAVEPOINT</> and <command>ROLLBACK TO</> in this style,
4739 your task is easy: just omit the <command>SAVEPOINT</> and
4740 <command>ROLLBACK TO</>. If you have a procedure that uses
4741 <command>SAVEPOINT</> and <command>ROLLBACK TO</> in a different way
4742 then some actual thought will be required.
4747 <title><command>EXECUTE</command></title>
4750 The <application>PL/pgSQL</> version of
4751 <command>EXECUTE</command> works similarly to the
4752 <application>PL/SQL</> version, but you have to remember to use
4753 <function>quote_literal</function> and
4754 <function>quote_ident</function> as described in <xref
4755 linkend="plpgsql-statements-executing-dyn">. Constructs of the
4756 type <literal>EXECUTE 'SELECT * FROM $1';</literal> will not work
4757 reliably unless you use these functions.
4761 <sect3 id="plpgsql-porting-optimization">
4762 <title>Optimizing <application>PL/pgSQL</application> Functions</title>
4765 <productname>PostgreSQL</> gives you two function creation
4766 modifiers to optimize execution: <quote>volatility</> (whether
4767 the function always returns the same result when given the same
4768 arguments) and <quote>strictness</quote> (whether the function
4769 returns null if any argument is null). Consult the <xref
4770 linkend="sql-createfunction">
4771 reference page for details.
4775 When making use of these optimization attributes, your
4776 <command>CREATE FUNCTION</command> statement might look something
4780 CREATE FUNCTION foo(...) RETURNS integer AS $$
4782 $$ LANGUAGE plpgsql STRICT IMMUTABLE;
4788 <sect2 id="plpgsql-porting-appendix">
4789 <title>Appendix</title>
4792 This section contains the code for a set of Oracle-compatible
4793 <function>instr</function> functions that you can use to simplify
4794 your porting efforts.
4799 -- instr functions that mimic Oracle's counterpart
4800 -- Syntax: instr(string1, string2, [n], [m]) where [] denotes optional parameters.
4802 -- Searches string1 beginning at the nth character for the mth occurrence
4803 -- of string2. If n is negative, search backwards. If m is not passed,
4804 -- assume 1 (search starts at first character).
4807 CREATE FUNCTION instr(varchar, varchar) RETURNS integer AS $$
4811 pos:= instr($1, $2, 1);
4814 $$ LANGUAGE plpgsql STRICT IMMUTABLE;
4817 CREATE FUNCTION instr(string varchar, string_to_search varchar, beg_index integer)
4818 RETURNS integer AS $$
4820 pos integer NOT NULL DEFAULT 0;
4826 IF beg_index > 0 THEN
4827 temp_str := substring(string FROM beg_index);
4828 pos := position(string_to_search IN temp_str);
4833 RETURN pos + beg_index - 1;
4836 ss_length := char_length(string_to_search);
4837 length := char_length(string);
4838 beg := length + beg_index - ss_length + 2;
4840 WHILE beg > 0 LOOP
4841 temp_str := substring(string FROM beg FOR ss_length);
4842 pos := position(string_to_search IN temp_str);
4854 $$ LANGUAGE plpgsql STRICT IMMUTABLE;
4857 CREATE FUNCTION instr(string varchar, string_to_search varchar,
4858 beg_index integer, occur_index integer)
4859 RETURNS integer AS $$
4861 pos integer NOT NULL DEFAULT 0;
4862 occur_number integer NOT NULL DEFAULT 0;
4869 IF beg_index > 0 THEN
4871 temp_str := substring(string FROM beg_index);
4873 FOR i IN 1..occur_index LOOP
4874 pos := position(string_to_search IN temp_str);
4877 beg := beg + pos - 1;
4882 temp_str := substring(string FROM beg + 1);
4891 ss_length := char_length(string_to_search);
4892 length := char_length(string);
4893 beg := length + beg_index - ss_length + 2;
4895 WHILE beg > 0 LOOP
4896 temp_str := substring(string FROM beg FOR ss_length);
4897 pos := position(string_to_search IN temp_str);
4900 occur_number := occur_number + 1;
4902 IF occur_number = occur_index THEN
4913 $$ LANGUAGE plpgsql STRICT IMMUTABLE;