1 <!-- $PostgreSQL: pgsql/doc/src/sgml/plpgsql.sgml,v 1.138 2009/02/05 15:25:49 momjian Exp $ -->
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.
61 <sect2 id="plpgsql-advantages">
62 <title>Advantages of Using <application>PL/pgSQL</application></title>
65 <acronym>SQL</acronym> is the language <productname>PostgreSQL</>
66 and most other relational databases use as query language. It's
67 portable and easy to learn. But every <acronym>SQL</acronym>
68 statement must be executed individually by the database server.
72 That means that your client application must send each query to
73 the database server, wait for it to be processed, receive and
74 process the results, do some computation, then send further
75 queries to the server. All this incurs interprocess
76 communication and will also incur network overhead if your client
77 is on a different machine than the database server.
81 With <application>PL/pgSQL</application> you can group a block of
82 computation and a series of queries <emphasis>inside</emphasis>
83 the database server, thus having the power of a procedural
84 language and the ease of use of SQL, but with considerable
85 savings of client/server communication overhead.
89 <listitem><para> Extra round trips between
90 client and server are eliminated </para></listitem>
92 <listitem><para> Intermediate results that the client does not
93 need do not have to be marshaled or transferred between server
94 and client </para></listitem>
96 <listitem><para> Multiple rounds of query
97 parsing can be avoided </para></listitem>
100 <para> This can result in a considerable performance increase as
101 compared to an application that does not use stored functions.
105 Also, with <application>PL/pgSQL</application> you can use all
106 the data types, operators and functions of SQL.
110 <sect2 id="plpgsql-args-results">
111 <title>Supported Argument and Result Data Types</title>
114 Functions written in <application>PL/pgSQL</application> can accept
115 as arguments any scalar or array data type supported by the server,
116 and they can return a result of any of these types. They can also
117 accept or return any composite type (row type) specified by name.
118 It is also possible to declare a <application>PL/pgSQL</application>
119 function as returning <type>record</>, which means that the result
120 is a row type whose columns are determined by specification in the
121 calling query, as discussed in <xref linkend="queries-tablefunctions">.
125 <application>PL/pgSQL</> functions can be declared to accept a variable
126 number of arguments by using the <literal>VARIADIC</> marker. This
127 works exactly the same way as for SQL functions, as discussed in
128 <xref linkend="xfunc-sql-variadic-functions">.
132 <application>PL/pgSQL</> functions can also be declared to accept
133 and return the polymorphic types
134 <type>anyelement</type>, <type>anyarray</type>, <type>anynonarray</type>,
135 and <type>anyenum</>. The actual
136 data types handled by a polymorphic function can vary from call to
137 call, as discussed in <xref linkend="extend-types-polymorphic">.
138 An example is shown in <xref linkend="plpgsql-declaration-aliases">.
142 <application>PL/pgSQL</> functions can also be declared to return
143 a <quote>set</> (or table) of any data type that can be returned as
144 a single instance. Such a function generates its output by executing
145 <command>RETURN NEXT</> for each desired element of the result
146 set, or by using <command>RETURN QUERY</> to output the result of
151 Finally, a <application>PL/pgSQL</> function can be declared to return
152 <type>void</> if it has no useful return value.
156 <application>PL/pgSQL</> functions can also be declared with output
157 parameters in place of an explicit specification of the return type.
158 This does not add any fundamental capability to the language, but
159 it is often convenient, especially for returning multiple values.
160 The <literal>RETURNS TABLE</> notation can also be used in place
161 of <literal>RETURNS SETOF</>.
165 Specific examples appear in
166 <xref linkend="plpgsql-declaration-aliases"> and
167 <xref linkend="plpgsql-statements-returning">.
172 <sect1 id="plpgsql-structure">
173 <title>Structure of <application>PL/pgSQL</application></title>
176 <application>PL/pgSQL</application> is a block-structured language.
177 The complete text of a function definition must be a
178 <firstterm>block</>. A block is defined as:
181 <optional> <<<replaceable>label</replaceable>>> </optional>
183 <replaceable>declarations</replaceable> </optional>
185 <replaceable>statements</replaceable>
186 END <optional> <replaceable>label</replaceable> </optional>;
191 Each declaration and each statement within a block is terminated
192 by a semicolon. A block that appears within another block must
193 have a semicolon after <literal>END</literal>, as shown above;
194 however the final <literal>END</literal> that
195 concludes a function body does not require a semicolon.
200 A common mistake is to write a semicolon immediately after
201 <literal>BEGIN</>. This is incorrect and will result in a syntax error.
206 A <replaceable>label</replaceable> is only needed if you want to
207 identify the block for use
208 in an <literal>EXIT</> statement, or to qualify the names of the
209 variables declared in the block. If a label is given after
210 <literal>END</>, it must match the label at the block's beginning.
214 All key words are case-insensitive.
215 Identifiers are implicitly converted to lowercase
216 unless double-quoted, just as they are in ordinary SQL commands.
220 There are two types of comments in <application>PL/pgSQL</>. A double
221 dash (<literal>--</literal>) starts a comment that extends to the end of
222 the line. A <literal>/*</literal> starts a block comment that extends to
223 the next occurrence of <literal>*/</literal>. Block comments cannot be
224 nested, but double dash comments can be enclosed into a block comment and
225 a double dash can hide the block comment delimiters <literal>/*</literal>
226 and <literal>*/</literal>.
230 Any statement in the statement section of a block
231 can be a <firstterm>subblock</>. Subblocks can be used for
232 logical grouping or to localize variables to a small group
233 of statements. Variables declared in a subblock mask any
234 similarly-named variables of outer blocks for the duration
235 of the subblock; but you can access the outer variables anyway
236 if you qualify their names with their block's label. For example:
238 CREATE FUNCTION somefunc() RETURNS integer AS $$
239 << outerblock >>
241 quantity integer := 30;
243 RAISE NOTICE 'Quantity here is %', quantity; -- Prints 30
249 quantity integer := 80;
251 RAISE NOTICE 'Quantity here is %', quantity; -- Prints 80
252 RAISE NOTICE 'Outer quantity here is %', outerblock.quantity; -- Prints 50
255 RAISE NOTICE 'Quantity here is %', quantity; -- Prints 50
265 There is actually a hidden <quote>outer block</> surrounding the body
266 of any <application>PL/pgSQL</> function. This block provides the
267 declarations of the function's parameters (if any), as well as some
268 special variables such as <literal>FOUND</literal> (see
269 <xref linkend="plpgsql-statements-diagnostics">). The outer block is
270 labeled with the function's name, meaning that parameters and special
271 variables can be qualified with the function's name.
276 It is important not to confuse the use of
277 <command>BEGIN</>/<command>END</> for grouping statements in
278 <application>PL/pgSQL</> with the similarly-named SQL commands
280 control. <application>PL/pgSQL</>'s <command>BEGIN</>/<command>END</>
281 are only for grouping; they do not start or end a transaction.
282 Functions and trigger procedures are always executed within a transaction
283 established by an outer query — they cannot start or commit that
284 transaction, since there would be no context for them to execute in.
285 However, a block containing an <literal>EXCEPTION</> clause effectively
286 forms a subtransaction that can be rolled back without affecting the
287 outer transaction. For more about that see <xref
288 linkend="plpgsql-error-trapping">.
292 <sect1 id="plpgsql-declarations">
293 <title>Declarations</title>
296 All variables used in a block must be declared in the
297 declarations section of the block.
298 (The only exceptions are that the loop variable of a <literal>FOR</> loop
299 iterating over a range of integer values is automatically declared as an
300 integer variable, and likewise the loop variable of a <literal>FOR</> loop
301 iterating over a cursor's result is automatically declared as a
306 <application>PL/pgSQL</> variables can have any SQL data type, such as
307 <type>integer</type>, <type>varchar</type>, and
312 Here are some examples of variable declarations:
317 myrow tablename%ROWTYPE;
318 myfield tablename.columnname%TYPE;
324 The general syntax of a variable declaration is:
326 <replaceable>name</replaceable> <optional> CONSTANT </optional> <replaceable>type</replaceable> <optional> NOT NULL </optional> <optional> { DEFAULT | := } <replaceable>expression</replaceable> </optional>;
328 The <literal>DEFAULT</> clause, if given, specifies the initial value assigned
329 to the variable when the block is entered. If the <literal>DEFAULT</> clause
330 is not given then the variable is initialized to the
331 <acronym>SQL</acronym> null value.
332 The <literal>CONSTANT</> option prevents the variable from being assigned to,
333 so that its value remains constant for the duration of the block.
334 If <literal>NOT NULL</>
335 is specified, an assignment of a null value results in a run-time
336 error. All variables declared as <literal>NOT NULL</>
337 must have a nonnull default value specified.
341 A variable's default value is evaluated and assigned to the variable
342 each time the block is entered (not just once per function call).
343 So, for example, assigning <literal>now()</literal> to a variable of type
344 <type>timestamp</type> causes the variable to have the
345 time of the current function call, not the time when the function was
352 quantity integer DEFAULT 32;
353 url varchar := 'http://mysite.com';
354 user_id CONSTANT integer := 10;
358 <sect2 id="plpgsql-declaration-aliases">
359 <title>Aliases for Function Parameters</title>
362 Parameters passed to functions are named with the identifiers
363 <literal>$1</literal>, <literal>$2</literal>,
364 etc. Optionally, aliases can be declared for
365 <literal>$<replaceable>n</replaceable></literal>
366 parameter names for increased readability. Either the alias or the
367 numeric identifier can then be used to refer to the parameter value.
371 There are two ways to create an alias. The preferred way is to give a
372 name to the parameter in the <command>CREATE FUNCTION</command> command,
375 CREATE FUNCTION sales_tax(subtotal real) RETURNS real AS $$
377 RETURN subtotal * 0.06;
381 The other way, which was the only way available before
382 <productname>PostgreSQL</productname> 8.0, is to explicitly
383 declare an alias, using the declaration syntax
386 <replaceable>name</replaceable> ALIAS FOR $<replaceable>n</replaceable>;
389 The same example in this style looks like:
391 CREATE FUNCTION sales_tax(real) RETURNS real AS $$
393 subtotal ALIAS FOR $1;
395 RETURN subtotal * 0.06;
403 These two examples are not perfectly equivalent. In the first case,
404 <literal>subtotal</> could be referenced as
405 <literal>sales_tax.subtotal</>, but in the second case it could not.
406 (Had we attached a label to the block, <literal>subtotal</> could
407 be qualified with that label, instead.)
414 CREATE FUNCTION instr(varchar, integer) RETURNS integer AS $$
416 v_string ALIAS FOR $1;
419 -- some computations using v_string and index here
424 CREATE FUNCTION concat_selected_fields(in_t sometablename) RETURNS text AS $$
426 RETURN in_t.f1 || in_t.f3 || in_t.f5 || in_t.f7;
433 When a <application>PL/pgSQL</application> function is declared
434 with output parameters, the output parameters are given
435 <literal>$<replaceable>n</replaceable></literal> names and optional
436 aliases in just the same way as the normal input parameters. An
437 output parameter is effectively a variable that starts out NULL;
438 it should be assigned to during the execution of the function.
439 The final value of the parameter is what is returned. For instance,
440 the sales-tax example could also be done this way:
443 CREATE FUNCTION sales_tax(subtotal real, OUT tax real) AS $$
445 tax := subtotal * 0.06;
450 Notice that we omitted <literal>RETURNS real</> — we could have
451 included it, but it would be redundant.
455 Output parameters are most useful when returning multiple values.
456 A trivial example is:
459 CREATE FUNCTION sum_n_product(x int, y int, OUT sum int, OUT prod int) AS $$
467 As discussed in <xref linkend="xfunc-output-parameters">, this
468 effectively creates an anonymous record type for the function's
469 results. If a <literal>RETURNS</> clause is given, it must say
470 <literal>RETURNS record</>.
474 Another way to declare a <application>PL/pgSQL</application> function
475 is with <literal>RETURNS TABLE</>, for example:
478 CREATE FUNCTION extended_sales(p_itemno int) RETURNS TABLE(quantity int, total numeric) AS $$
480 RETURN QUERY SELECT quantity, quantity * price FROM sales WHERE itemno = p_itemno;
485 This is exactly equivalent to declaring one or more <literal>OUT</>
486 parameters and specifying <literal>RETURNS SETOF
487 <replaceable>sometype</></literal>.
491 When the return type of a <application>PL/pgSQL</application>
492 function is declared as a polymorphic type (<type>anyelement</type>,
493 <type>anyarray</type>, <type>anynonarray</type>, or <type>anyenum</>),
494 a special parameter <literal>$0</literal>
495 is created. Its data type is the actual return type of the function,
496 as deduced from the actual input types (see <xref
497 linkend="extend-types-polymorphic">).
498 This allows the function to access its actual return type
499 as shown in <xref linkend="plpgsql-declaration-type">.
500 <literal>$0</literal> is initialized to null and can be modified by
501 the function, so it can be used to hold the return value if desired,
502 though that is not required. <literal>$0</literal> can also be
503 given an alias. For example, this function works on any data type
504 that has a <literal>+</> operator:
507 CREATE FUNCTION add_three_values(v1 anyelement, v2 anyelement, v3 anyelement)
508 RETURNS anyelement AS $$
512 result := v1 + v2 + v3;
520 The same effect can be had by declaring one or more output parameters as
521 polymorphic types. In this case the
522 special <literal>$0</literal> parameter is not used; the output
523 parameters themselves serve the same purpose. For example:
526 CREATE FUNCTION add_three_values(v1 anyelement, v2 anyelement, v3 anyelement,
537 <sect2 id="plpgsql-declaration-type">
538 <title>Copying Types</title>
541 <replaceable>variable</replaceable>%TYPE
545 <literal>%TYPE</literal> provides the data type of a variable or
546 table column. You can use this to declare variables that will hold
547 database values. For example, let's say you have a column named
548 <literal>user_id</literal> in your <literal>users</literal>
549 table. To declare a variable with the same data type as
550 <literal>users.user_id</> you write:
552 user_id users.user_id%TYPE;
557 By using <literal>%TYPE</literal> you don't need to know the data
558 type of the structure you are referencing, and most importantly,
559 if the data type of the referenced item changes in the future (for
560 instance: you change the type of <literal>user_id</>
561 from <type>integer</type> to <type>real</type>), you might not need
562 to change your function definition.
566 <literal>%TYPE</literal> is particularly valuable in polymorphic
567 functions, since the data types needed for internal variables can
568 change from one call to the next. Appropriate variables can be
569 created by applying <literal>%TYPE</literal> to the function's
570 arguments or result placeholders.
575 <sect2 id="plpgsql-declaration-rowtypes">
576 <title>Row Types</title>
579 <replaceable>name</replaceable> <replaceable>table_name</replaceable><literal>%ROWTYPE</literal>;
580 <replaceable>name</replaceable> <replaceable>composite_type_name</replaceable>;
584 A variable of a composite type is called a <firstterm>row</>
585 variable (or <firstterm>row-type</> variable). Such a variable
586 can hold a whole row of a <command>SELECT</> or <command>FOR</>
587 query result, so long as that query's column set matches the
588 declared type of the variable.
589 The individual fields of the row value
590 are accessed using the usual dot notation, for example
591 <literal>rowvar.field</literal>.
595 A row variable can be declared to have the same type as the rows of
596 an existing table or view, by using the
597 <replaceable>table_name</replaceable><literal>%ROWTYPE</literal>
598 notation; or it can be declared by giving a composite type's name.
599 (Since every table has an associated composite type of the same name,
600 it actually does not matter in <productname>PostgreSQL</> whether you
601 write <literal>%ROWTYPE</literal> or not. But the form with
602 <literal>%ROWTYPE</literal> is more portable.)
606 Parameters to a function can be
607 composite types (complete table rows). In that case, the
608 corresponding identifier <literal>$<replaceable>n</replaceable></> will be a row variable, and fields can
609 be selected from it, for example <literal>$1.user_id</literal>.
613 Only the user-defined columns of a table row are accessible in a
614 row-type variable, not the OID or other system columns (because the
615 row could be from a view). The fields of the row type inherit the
616 table's field size or precision for data types such as
617 <type>char(<replaceable>n</>)</type>.
621 Here is an example of using composite types. <structname>table1</>
622 and <structname>table2</> are existing tables having at least the
626 CREATE FUNCTION merge_fields(t_row table1) RETURNS text AS $$
628 t2_row table2%ROWTYPE;
630 SELECT * INTO t2_row FROM table2 WHERE ... ;
631 RETURN t_row.f1 || t2_row.f3 || t_row.f5 || t2_row.f7;
635 SELECT merge_fields(t.*) FROM table1 t WHERE ... ;
640 <sect2 id="plpgsql-declaration-records">
641 <title>Record Types</title>
644 <replaceable>name</replaceable> RECORD;
648 Record variables are similar to row-type variables, but they have no
649 predefined structure. They take on the actual row structure of the
650 row they are assigned during a <command>SELECT</> or <command>FOR</> command. The substructure
651 of a record variable can change each time it is assigned to.
652 A consequence of this is that until a record variable is first assigned
653 to, it has no substructure, and any attempt to access a
654 field in it will draw a run-time error.
658 Note that <literal>RECORD</> is not a true data type, only a placeholder.
659 One should also realize that when a <application>PL/pgSQL</application>
660 function is declared to return type <type>record</>, this is not quite the
661 same concept as a record variable, even though such a function might
662 use a record variable to hold its result. In both cases the actual row
663 structure is unknown when the function is written, but for a function
664 returning <type>record</> the actual structure is determined when the
665 calling query is parsed, whereas a record variable can change its row
666 structure on-the-fly.
670 <sect2 id="plpgsql-declaration-renaming-vars">
671 <title><literal>RENAME</></title>
674 RENAME <replaceable>oldname</replaceable> TO <replaceable>newname</replaceable>;
678 Using the <literal>RENAME</literal> declaration you can change the
679 name of a variable, record or row. This is primarily useful if
680 <varname>NEW</varname> or <varname>OLD</varname> should be
681 referenced by another name inside a trigger procedure. See also
682 <literal>ALIAS</literal>.
688 RENAME id TO user_id;
689 RENAME this_var TO that_var;
695 <literal>RENAME</literal> appears to be broken as of
696 <productname>PostgreSQL</> 7.3. Fixing this is of low priority,
697 since <literal>ALIAS</literal> covers most of the practical uses
698 of <literal>RENAME</literal>.
704 <sect1 id="plpgsql-expressions">
705 <title>Expressions</title>
708 All expressions used in <application>PL/pgSQL</application>
709 statements are processed using the server's main
710 <acronym>SQL</acronym> executor. For example, when you write
711 a <application>PL/pgSQL</application> statement like
713 IF <replaceable>expression</replaceable> THEN ...
715 <application>PL/pgSQL</application> will evaluate the expression by
718 SELECT <replaceable>expression</replaceable>
720 to the main SQL engine. While forming the <command>SELECT</> command,
721 any occurrences of <application>PL/pgSQL</application> variable names
722 are replaced by parameters, as discussed in detail in
723 <xref linkend="plpgsql-var-subst">.
724 This allows the query plan for the <command>SELECT</command> to
725 be prepared just once and then reused for subsequent
726 evaluations with different values of the variables. Thus, what
727 really happens on first use of an expression is essentially a
728 <command>PREPARE</> command. For example, if we have declared
729 two integer variables <literal>x</> and <literal>y</>, and we write
733 what happens behind the scenes is
735 PREPARE <replaceable>statement_name</>(integer, integer) AS SELECT $1 < $2;
737 and then this prepared statement is <command>EXECUTE</>d for each
738 execution of the <command>IF</> statement, with the current values
739 of the <application>PL/pgSQL</application> variables supplied as
741 The query plan prepared in this way is saved for the life of the database
742 connection, as described in
743 <xref linkend="plpgsql-plan-caching">. Normally these details are
744 not important to a <application>PL/pgSQL</application> user, but
745 they are useful to know when trying to diagnose a problem.
749 <sect1 id="plpgsql-statements">
750 <title>Basic Statements</title>
753 In this section and the following ones, we describe all the statement
754 types that are explicitly understood by
755 <application>PL/pgSQL</application>.
756 Anything not recognized as one of these statement types is presumed
757 to be an SQL command and is sent to the main database engine to execute,
758 as described in <xref linkend="plpgsql-statements-sql-noresult">
759 and <xref linkend="plpgsql-statements-sql-onerow">.
762 <sect2 id="plpgsql-statements-assignment">
763 <title>Assignment</title>
766 An assignment of a value to a <application>PL/pgSQL</application>
767 variable or row/record field is written as:
769 <replaceable>variable</replaceable> := <replaceable>expression</replaceable>;
771 As explained above, the expression in such a statement is evaluated
772 by means of an SQL <command>SELECT</> command sent to the main
773 database engine. The expression must yield a single value.
777 If the expression's result data type doesn't match the variable's
778 data type, or the variable has a specific size/precision
779 (like <type>char(20)</type>), the result value will be implicitly
780 converted by the <application>PL/pgSQL</application> interpreter using
781 the result type's output-function and
782 the variable type's input-function. Note that this could potentially
783 result in run-time errors generated by the input function, if the
784 string form of the result value is not acceptable to the input function.
790 tax := subtotal * 0.06;
791 my_record.user_id := 20;
796 <sect2 id="plpgsql-statements-sql-noresult">
797 <title>Executing a Command With No Result</title>
800 For any SQL command that does not return rows, for example
801 <command>INSERT</> without a <literal>RETURNING</> clause, you can
802 execute the command within a <application>PL/pgSQL</application> function
803 just by writing the command.
807 Any <application>PL/pgSQL</application> variable name appearing
808 in the command text is replaced by a parameter symbol, and then the
809 current value of the variable is provided as the parameter value
810 at run time. This is exactly like the processing described earlier
811 for expressions; for details see <xref linkend="plpgsql-var-subst">.
812 As an example, if you write:
819 UPDATE mytab SET val = val + delta WHERE id = key;
821 the command text seen by the main SQL engine will look like:
823 UPDATE mytab SET val = val + $1 WHERE id = $2;
825 Although you don't normally have to think about this, it's helpful
826 to know it when you need to make sense of syntax-error messages.
831 <application>PL/pgSQL</application> will substitute for any identifier
832 matching one of the function's declared variables; it is not bright
833 enough to know whether that's what you meant! Thus, it is a bad idea
834 to use a variable name that is the same as any table, column, or
835 function name that you need to reference in commands within the
836 function. For more discussion see <xref linkend="plpgsql-var-subst">.
841 When executing a SQL command in this way,
842 <application>PL/pgSQL</application> plans the command just once
843 and re-uses the plan on subsequent executions, for the life of
844 the database connection. The implications of this are discussed
845 in detail in <xref linkend="plpgsql-plan-caching">.
849 Sometimes it is useful to evaluate an expression or <command>SELECT</>
850 query but discard the result, for example when calling a function
851 that has side-effects but no useful result value. To do
852 this in <application>PL/pgSQL</application>, use the
853 <command>PERFORM</command> statement:
856 PERFORM <replaceable>query</replaceable>;
859 This executes <replaceable>query</replaceable> and discards the
860 result. Write the <replaceable>query</replaceable> the same
861 way you would write an SQL <command>SELECT</> command, but replace the
862 initial keyword <command>SELECT</> with <command>PERFORM</command>.
863 <application>PL/pgSQL</application> variables will be
864 substituted into the query just as for commands that return no result,
865 and the plan is cached in the same way. Also, the special variable
866 <literal>FOUND</literal> is set to true if the query produced at
867 least one row, or false if it produced no rows (see
868 <xref linkend="plpgsql-statements-diagnostics">).
873 One might expect that writing <command>SELECT</command> directly
874 would accomplish this result, but at
875 present the only accepted way to do it is
876 <command>PERFORM</command>. A SQL command that can return rows,
877 such as <command>SELECT</command>, will be rejected as an error
878 unless it has an <literal>INTO</> clause as discussed in the
886 PERFORM create_mv('cs_session_page_requests_mv', my_query);
891 <sect2 id="plpgsql-statements-sql-onerow">
892 <title>Executing a Query with a Single-Row Result</title>
894 <indexterm zone="plpgsql-statements-sql-onerow">
895 <primary>SELECT INTO</primary>
896 <secondary>in PL/pgSQL</secondary>
899 <indexterm zone="plpgsql-statements-sql-onerow">
900 <primary>RETURNING INTO</primary>
901 <secondary>in PL/pgSQL</secondary>
905 The result of a SQL command yielding a single row (possibly of multiple
906 columns) can be assigned to a record variable, row-type variable, or list
907 of scalar variables. This is done by writing the base SQL command and
908 adding an <literal>INTO</> clause. For example,
911 SELECT <replaceable>select_expressions</replaceable> INTO <optional>STRICT</optional> <replaceable>target</replaceable> FROM ...;
912 INSERT ... RETURNING <replaceable>expressions</replaceable> INTO <optional>STRICT</optional> <replaceable>target</replaceable>;
913 UPDATE ... RETURNING <replaceable>expressions</replaceable> INTO <optional>STRICT</optional> <replaceable>target</replaceable>;
914 DELETE ... RETURNING <replaceable>expressions</replaceable> INTO <optional>STRICT</optional> <replaceable>target</replaceable>;
917 where <replaceable>target</replaceable> can be a record variable, a row
918 variable, or a comma-separated list of simple variables and
920 <application>PL/pgSQL</application> variables will be
921 substituted into the rest of the query, and the plan is cached,
922 just as described above for commands that do not return rows.
923 This works for <command>SELECT</>,
924 <command>INSERT</>/<command>UPDATE</>/<command>DELETE</> with
925 <literal>RETURNING</>, and utility commands that return row-set
926 results (such as <command>EXPLAIN</>).
927 Except for the <literal>INTO</> clause, the SQL command is the same
928 as it would be written outside <application>PL/pgSQL</application>.
933 Note that this interpretation of <command>SELECT</> with <literal>INTO</>
934 is quite different from <productname>PostgreSQL</>'s regular
935 <command>SELECT INTO</command> command, wherein the <literal>INTO</>
936 target is a newly created table. If you want to create a table from a
937 <command>SELECT</> result inside a
938 <application>PL/pgSQL</application> function, use the syntax
939 <command>CREATE TABLE ... AS SELECT</command>.
944 If a row or a variable list is used as target, the query's result columns
945 must exactly match the structure of the target as to number and data
946 types, or a run-time error
947 occurs. When a record variable is the target, it automatically
948 configures itself to the row type of the query result columns.
952 The <literal>INTO</> clause can appear almost anywhere in the SQL
953 command. Customarily it is written either just before or just after
954 the list of <replaceable>select_expressions</replaceable> in a
955 <command>SELECT</> command, or at the end of the command for other
956 command types. It is recommended that you follow this convention
957 in case the <application>PL/pgSQL</application> parser becomes
958 stricter in future versions.
962 If <literal>STRICT</literal> is not specified in the <literal>INTO</>
963 clause, then <replaceable>target</replaceable> will be set to the first
964 row returned by the query, or to nulls if the query returned no rows.
965 (Note that <quote>the first row</> is not
966 well-defined unless you've used <literal>ORDER BY</>.) Any result rows
967 after the first row are discarded.
968 You can check the special <literal>FOUND</literal> variable (see
969 <xref linkend="plpgsql-statements-diagnostics">) to
970 determine whether a row was returned:
973 SELECT * INTO myrec FROM emp WHERE empname = myname;
975 RAISE EXCEPTION 'employee % not found', myname;
979 If the <literal>STRICT</literal> option is specified, the query must
980 return exactly one row or a run-time error will be reported, either
981 <literal>NO_DATA_FOUND</> (no rows) or <literal>TOO_MANY_ROWS</>
982 (more than one row). You can use an exception block if you wish
983 to catch the error, for example:
987 SELECT * INTO STRICT myrec FROM emp WHERE empname = myname;
989 WHEN NO_DATA_FOUND THEN
990 RAISE EXCEPTION 'employee % not found', myname;
991 WHEN TOO_MANY_ROWS THEN
992 RAISE EXCEPTION 'employee % not unique', myname;
995 Successful execution of a command with <literal>STRICT</>
996 always sets <literal>FOUND</literal> to true.
1000 For <command>INSERT</>/<command>UPDATE</>/<command>DELETE</> with
1001 <literal>RETURNING</>, <application>PL/pgSQL</application> reports
1002 an error for more than one returned row, even when
1003 <literal>STRICT</literal> is not specified. This is because there
1004 is no option such as <literal>ORDER BY</> with which to determine
1005 which affected row should be returned.
1010 The <literal>STRICT</> option matches the behavior of
1011 Oracle PL/SQL's <command>SELECT INTO</command> and related statements.
1016 To handle cases where you need to process multiple result rows
1017 from a SQL query, see <xref linkend="plpgsql-records-iterating">.
1022 <sect2 id="plpgsql-statements-executing-dyn">
1023 <title>Executing Dynamic Commands</title>
1026 Oftentimes you will want to generate dynamic commands inside your
1027 <application>PL/pgSQL</application> functions, that is, commands
1028 that will involve different tables or different data types each
1029 time they are executed. <application>PL/pgSQL</application>'s
1030 normal attempts to cache plans for commands (as discussed in
1031 <xref linkend="plpgsql-plan-caching">) will not work in such
1032 scenarios. To handle this sort of problem, the
1033 <command>EXECUTE</command> statement is provided:
1036 EXECUTE <replaceable class="command">command-string</replaceable> <optional> INTO <optional>STRICT</optional> <replaceable>target</replaceable> </optional> <optional> USING <replaceable>expression</replaceable> <optional>, ...</optional> </optional>;
1039 where <replaceable>command-string</replaceable> is an expression
1040 yielding a string (of type <type>text</type>) containing the
1041 command to be executed. The optional <replaceable>target</replaceable>
1042 is a record variable, a row variable, or a comma-separated list of
1043 simple variables and record/row fields, into which the results of
1044 the command will be stored. The optional <literal>USING</> expressions
1045 supply values to be inserted into the command.
1049 No substitution of <application>PL/pgSQL</> variables is done on the
1050 computed command string. Any required variable values must be inserted
1051 in the command string as it is constructed; or you can use parameters
1056 Also, there is no plan caching for commands executed via
1057 <command>EXECUTE</command>. Instead, the
1058 command is prepared each time the statement is run. Thus the command
1059 string can be dynamically created within the function to perform
1060 actions on different tables and columns.
1064 The <literal>INTO</literal> clause specifies where the results of
1065 a SQL command returning rows should be assigned. If a row
1066 or variable list is provided, it must exactly match the structure
1067 of the query's results (when a
1068 record variable is used, it will configure itself to match the
1069 result structure automatically). If multiple rows are returned,
1070 only the first will be assigned to the <literal>INTO</literal>
1071 variable. If no rows are returned, NULL is assigned to the
1072 <literal>INTO</literal> variable(s). If no <literal>INTO</literal>
1073 clause is specified, the query results are discarded.
1077 If the <literal>STRICT</> option is given, an error is reported
1078 unless the query produces exactly one row.
1082 The command string can use parameter values, which are referenced
1083 in the command as <literal>$1</>, <literal>$2</>, etc.
1084 These symbols refer to values supplied in the <literal>USING</>
1085 clause. This method is often preferable to inserting data values
1086 into the command string as text: it avoids run-time overhead of
1087 converting the values to text and back, and it is much less prone
1088 to SQL-injection attacks since there is no need for quoting or escaping.
1091 EXECUTE 'SELECT count(*) FROM mytable WHERE inserted_by = $1 AND inserted <= $2'
1093 USING checked_user, checked_date;
1096 Note that parameter symbols can only be used for data values
1097 — if you want to use dynamically determined table or column
1098 names, you must insert them into the command string textually.
1099 For example, if the preceding query needed to be done against a
1100 dynamically selected table, you could do this:
1102 EXECUTE 'SELECT count(*) FROM '
1103 || tabname::regclass
1104 || ' WHERE inserted_by = $1 AND inserted <= $2'
1106 USING checked_user, checked_date;
1111 An <command>EXECUTE</> with a simple constant command string and some
1112 <literal>USING</> parameters, as in the first example above, is
1113 functionally equivalent to just writing the command directly in
1114 <application>PL/pgSQL</application> and allowing replacement of
1115 <application>PL/pgSQL</application> variables to happen automatically.
1116 The important difference is that <command>EXECUTE</> will re-plan
1117 the command on each execution, generating a plan that is specific
1118 to the current parameter values; whereas
1119 <application>PL/pgSQL</application> normally creates a generic plan
1120 and caches it for re-use. In situations where the best plan depends
1121 strongly on the parameter values, <command>EXECUTE</> can be
1122 significantly faster; while when the plan is not sensitive to parameter
1123 values, re-planning will be a waste.
1127 <command>SELECT INTO</command> is not currently supported within
1128 <command>EXECUTE</command>; instead, execute a plain <command>SELECT</>
1129 command and specify <literal>INTO</> as part of the <command>EXECUTE</>
1135 The <application>PL/pgSQL</application>
1136 <command>EXECUTE</command> statement is not related to the
1137 <xref linkend="sql-execute" endterm="sql-execute-title"> SQL
1138 statement supported by the
1139 <productname>PostgreSQL</productname> server. The server's
1140 <command>EXECUTE</command> statement cannot be used directly within
1141 <application>PL/pgSQL</> functions (and is not needed).
1145 <example id="plpgsql-quote-literal-example">
1146 <title>Quoting values in dynamic queries</title>
1149 <primary>quote_ident</primary>
1150 <secondary>use in PL/PgSQL</secondary>
1154 <primary>quote_literal</primary>
1155 <secondary>use in PL/PgSQL</secondary>
1159 <primary>quote_nullable</primary>
1160 <secondary>use in PL/PgSQL</secondary>
1164 When working with dynamic commands you will often have to handle escaping
1165 of single quotes. The recommended method for quoting fixed text in your
1166 function body is dollar quoting. (If you have legacy code that does
1167 not use dollar quoting, please refer to the
1168 overview in <xref linkend="plpgsql-quote-tips">, which can save you
1169 some effort when translating said code to a more reasonable scheme.)
1173 Dynamic values that are to be inserted into the constructed
1174 query require careful handling since they might themselves contain
1176 An example (this assumes that you are using dollar quoting for the
1177 function as a whole, so the quote marks need not be doubled):
1179 EXECUTE 'UPDATE tbl SET '
1180 || quote_ident(colname)
1182 || quote_literal(newvalue)
1184 || quote_literal(keyvalue);
1189 This example demonstrates the use of the
1190 <function>quote_ident</function> and
1191 <function>quote_literal</function> functions (see <xref
1192 linkend="functions-string">). For safety, expressions containing column
1193 or table identifiers should be passed through
1194 <function>quote_ident</function> before insertion in a dynamic query.
1195 Expressions containing values that should be literal strings in the
1196 constructed command should be passed through <function>quote_literal</>.
1197 These functions take the appropriate steps to return the input text
1198 enclosed in double or single quotes respectively, with any embedded
1199 special characters properly escaped.
1203 Because <function>quote_literal</function> is labelled
1204 <literal>STRICT</literal>, it will always return null when called with a
1205 null argument. In the above example, if <literal>newvalue</> or
1206 <literal>keyvalue</> were null, the entire dynamic query string would
1207 become null, leading to an error from <command>EXECUTE</command>.
1208 You can avoid this problem by using the <function>quote_nullable</>
1209 function, which works the same as <function>quote_literal</> except that
1210 when called with a null argument it returns the string <literal>NULL</>.
1213 EXECUTE 'UPDATE tbl SET '
1214 || quote_ident(colname)
1216 || quote_nullable(newvalue)
1218 || quote_nullable(keyvalue);
1220 If you are dealing with values that might be null, you should usually
1221 use <function>quote_nullable</> in place of <function>quote_literal</>.
1225 As always, care must be taken to ensure that null values in a query do
1226 not deliver unintended results. For example the <literal>WHERE</> clause
1228 'WHERE key = ' || quote_nullable(keyvalue)
1230 will never succeed if <literal>keyvalue</> is null, because the
1231 result of using the equality operator <literal>=</> with a null operand
1232 is always null. If you wish null to work like an ordinary key value,
1233 you would need to rewrite the above as
1235 'WHERE key IS NOT DISTINCT FROM ' || quote_nullable(keyvalue)
1237 (At present, <literal>IS NOT DISTINCT FROM</> is handled much less
1238 efficiently than <literal>=</>, so don't do this unless you must.
1239 See <xref linkend="functions-comparison"> for
1240 more information on nulls and <literal>IS DISTINCT</>.)
1244 Note that dollar quoting is only useful for quoting fixed text.
1245 It would be a very bad idea to try to write this example as:
1247 EXECUTE 'UPDATE tbl SET '
1248 || quote_ident(colname)
1251 || '$$ WHERE key = '
1252 || quote_literal(keyvalue);
1254 because it would break if the contents of <literal>newvalue</>
1255 happened to contain <literal>$$</>. The same objection would
1256 apply to any other dollar-quoting delimiter you might pick.
1257 So, to safely quote text that is not known in advance, you
1258 <emphasis>must</> use <function>quote_literal</>,
1259 <function>quote_nullable</>, or <function>quote_ident</>, as appropriate.
1264 A much larger example of a dynamic command and
1265 <command>EXECUTE</command> can be seen in <xref
1266 linkend="plpgsql-porting-ex2">, which builds and executes a
1267 <command>CREATE FUNCTION</> command to define a new function.
1271 <sect2 id="plpgsql-statements-diagnostics">
1272 <title>Obtaining the Result Status</title>
1275 There are several ways to determine the effect of a command. The
1276 first method is to use the <command>GET DIAGNOSTICS</command>
1277 command, which has the form:
1280 GET DIAGNOSTICS <replaceable>variable</replaceable> = <replaceable>item</replaceable> <optional> , ... </optional>;
1283 This command allows retrieval of system status indicators. Each
1284 <replaceable>item</replaceable> is a key word identifying a state
1285 value to be assigned to the specified variable (which should be
1286 of the right data type to receive it). The currently available
1287 status items are <varname>ROW_COUNT</>, the number of rows
1288 processed by the last <acronym>SQL</acronym> command sent down to
1289 the <acronym>SQL</acronym> engine, and <varname>RESULT_OID</>,
1290 the OID of the last row inserted by the most recent
1291 <acronym>SQL</acronym> command. Note that <varname>RESULT_OID</>
1292 is only useful after an <command>INSERT</command> command into a
1293 table containing OIDs.
1299 GET DIAGNOSTICS integer_var = ROW_COUNT;
1304 The second method to determine the effects of a command is to check the
1305 special variable named <literal>FOUND</literal>, which is of
1306 type <type>boolean</type>. <literal>FOUND</literal> starts out
1307 false within each <application>PL/pgSQL</application> function call.
1308 It is set by each of the following types of statements:
1312 A <command>SELECT INTO</command> statement sets
1313 <literal>FOUND</literal> true if a row is assigned, false if no
1319 A <command>PERFORM</> statement sets <literal>FOUND</literal>
1320 true if it produces (and discards) one or more rows, false if
1326 <command>UPDATE</>, <command>INSERT</>, and <command>DELETE</>
1327 statements set <literal>FOUND</literal> true if at least one
1328 row is affected, false if no row is affected.
1333 A <command>FETCH</> statement sets <literal>FOUND</literal>
1334 true if it returns a row, false if no row is returned.
1339 A <command>MOVE</> statement sets <literal>FOUND</literal>
1340 true if it successfully repositions the cursor, false otherwise.
1346 A <command>FOR</> statement sets <literal>FOUND</literal> true
1347 if it iterates one or more times, else false. This applies to
1348 all four variants of the <command>FOR</> statement (integer
1349 <command>FOR</> loops, record-set <command>FOR</> loops,
1350 dynamic record-set <command>FOR</> loops, and cursor
1351 <command>FOR</> loops).
1352 <literal>FOUND</literal> is set this way when the
1353 <command>FOR</> loop exits; inside the execution of the loop,
1354 <literal>FOUND</literal> is not modified by the
1355 <command>FOR</> statement, although it might be changed by the
1356 execution of other statements within the loop body.
1361 A <command>RETURN QUERY</command> and <command>RETURN QUERY
1362 EXECUTE</command> statements set <literal>FOUND</literal>
1363 true if the query returns at least one row, false if no row
1369 <literal>FOUND</literal> is a local variable within each
1370 <application>PL/pgSQL</application> function; any changes to it
1371 affect only the current function.
1376 <sect2 id="plpgsql-statements-null">
1377 <title>Doing Nothing At All</title>
1380 Sometimes a placeholder statement that does nothing is useful.
1381 For example, it can indicate that one arm of an if/then/else
1382 chain is deliberately empty. For this purpose, use the
1383 <command>NULL</command> statement:
1391 For example, the following two fragments of code are equivalent:
1396 WHEN division_by_zero THEN
1397 NULL; -- ignore the error
1405 WHEN division_by_zero THEN -- ignore the error
1408 Which is preferable is a matter of taste.
1413 In Oracle's PL/SQL, empty statement lists are not allowed, and so
1414 <command>NULL</> statements are <emphasis>required</> for situations
1415 such as this. <application>PL/pgSQL</application> allows you to
1416 just write nothing, instead.
1423 <sect1 id="plpgsql-control-structures">
1424 <title>Control Structures</title>
1427 Control structures are probably the most useful (and
1428 important) part of <application>PL/pgSQL</>. With
1429 <application>PL/pgSQL</>'s control structures,
1430 you can manipulate <productname>PostgreSQL</> data in a very
1431 flexible and powerful way.
1434 <sect2 id="plpgsql-statements-returning">
1435 <title>Returning From a Function</title>
1438 There are two commands available that allow you to return data
1439 from a function: <command>RETURN</command> and <command>RETURN
1444 <title><command>RETURN</></title>
1447 RETURN <replaceable>expression</replaceable>;
1451 <command>RETURN</command> with an expression terminates the
1452 function and returns the value of
1453 <replaceable>expression</replaceable> to the caller. This form
1454 is to be used for <application>PL/pgSQL</> functions that do
1459 When returning a scalar type, any expression can be used. The
1460 expression's result will be automatically cast into the
1461 function's return type as described for assignments. To return a
1462 composite (row) value, you must write a record or row variable
1463 as the <replaceable>expression</replaceable>.
1467 If you declared the function with output parameters, write just
1468 <command>RETURN</command> with no expression. The current values
1469 of the output parameter variables will be returned.
1473 If you declared the function to return <type>void</type>, a
1474 <command>RETURN</command> statement can be used to exit the function
1475 early; but do not write an expression following
1476 <command>RETURN</command>.
1480 The return value of a function cannot be left undefined. If
1481 control reaches the end of the top-level block of the function
1482 without hitting a <command>RETURN</command> statement, a run-time
1483 error will occur. This restriction does not apply to functions
1484 with output parameters and functions returning <type>void</type>,
1485 however. In those cases a <command>RETURN</command> statement is
1486 automatically executed if the top-level block finishes.
1491 <title><command>RETURN NEXT</> and <command>RETURN QUERY</command></title>
1493 <primary>RETURN NEXT</primary>
1494 <secondary>in PL/PgSQL</secondary>
1497 <primary>RETURN QUERY</primary>
1498 <secondary>in PL/PgSQL</secondary>
1502 RETURN NEXT <replaceable>expression</replaceable>;
1503 RETURN QUERY <replaceable>query</replaceable>;
1504 RETURN QUERY EXECUTE <replaceable class="command">command-string</replaceable> <optional> USING <replaceable>expression</replaceable> <optional>, ...</optional> </optional>;
1508 When a <application>PL/pgSQL</> function is declared to return
1509 <literal>SETOF <replaceable>sometype</></literal>, the procedure
1510 to follow is slightly different. In that case, the individual
1511 items to return are specified by a sequence of <command>RETURN
1512 NEXT</command> or <command>RETURN QUERY</command> commands, and
1513 then a final <command>RETURN</command> command with no argument
1514 is used to indicate that the function has finished executing.
1515 <command>RETURN NEXT</command> can be used with both scalar and
1516 composite data types; with a composite result type, an entire
1517 <quote>table</quote> of results will be returned.
1518 <command>RETURN QUERY</command> appends the results of executing
1519 a query to the function's result set. <command>RETURN
1520 NEXT</command> and <command>RETURN QUERY</command> can be freely
1521 intermixed in a single set-returning function, in which case
1522 their results will be concatenated.
1526 <command>RETURN NEXT</command> and <command>RETURN
1527 QUERY</command> do not actually return from the function —
1528 they simply append zero or more rows to the function's result
1529 set. Execution then continues with the next statement in the
1530 <application>PL/pgSQL</> function. As successive
1531 <command>RETURN NEXT</command> or <command>RETURN
1532 QUERY</command> commands are executed, the result set is built
1533 up. A final <command>RETURN</command>, which should have no
1534 argument, causes control to exit the function (or you can just
1535 let control reach the end of the function).
1539 <command>RETURN QUERY</command> has a variant
1540 <command>RETURN QUERY EXECUTE</command>, which specifies the
1541 query to be executed dynamically. Parameter expressions can
1542 be inserted into the computed query string via <literal>USING</>,
1543 in just the same way as in the <command>EXECUTE</> command.
1547 If you declared the function with output parameters, write just
1548 <command>RETURN NEXT</command> with no expression. On each
1549 execution, the current values of the output parameter
1550 variable(s) will be saved for eventual return as a row of the
1551 result. Note that you must declare the function as returning
1552 <literal>SETOF record</literal> when there are multiple output
1553 parameters, or <literal>SETOF <replaceable>sometype</></literal>
1554 when there is just one output parameter of type
1555 <replaceable>sometype</>, in order to create a set-returning
1556 function with output parameters.
1560 Here is an example of a function using <command>RETURN
1564 CREATE TABLE foo (fooid INT, foosubid INT, fooname TEXT);
1565 INSERT INTO foo VALUES (1, 2, 'three');
1566 INSERT INTO foo VALUES (4, 5, 'six');
1568 CREATE OR REPLACE FUNCTION getAllFoo() RETURNS SETOF foo AS
1573 FOR r IN SELECT * FROM foo
1576 -- can do some processing here
1577 RETURN NEXT r; -- return current row of SELECT
1582 LANGUAGE 'plpgsql' ;
1584 SELECT * FROM getallfoo();
1590 The current implementation of <command>RETURN NEXT</command>
1591 and <command>RETURN QUERY</command> stores the entire result set
1592 before returning from the function, as discussed above. That
1593 means that if a <application>PL/pgSQL</> function produces a
1594 very large result set, performance might be poor: data will be
1595 written to disk to avoid memory exhaustion, but the function
1596 itself will not return until the entire result set has been
1597 generated. A future version of <application>PL/pgSQL</> might
1598 allow users to define set-returning functions
1599 that do not have this limitation. Currently, the point at
1600 which data begins being written to disk is controlled by the
1601 <xref linkend="guc-work-mem">
1602 configuration variable. Administrators who have sufficient
1603 memory to store larger result sets in memory should consider
1604 increasing this parameter.
1610 <sect2 id="plpgsql-conditionals">
1611 <title>Conditionals</title>
1614 <command>IF</> and <command>CASE</> statements let you execute
1615 alternative commands based on certain conditions.
1616 <application>PL/pgSQL</> has three forms of <command>IF</>:
1619 <para><literal>IF ... THEN</></>
1622 <para><literal>IF ... THEN ... ELSE</></>
1625 <para><literal>IF ... THEN ... ELSIF ... THEN ... ELSE</></>
1629 and two forms of <command>CASE</>:
1632 <para><literal>CASE ... WHEN ... THEN ... ELSE ... END CASE</></>
1635 <para><literal>CASE WHEN ... THEN ... ELSE ... END CASE</></>
1641 <title><literal>IF-THEN</></title>
1644 IF <replaceable>boolean-expression</replaceable> THEN
1645 <replaceable>statements</replaceable>
1650 <literal>IF-THEN</literal> statements are the simplest form of
1651 <literal>IF</literal>. The statements between
1652 <literal>THEN</literal> and <literal>END IF</literal> will be
1653 executed if the condition is true. Otherwise, they are
1660 IF v_user_id <> 0 THEN
1661 UPDATE users SET email = v_email WHERE user_id = v_user_id;
1668 <title><literal>IF-THEN-ELSE</></title>
1671 IF <replaceable>boolean-expression</replaceable> THEN
1672 <replaceable>statements</replaceable>
1674 <replaceable>statements</replaceable>
1679 <literal>IF-THEN-ELSE</literal> statements add to
1680 <literal>IF-THEN</literal> by letting you specify an
1681 alternative set of statements that should be executed if the
1682 condition is not true. (Note this includes the case where the
1683 condition evaluates to NULL.)
1689 IF parentid IS NULL OR parentid = ''
1693 RETURN hp_true_filename(parentid) || '/' || fullname;
1698 IF v_count > 0 THEN
1699 INSERT INTO users_count (count) VALUES (v_count);
1709 <title><literal>IF-THEN-ELSIF</></title>
1712 IF <replaceable>boolean-expression</replaceable> THEN
1713 <replaceable>statements</replaceable>
1714 <optional> ELSIF <replaceable>boolean-expression</replaceable> THEN
1715 <replaceable>statements</replaceable>
1716 <optional> ELSIF <replaceable>boolean-expression</replaceable> THEN
1717 <replaceable>statements</replaceable>
1722 <replaceable>statements</replaceable> </optional>
1727 Sometimes there are more than just two alternatives.
1728 <literal>IF-THEN-ELSIF</> provides a convenient
1729 method of checking several alternatives in turn.
1730 The <literal>IF</> conditions are tested successively
1731 until the first one that is true is found. Then the
1732 associated statement(s) are executed, after which control
1733 passes to the next statement after <literal>END IF</>.
1734 (Any subsequent <literal>IF</> conditions are <emphasis>not</>
1735 tested.) If none of the <literal>IF</> conditions is true,
1736 then the <literal>ELSE</> block (if any) is executed.
1745 ELSIF number > 0 THEN
1746 result := 'positive';
1747 ELSIF number < 0 THEN
1748 result := 'negative';
1750 -- hmm, the only other possibility is that number is null
1757 The key word <literal>ELSIF</> can also be spelled
1762 An alternative way of accomplishing the same task is to nest
1763 <literal>IF-THEN-ELSE</literal> statements, as in the
1767 IF demo_row.sex = 'm' THEN
1768 pretty_sex := 'man';
1770 IF demo_row.sex = 'f' THEN
1771 pretty_sex := 'woman';
1778 However, this method requires writing a matching <literal>END IF</>
1779 for each <literal>IF</>, so it is much more cumbersome than
1780 using <literal>ELSIF</> when there are many alternatives.
1785 <title>Simple <literal>CASE</></title>
1788 CASE <replaceable>search-expression</replaceable>
1789 WHEN <replaceable>expression</replaceable> <optional>, <replaceable>expression</replaceable> <optional> ... </optional></optional> THEN
1790 <replaceable>statements</replaceable>
1791 <optional> WHEN <replaceable>expression</replaceable> <optional>, <replaceable>expression</replaceable> <optional> ... </optional></optional> THEN
1792 <replaceable>statements</replaceable>
1795 <replaceable>statements</replaceable> </optional>
1800 The simple form of <command>CASE</> provides conditional execution
1801 based on equality of operands. The <replaceable>search-expression</>
1802 is evaluated (once) and successively compared to each
1803 <replaceable>expression</> in the <literal>WHEN</> clauses.
1804 If a match is found, then the corresponding
1805 <replaceable>statements</replaceable> are executed, and then control
1806 passes to the next statement after <literal>END CASE</>. (Subsequent
1807 <literal>WHEN</> expressions are not evaluated.) If no match is
1808 found, the <literal>ELSE</> <replaceable>statements</replaceable> are
1809 executed; but if <literal>ELSE</> is not present, then a
1810 <literal>CASE_NOT_FOUND</literal> exception is raised.
1814 Here is a simple example:
1819 msg := 'one or two';
1821 msg := 'other value than one or two';
1828 <title>Searched <literal>CASE</></title>
1832 WHEN <replaceable>boolean-expression</replaceable> THEN
1833 <replaceable>statements</replaceable>
1834 <optional> WHEN <replaceable>boolean-expression</replaceable> THEN
1835 <replaceable>statements</replaceable>
1838 <replaceable>statements</replaceable> </optional>
1843 The searched form of <command>CASE</> provides conditional execution
1844 based on truth of boolean expressions. Each <literal>WHEN</> clause's
1845 <replaceable>boolean-expression</replaceable> is evaluated in turn,
1846 until one is found that yields <literal>true</>. Then the
1847 corresponding <replaceable>statements</replaceable> are executed, and
1848 then control passes to the next statement after <literal>END CASE</>.
1849 (Subsequent <literal>WHEN</> expressions are not evaluated.)
1850 If no true result is found, the <literal>ELSE</>
1851 <replaceable>statements</replaceable> are executed;
1852 but if <literal>ELSE</> is not present, then a
1853 <literal>CASE_NOT_FOUND</literal> exception is raised.
1861 WHEN x BETWEEN 0 AND 10 THEN
1862 msg := 'value is between zero and ten';
1863 WHEN x BETWEEN 11 AND 20 THEN
1864 msg := 'value is between eleven and twenty';
1870 This form of <command>CASE</> is entirely equivalent to
1871 <literal>IF-THEN-ELSIF</>, except for the rule that reaching
1872 an omitted <literal>ELSE</> clause results in an error rather
1879 <sect2 id="plpgsql-control-structures-loops">
1880 <title>Simple Loops</title>
1882 <indexterm zone="plpgsql-control-structures-loops">
1883 <primary>loop</primary>
1884 <secondary>in PL/pgSQL</secondary>
1888 With the <literal>LOOP</>, <literal>EXIT</>,
1889 <literal>CONTINUE</>, <literal>WHILE</>, and <literal>FOR</>
1890 statements, you can arrange for your <application>PL/pgSQL</>
1891 function to repeat a series of commands.
1895 <title><literal>LOOP</></title>
1898 <optional> <<<replaceable>label</replaceable>>> </optional>
1900 <replaceable>statements</replaceable>
1901 END LOOP <optional> <replaceable>label</replaceable> </optional>;
1905 <literal>LOOP</> defines an unconditional loop that is repeated
1906 indefinitely until terminated by an <literal>EXIT</> or
1907 <command>RETURN</command> statement. The optional
1908 <replaceable>label</replaceable> can be used by <literal>EXIT</>
1909 and <literal>CONTINUE</literal> statements in nested loops to
1910 specify which loop the statement should be applied to.
1915 <title><literal>EXIT</></title>
1918 <primary>EXIT</primary>
1919 <secondary>in PL/pgSQL</secondary>
1923 EXIT <optional> <replaceable>label</replaceable> </optional> <optional> WHEN <replaceable>boolean-expression</replaceable> </optional>;
1927 If no <replaceable>label</replaceable> is given, the innermost
1928 loop is terminated and the statement following <literal>END
1929 LOOP</> is executed next. If <replaceable>label</replaceable>
1930 is given, it must be the label of the current or some outer
1931 level of nested loop or block. Then the named loop or block is
1932 terminated and control continues with the statement after the
1933 loop's/block's corresponding <literal>END</>.
1937 If <literal>WHEN</> is specified, the loop exit occurs only if
1938 <replaceable>boolean-expression</> is true. Otherwise, control passes
1939 to the statement after <literal>EXIT</>.
1943 <literal>EXIT</> can be used with all types of loops; it is
1944 not limited to use with unconditional loops. When used with a
1945 <literal>BEGIN</literal> block, <literal>EXIT</literal> passes
1946 control to the next statement after the end of the block.
1953 -- some computations
1954 IF count > 0 THEN
1960 -- some computations
1961 EXIT WHEN count > 0; -- same result as previous example
1965 -- some computations
1966 IF stocks > 100000 THEN
1967 EXIT; -- causes exit from the BEGIN block
1975 <title><literal>CONTINUE</></title>
1978 <primary>CONTINUE</primary>
1979 <secondary>in PL/pgSQL</secondary>
1983 CONTINUE <optional> <replaceable>label</replaceable> </optional> <optional> WHEN <replaceable>boolean-expression</replaceable> </optional>;
1987 If no <replaceable>label</> is given, the next iteration of
1988 the innermost loop is begun. That is, all statements remaining
1989 in the loop body are skipped, and control returns
1990 to the loop control expression (if any) to determine whether
1991 another loop iteration is needed.
1992 If <replaceable>label</> is present, it
1993 specifies the label of the loop whose execution will be
1998 If <literal>WHEN</> is specified, the next iteration of the
1999 loop is begun only if <replaceable>boolean-expression</> is
2000 true. Otherwise, control passes to the statement after
2001 <literal>CONTINUE</>.
2005 <literal>CONTINUE</> can be used with all types of loops; it
2006 is not limited to use with unconditional loops.
2013 -- some computations
2014 EXIT WHEN count > 100;
2015 CONTINUE WHEN count < 50;
2016 -- some computations for count IN [50 .. 100]
2024 <title><literal>WHILE</></title>
2027 <primary>WHILE</primary>
2028 <secondary>in PL/pgSQL</secondary>
2032 <optional> <<<replaceable>label</replaceable>>> </optional>
2033 WHILE <replaceable>boolean-expression</replaceable> LOOP
2034 <replaceable>statements</replaceable>
2035 END LOOP <optional> <replaceable>label</replaceable> </optional>;
2039 The <literal>WHILE</> statement repeats a
2040 sequence of statements so long as the
2041 <replaceable>boolean-expression</replaceable>
2042 evaluates to true. The expression is checked just before
2043 each entry to the loop body.
2049 WHILE amount_owed > 0 AND gift_certificate_balance > 0 LOOP
2050 -- some computations here
2054 -- some computations here
2060 <sect3 id="plpgsql-integer-for">
2061 <title><literal>FOR</> (integer variant)</title>
2064 <optional> <<<replaceable>label</replaceable>>> </optional>
2065 FOR <replaceable>name</replaceable> IN <optional> REVERSE </optional> <replaceable>expression</replaceable> .. <replaceable>expression</replaceable> <optional> BY <replaceable>expression</replaceable> </optional> LOOP
2066 <replaceable>statements</replaceable>
2067 END LOOP <optional> <replaceable>label</replaceable> </optional>;
2071 This form of <literal>FOR</> creates a loop that iterates over a range
2072 of integer values. The variable
2073 <replaceable>name</replaceable> is automatically defined as type
2074 <type>integer</> and exists only inside the loop (any existing
2075 definition of the variable name is ignored within the loop).
2076 The two expressions giving
2077 the lower and upper bound of the range are evaluated once when entering
2078 the loop. If the <literal>BY</> clause isn't specified the iteration
2079 step is 1, otherwise it's the value specified in the <literal>BY</>
2080 clause, which again is evaluated once on loop entry.
2081 If <literal>REVERSE</> is specified then the step value is
2082 subtracted, rather than added, after each iteration.
2086 Some examples of integer <literal>FOR</> loops:
2089 -- i will take on the values 1,2,3,4,5,6,7,8,9,10 within the loop
2092 FOR i IN REVERSE 10..1 LOOP
2093 -- i will take on the values 10,9,8,7,6,5,4,3,2,1 within the loop
2096 FOR i IN REVERSE 10..1 BY 2 LOOP
2097 -- i will take on the values 10,8,6,4,2 within the loop
2103 If the lower bound is greater than the upper bound (or less than,
2104 in the <literal>REVERSE</> case), the loop body is not
2105 executed at all. No error is raised.
2109 If a <replaceable>label</replaceable> is attached to the
2110 <literal>FOR</> loop then the integer loop variable can be
2111 referenced with a qualified name, using that
2112 <replaceable>label</replaceable>.
2117 <sect2 id="plpgsql-records-iterating">
2118 <title>Looping Through Query Results</title>
2121 Using a different type of <literal>FOR</> loop, you can iterate through
2122 the results of a query and manipulate that data
2123 accordingly. The syntax is:
2125 <optional> <<<replaceable>label</replaceable>>> </optional>
2126 FOR <replaceable>target</replaceable> IN <replaceable>query</replaceable> LOOP
2127 <replaceable>statements</replaceable>
2128 END LOOP <optional> <replaceable>label</replaceable> </optional>;
2130 The <replaceable>target</replaceable> is a record variable, row variable,
2131 or comma-separated list of scalar variables.
2132 The <replaceable>target</replaceable> is successively assigned each row
2133 resulting from the <replaceable>query</replaceable> and the loop body is
2134 executed for each row. Here is an example:
2136 CREATE FUNCTION cs_refresh_mviews() RETURNS integer AS $$
2140 PERFORM cs_log('Refreshing materialized views...');
2142 FOR mviews IN SELECT * FROM cs_materialized_views ORDER BY sort_key LOOP
2144 -- Now "mviews" has one record from cs_materialized_views
2146 PERFORM cs_log('Refreshing materialized view ' || quote_ident(mviews.mv_name) || ' ...');
2147 EXECUTE 'TRUNCATE TABLE ' || quote_ident(mviews.mv_name);
2148 EXECUTE 'INSERT INTO ' || quote_ident(mviews.mv_name) || ' ' || mviews.mv_query;
2151 PERFORM cs_log('Done refreshing materialized views.');
2154 $$ LANGUAGE plpgsql;
2157 If the loop is terminated by an <literal>EXIT</> statement, the last
2158 assigned row value is still accessible after the loop.
2162 The <replaceable>query</replaceable> used in this type of <literal>FOR</>
2163 statement can be any SQL command that returns rows to the caller:
2164 <command>SELECT</> is the most common case,
2165 but you can also use <command>INSERT</>, <command>UPDATE</>, or
2166 <command>DELETE</> with a <literal>RETURNING</> clause. Some utility
2167 commands such as <command>EXPLAIN</> will work too.
2171 <application>PL/pgSQL</> variables are substituted into the query text,
2172 and the query plan is cached for possible re-use, as discussed in
2173 detail in <xref linkend="plpgsql-var-subst"> and
2174 <xref linkend="plpgsql-plan-caching">.
2178 The <literal>FOR-IN-EXECUTE</> statement is another way to iterate over
2181 <optional> <<<replaceable>label</replaceable>>> </optional>
2182 FOR <replaceable>target</replaceable> IN EXECUTE <replaceable>text_expression</replaceable> <optional> USING <replaceable>expression</replaceable> <optional>, ...</optional> </optional> LOOP
2183 <replaceable>statements</replaceable>
2184 END LOOP <optional> <replaceable>label</replaceable> </optional>;
2186 This is like the previous form, except that the source query
2187 is specified as a string expression, which is evaluated and replanned
2188 on each entry to the <literal>FOR</> loop. This allows the programmer to
2189 choose the speed of a preplanned query or the flexibility of a dynamic
2190 query, just as with a plain <command>EXECUTE</command> statement.
2191 As with <command>EXECUTE</command>, parameter values can be inserted
2192 into the dynamic command via <literal>USING</>.
2196 Another way to specify the query whose results should be iterated
2197 through is to declare it as a cursor. This is described in
2198 <xref linkend="plpgsql-cursor-for-loop">.
2202 <sect2 id="plpgsql-error-trapping">
2203 <title>Trapping Errors</title>
2206 <primary>exceptions</primary>
2207 <secondary>in PL/PgSQL</secondary>
2211 By default, any error occurring in a <application>PL/pgSQL</>
2212 function aborts execution of the function, and indeed of the
2213 surrounding transaction as well. You can trap errors and recover
2214 from them by using a <command>BEGIN</> block with an
2215 <literal>EXCEPTION</> clause. The syntax is an extension of the
2216 normal syntax for a <command>BEGIN</> block:
2219 <optional> <<<replaceable>label</replaceable>>> </optional>
2221 <replaceable>declarations</replaceable> </optional>
2223 <replaceable>statements</replaceable>
2225 WHEN <replaceable>condition</replaceable> <optional> OR <replaceable>condition</replaceable> ... </optional> THEN
2226 <replaceable>handler_statements</replaceable>
2227 <optional> WHEN <replaceable>condition</replaceable> <optional> OR <replaceable>condition</replaceable> ... </optional> THEN
2228 <replaceable>handler_statements</replaceable>
2235 If no error occurs, this form of block simply executes all the
2236 <replaceable>statements</replaceable>, and then control passes
2237 to the next statement after <literal>END</>. But if an error
2238 occurs within the <replaceable>statements</replaceable>, further
2239 processing of the <replaceable>statements</replaceable> is
2240 abandoned, and control passes to the <literal>EXCEPTION</> list.
2241 The list is searched for the first <replaceable>condition</replaceable>
2242 matching the error that occurred. If a match is found, the
2243 corresponding <replaceable>handler_statements</replaceable> are
2244 executed, and then control passes to the next statement after
2245 <literal>END</>. If no match is found, the error propagates out
2246 as though the <literal>EXCEPTION</> clause were not there at all:
2247 the error can be caught by an enclosing block with
2248 <literal>EXCEPTION</>, or if there is none it aborts processing
2253 The <replaceable>condition</replaceable> names can be any of
2254 those shown in <xref linkend="errcodes-appendix">. A category
2255 name matches any error within its category. The special
2256 condition name <literal>OTHERS</> matches every error type except
2257 <literal>QUERY_CANCELED</>. (It is possible, but often unwise,
2258 to trap <literal>QUERY_CANCELED</> by name.) Condition names are
2259 not case-sensitive. Also, an error condition can be specified
2260 by <literal>SQLSTATE</> code; for example these are equivalent:
2262 WHEN division_by_zero THEN ...
2263 WHEN SQLSTATE '22012' THEN ...
2268 If a new error occurs within the selected
2269 <replaceable>handler_statements</replaceable>, it cannot be caught
2270 by this <literal>EXCEPTION</> clause, but is propagated out.
2271 A surrounding <literal>EXCEPTION</> clause could catch it.
2275 When an error is caught by an <literal>EXCEPTION</> clause,
2276 the local variables of the <application>PL/pgSQL</> function
2277 remain as they were when the error occurred, but all changes
2278 to persistent database state within the block are rolled back.
2279 As an example, consider this fragment:
2282 INSERT INTO mytab(firstname, lastname) VALUES('Tom', 'Jones');
2284 UPDATE mytab SET firstname = 'Joe' WHERE lastname = 'Jones';
2288 WHEN division_by_zero THEN
2289 RAISE NOTICE 'caught division_by_zero';
2294 When control reaches the assignment to <literal>y</>, it will
2295 fail with a <literal>division_by_zero</> error. This will be caught by
2296 the <literal>EXCEPTION</> clause. The value returned in the
2297 <command>RETURN</> statement will be the incremented value of
2298 <literal>x</>, but the effects of the <command>UPDATE</> command will
2299 have been rolled back. The <command>INSERT</> command preceding the
2300 block is not rolled back, however, so the end result is that the database
2301 contains <literal>Tom Jones</> not <literal>Joe Jones</>.
2306 A block containing an <literal>EXCEPTION</> clause is significantly
2307 more expensive to enter and exit than a block without one. Therefore,
2308 don't use <literal>EXCEPTION</> without need.
2313 Within an exception handler, the <varname>SQLSTATE</varname>
2314 variable contains the error code that corresponds to the
2315 exception that was raised (refer to <xref
2316 linkend="errcodes-table"> for a list of possible error
2317 codes). The <varname>SQLERRM</varname> variable contains the
2318 error message associated with the exception. These variables are
2319 undefined outside exception handlers.
2322 <example id="plpgsql-upsert-example">
2323 <title>Exceptions with <command>UPDATE</>/<command>INSERT</></title>
2326 This example uses exception handling to perform either
2327 <command>UPDATE</> or <command>INSERT</>, as appropriate:
2330 CREATE TABLE db (a INT PRIMARY KEY, b TEXT);
2332 CREATE FUNCTION merge_db(key INT, data TEXT) RETURNS VOID AS
2336 -- first try to update the key
2337 UPDATE db SET b = data WHERE a = key;
2341 -- not there, so try to insert the key
2342 -- if someone else inserts the same key concurrently,
2343 -- we could get a unique-key failure
2345 INSERT INTO db(a,b) VALUES (key, data);
2347 EXCEPTION WHEN unique_violation THEN
2348 -- do nothing, and loop to try the UPDATE again
2355 SELECT merge_db(1, 'david');
2356 SELECT merge_db(1, 'dennis');
2364 <sect1 id="plpgsql-cursors">
2365 <title>Cursors</title>
2367 <indexterm zone="plpgsql-cursors">
2368 <primary>cursor</primary>
2369 <secondary>in PL/pgSQL</secondary>
2373 Rather than executing a whole query at once, it is possible to set
2374 up a <firstterm>cursor</> that encapsulates the query, and then read
2375 the query result a few rows at a time. One reason for doing this is
2376 to avoid memory overrun when the result contains a large number of
2377 rows. (However, <application>PL/pgSQL</> users do not normally need
2378 to worry about that, since <literal>FOR</> loops automatically use a cursor
2379 internally to avoid memory problems.) A more interesting usage is to
2380 return a reference to a cursor that a function has created, allowing the
2381 caller to read the rows. This provides an efficient way to return
2382 large row sets from functions.
2385 <sect2 id="plpgsql-cursor-declarations">
2386 <title>Declaring Cursor Variables</title>
2389 All access to cursors in <application>PL/pgSQL</> goes through
2390 cursor variables, which are always of the special data type
2391 <type>refcursor</>. One way to create a cursor variable
2392 is just to declare it as a variable of type <type>refcursor</>.
2393 Another way is to use the cursor declaration syntax,
2394 which in general is:
2396 <replaceable>name</replaceable> <optional> <optional> NO </optional> SCROLL </optional> CURSOR <optional> ( <replaceable>arguments</replaceable> ) </optional> FOR <replaceable>query</replaceable>;
2398 (<literal>FOR</> can be replaced by <literal>IS</> for
2399 <productname>Oracle</productname> compatibility.)
2400 If <literal>SCROLL</> is specified, the cursor will be capable of
2401 scrolling backward; if <literal>NO SCROLL</> is specified, backward
2402 fetches will be rejected; if neither specification appears, it is
2403 query-dependent whether backward fetches will be allowed.
2404 <replaceable>arguments</replaceable>, if specified, is a
2405 comma-separated list of pairs <literal><replaceable>name</replaceable>
2406 <replaceable>datatype</replaceable></literal> that define names to be
2407 replaced by parameter values in the given query. The actual
2408 values to substitute for these names will be specified later,
2409 when the cursor is opened.
2416 curs2 CURSOR FOR SELECT * FROM tenk1;
2417 curs3 CURSOR (key integer) IS SELECT * FROM tenk1 WHERE unique1 = key;
2419 All three of these variables have the data type <type>refcursor</>,
2420 but the first can be used with any query, while the second has
2421 a fully specified query already <firstterm>bound</> to it, and the last
2422 has a parameterized query bound to it. (<literal>key</> will be
2423 replaced by an integer parameter value when the cursor is opened.)
2424 The variable <literal>curs1</>
2425 is said to be <firstterm>unbound</> since it is not bound to
2426 any particular query.
2430 <sect2 id="plpgsql-cursor-opening">
2431 <title>Opening Cursors</title>
2434 Before a cursor can be used to retrieve rows, it must be
2435 <firstterm>opened</>. (This is the equivalent action to the SQL
2436 command <command>DECLARE CURSOR</>.) <application>PL/pgSQL</> has
2437 three forms of the <command>OPEN</> statement, two of which use unbound
2438 cursor variables while the third uses a bound cursor variable.
2443 Bound cursors can also be used without explicitly opening them,
2444 via the <command>FOR</> statement described in
2445 <xref linkend="plpgsql-cursor-for-loop">.
2450 <title><command>OPEN FOR</command> <replaceable>query</replaceable></title>
2453 OPEN <replaceable>unbound_cursor</replaceable> <optional> <optional> NO </optional> SCROLL </optional> FOR <replaceable>query</replaceable>;
2457 The cursor variable is opened and given the specified query to
2458 execute. The cursor cannot be open already, and it must have been
2459 declared as an unbound cursor (that is, as a simple
2460 <type>refcursor</> variable). The query must be a
2461 <command>SELECT</command>, or something else that returns rows
2462 (such as <command>EXPLAIN</>). The query
2463 is treated in the same way as other SQL commands in
2464 <application>PL/pgSQL</>: <application>PL/pgSQL</>
2465 variable names are substituted, and the query plan is cached for
2466 possible reuse. When a <application>PL/pgSQL</>
2467 variable is substituted into the cursor query, the value that is
2468 substituted is the one it has at the time of the <command>OPEN</>;
2469 subsequent changes to the variable will not affect the cursor's
2471 The <literal>SCROLL</> and <literal>NO SCROLL</>
2472 options have the same meanings as for a bound cursor.
2478 OPEN curs1 FOR SELECT * FROM foo WHERE key = mykey;
2484 <title><command>OPEN FOR EXECUTE</command></title>
2487 OPEN <replaceable>unbound_cursor</replaceable> <optional> <optional> NO </optional> SCROLL </optional> FOR EXECUTE <replaceable class="command">query_string</replaceable>;
2491 The cursor variable is opened and given the specified query to
2492 execute. The cursor cannot be open already, and it must have been
2493 declared as an unbound cursor (that is, as a simple
2494 <type>refcursor</> variable). The query is specified as a string
2495 expression, in the same way as in the <command>EXECUTE</command>
2496 command. As usual, this gives flexibility so the query plan can vary
2497 from one run to the next (see <xref linkend="plpgsql-plan-caching">),
2498 and it also means that variable substitution is not done on the
2500 The <literal>SCROLL</> and
2501 <literal>NO SCROLL</> options have the same meanings as for a bound
2508 OPEN curs1 FOR EXECUTE 'SELECT * FROM ' || quote_ident($1);
2514 <title>Opening a Bound Cursor</title>
2517 OPEN <replaceable>bound_cursor</replaceable> <optional> ( <replaceable>argument_values</replaceable> ) </optional>;
2521 This form of <command>OPEN</command> is used to open a cursor
2522 variable whose query was bound to it when it was declared. The
2523 cursor cannot be open already. A list of actual argument value
2524 expressions must appear if and only if the cursor was declared to
2525 take arguments. These values will be substituted in the query.
2526 The query plan for a bound cursor is always considered cacheable;
2527 there is no equivalent of <command>EXECUTE</command> in this case.
2528 Notice that <literal>SCROLL</> and
2529 <literal>NO SCROLL</> cannot be specified, as the cursor's scrolling
2530 behavior was already determined.
2534 Note that because variable substitution is done on the bound
2535 cursor's query, there are two ways to pass values into the cursor:
2536 either with an explicit argument to <command>OPEN</>, or
2537 implicitly by referencing a <application>PL/pgSQL</> variable
2538 in the query. However, only variables declared before the bound
2539 cursor was declared will be substituted into it. In either case
2540 the value to be passed is determined at the time of the
2554 <sect2 id="plpgsql-cursor-using">
2555 <title>Using Cursors</title>
2558 Once a cursor has been opened, it can be manipulated with the
2559 statements described here.
2563 These manipulations need not occur in the same function that
2564 opened the cursor to begin with. You can return a <type>refcursor</>
2565 value out of a function and let the caller operate on the cursor.
2566 (Internally, a <type>refcursor</> value is simply the string name
2567 of a so-called portal containing the active query for the cursor. This name
2568 can be passed around, assigned to other <type>refcursor</> variables,
2569 and so on, without disturbing the portal.)
2573 All portals are implicitly closed at transaction end. Therefore
2574 a <type>refcursor</> value is usable to reference an open cursor
2575 only until the end of the transaction.
2579 <title><literal>FETCH</></title>
2582 FETCH <optional> <replaceable>direction</replaceable> { FROM | IN } </optional> <replaceable>cursor</replaceable> INTO <replaceable>target</replaceable>;
2586 <command>FETCH</command> retrieves the next row from the
2587 cursor into a target, which might be a row variable, a record
2588 variable, or a comma-separated list of simple variables, just like
2589 <command>SELECT INTO</command>. If there is no next row, the
2590 target is set to NULL(s). As with <command>SELECT
2591 INTO</command>, the special variable <literal>FOUND</literal> can
2592 be checked to see whether a row was obtained or not.
2596 The <replaceable>direction</replaceable> clause can be any of the
2597 variants allowed in the SQL <xref linkend="sql-fetch"
2598 endterm="sql-fetch-title"> command except the ones that can fetch
2599 more than one row; namely, it can be
2604 <literal>ABSOLUTE</> <replaceable>count</replaceable>,
2605 <literal>RELATIVE</> <replaceable>count</replaceable>,
2606 <literal>FORWARD</>, or
2607 <literal>BACKWARD</>.
2608 Omitting <replaceable>direction</replaceable> is the same
2609 as specifying <literal>NEXT</>.
2610 <replaceable>direction</replaceable> values that require moving
2611 backward are likely to fail unless the cursor was declared or opened
2612 with the <literal>SCROLL</> option.
2616 <replaceable>cursor</replaceable> must be the name of a <type>refcursor</>
2617 variable that references an open cursor portal.
2623 FETCH curs1 INTO rowvar;
2624 FETCH curs2 INTO foo, bar, baz;
2625 FETCH LAST FROM curs3 INTO x, y;
2626 FETCH RELATIVE -2 FROM curs4 INTO x;
2632 <title><literal>MOVE</></title>
2635 MOVE <optional> <replaceable>direction</replaceable> { FROM | IN } </optional> <replaceable>cursor</replaceable>;
2639 <command>MOVE</command> repositions a cursor without retrieving
2640 any data. <command>MOVE</command> works exactly like the
2641 <command>FETCH</command> command, except it only repositions the
2642 cursor and does not return the row moved to. As with <command>SELECT
2643 INTO</command>, the special variable <literal>FOUND</literal> can
2644 be checked to see whether there was a next row to move to.
2648 The options for the <replaceable>direction</replaceable> clause are
2649 the same as for <command>FETCH</>, namely
2654 <literal>ABSOLUTE</> <replaceable>count</replaceable>,
2655 <literal>RELATIVE</> <replaceable>count</replaceable>,
2656 <literal>FORWARD</>, or
2657 <literal>BACKWARD</>.
2658 Omitting <replaceable>direction</replaceable> is the same
2659 as specifying <literal>NEXT</>.
2660 <replaceable>direction</replaceable> values that require moving
2661 backward are likely to fail unless the cursor was declared or opened
2662 with the <literal>SCROLL</> option.
2669 MOVE LAST FROM curs3;
2670 MOVE RELATIVE -2 FROM curs4;
2676 <title><literal>UPDATE/DELETE WHERE CURRENT OF</></title>
2679 UPDATE <replaceable>table</replaceable> SET ... WHERE CURRENT OF <replaceable>cursor</replaceable>;
2680 DELETE FROM <replaceable>table</replaceable> WHERE CURRENT OF <replaceable>cursor</replaceable>;
2684 When a cursor is positioned on a table row, that row can be updated
2685 or deleted using the cursor to identify the row. There are
2686 restrictions on what the cursor's query can be (in particular,
2687 no grouping) and it's best to use <literal>FOR UPDATE</> in the
2688 cursor. For additional information see the
2689 <xref linkend="sql-declare" endterm="sql-declare-title">
2696 UPDATE foo SET dataval = myval WHERE CURRENT OF curs1;
2702 <title><literal>CLOSE</></title>
2705 CLOSE <replaceable>cursor</replaceable>;
2709 <command>CLOSE</command> closes the portal underlying an open
2710 cursor. This can be used to release resources earlier than end of
2711 transaction, or to free up the cursor variable to be opened again.
2723 <title>Returning Cursors</title>
2726 <application>PL/pgSQL</> functions can return cursors to the
2727 caller. This is useful to return multiple rows or columns,
2728 especially with very large result sets. To do this, the function
2729 opens the cursor and returns the cursor name to the caller (or simply
2730 opens the cursor using a portal name specified by or otherwise known
2731 to the caller). The caller can then fetch rows from the cursor. The
2732 cursor can be closed by the caller, or it will be closed automatically
2733 when the transaction closes.
2737 The portal name used for a cursor can be specified by the
2738 programmer or automatically generated. To specify a portal name,
2739 simply assign a string to the <type>refcursor</> variable before
2740 opening it. The string value of the <type>refcursor</> variable
2741 will be used by <command>OPEN</> as the name of the underlying portal.
2742 However, if the <type>refcursor</> variable is null,
2743 <command>OPEN</> automatically generates a name that does not
2744 conflict with any existing portal, and assigns it to the
2745 <type>refcursor</> variable.
2750 A bound cursor variable is initialized to the string value
2751 representing its name, so that the portal name is the same as
2752 the cursor variable name, unless the programmer overrides it
2753 by assignment before opening the cursor. But an unbound cursor
2754 variable defaults to the null value initially, so it will receive
2755 an automatically-generated unique name, unless overridden.
2760 The following example shows one way a cursor name can be supplied by
2764 CREATE TABLE test (col text);
2765 INSERT INTO test VALUES ('123');
2767 CREATE FUNCTION reffunc(refcursor) RETURNS refcursor AS '
2769 OPEN $1 FOR SELECT col FROM test;
2775 SELECT reffunc('funccursor');
2776 FETCH ALL IN funccursor;
2782 The following example uses automatic cursor name generation:
2785 CREATE FUNCTION reffunc2() RETURNS refcursor AS '
2789 OPEN ref FOR SELECT col FROM test;
2798 --------------------
2799 <unnamed cursor 1>
2802 FETCH ALL IN "<unnamed cursor 1>";
2808 The following example shows one way to return multiple cursors
2809 from a single function:
2812 CREATE FUNCTION myfunc(refcursor, refcursor) RETURNS SETOF refcursor AS $$
2814 OPEN $1 FOR SELECT * FROM table_1;
2816 OPEN $2 FOR SELECT * FROM table_2;
2819 $$ LANGUAGE plpgsql;
2821 -- need to be in a transaction to use cursors.
2824 SELECT * FROM myfunc('a', 'b');
2834 <sect2 id="plpgsql-cursor-for-loop">
2835 <title>Looping Through a Cursor's Result</title>
2838 There is a variant of the <command>FOR</> statement that allows
2839 iterating through the rows returned by a cursor. The syntax is:
2842 <optional> <<<replaceable>label</replaceable>>> </optional>
2843 FOR <replaceable>recordvar</replaceable> IN <replaceable>bound_cursor</replaceable> <optional> ( <replaceable>argument_values</replaceable> ) </optional> LOOP
2844 <replaceable>statements</replaceable>
2845 END LOOP <optional> <replaceable>label</replaceable> </optional>;
2848 The cursor variable must have been bound to some query when it was
2849 declared, and it <emphasis>cannot</> be open already. The
2850 <command>FOR</> statement automatically opens the cursor, and it closes
2851 the cursor again when the loop exits. A list of actual argument value
2852 expressions must appear if and only if the cursor was declared to take
2853 arguments. These values will be substituted in the query, in just
2854 the same way as during an <command>OPEN</>.
2855 The variable <replaceable>recordvar</replaceable> is automatically
2856 defined as type <type>record</> and exists only inside the loop (any
2857 existing definition of the variable name is ignored within the loop).
2858 Each row returned by the cursor is successively assigned to this
2859 record variable and the loop body is executed.
2865 <sect1 id="plpgsql-errors-and-messages">
2866 <title>Errors and Messages</title>
2869 <primary>RAISE</primary>
2873 <primary>reporting errors</primary>
2874 <secondary>in PL/PgSQL</secondary>
2878 Use the <command>RAISE</command> statement to report messages and
2882 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>;
2883 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>;
2884 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>;
2885 RAISE <optional> <replaceable class="parameter">level</replaceable> </optional> USING <replaceable class="parameter">option</replaceable> = <replaceable class="parameter">expression</replaceable> <optional>, ... </optional>;
2889 The <replaceable class="parameter">level</replaceable> option specifies
2890 the error severity. Allowed levels are <literal>DEBUG</literal>,
2891 <literal>LOG</literal>, <literal>INFO</literal>,
2892 <literal>NOTICE</literal>, <literal>WARNING</literal>,
2893 and <literal>EXCEPTION</literal>, with <literal>EXCEPTION</literal>
2895 <literal>EXCEPTION</literal> raises an error (which normally aborts the
2896 current transaction); the other levels only generate messages of different
2898 Whether messages of a particular priority are reported to the client,
2899 written to the server log, or both is controlled by the
2900 <xref linkend="guc-log-min-messages"> and
2901 <xref linkend="guc-client-min-messages"> configuration
2902 variables. See <xref linkend="runtime-config"> for more
2907 After <replaceable class="parameter">level</replaceable> if any,
2908 you can write a <replaceable class="parameter">format</replaceable>
2909 (which must be a simple string literal, not an expression). The
2910 format string specifies the error message text to be reported.
2911 The format string can be followed
2912 by optional argument expressions to be inserted into the message.
2913 Inside the format string, <literal>%</literal> is replaced by the
2914 string representation of the next optional argument's value. Write
2915 <literal>%%</literal> to emit a literal <literal>%</literal>.
2919 In this example, the value of <literal>v_job_id</> will replace the
2920 <literal>%</literal> in the string:
2922 RAISE NOTICE 'Calling cs_create_job(%)', v_job_id;
2927 You can attach additional information to the error report by writing
2928 <literal>USING</> followed by <replaceable
2929 class="parameter">option</replaceable> = <replaceable
2930 class="parameter">expression</replaceable> items. The allowed
2931 <replaceable class="parameter">option</replaceable> keywords are
2932 <literal>MESSAGE</>, <literal>DETAIL</>, <literal>HINT</>, and
2933 <literal>ERRCODE</>, while each <replaceable
2934 class="parameter">expression</replaceable> can be any string-valued
2936 <literal>MESSAGE</> sets the error message text (this option can't
2937 be used in the form of <command>RAISE</> that includes a format
2938 string before <literal>USING</>).
2939 <literal>DETAIL</> supplies an error detail message, while
2940 <literal>HINT</> supplies a hint message.
2941 <literal>ERRCODE</> specifies the error code (SQLSTATE) to report,
2942 either by condition name as shown in <xref linkend="errcodes-appendix">,
2943 or directly as a five-character SQLSTATE code.
2947 This example will abort the transaction with the given error message
2950 RAISE EXCEPTION 'Nonexistent ID --> %', user_id USING HINT = 'Please check your user id';
2955 These two examples show equivalent ways of setting the SQLSTATE:
2957 RAISE 'Duplicate user ID: %', user_id USING ERRCODE = 'unique_violation';
2958 RAISE 'Duplicate user ID: %', user_id USING ERRCODE = '23505';
2963 There is a second <command>RAISE</> syntax in which the main argument
2964 is the condition name or SQLSTATE to be reported, for example:
2966 RAISE division_by_zero;
2967 RAISE SQLSTATE '22012';
2969 In this syntax, <literal>USING</> can be used to supply a custom
2970 error message, detail, or hint. Another way to do the earlier
2973 RAISE unique_violation USING MESSAGE = 'Duplicate user ID: ' || user_id;
2978 Still another variant is to write <literal>RAISE USING</> or <literal>RAISE
2979 <replaceable class="parameter">level</replaceable> USING</> and put
2980 everything else into the <literal>USING</> list.
2984 The last variant of <command>RAISE</> has no parameters at all.
2985 This form can only be used inside a <literal>BEGIN</> block's
2986 <literal>EXCEPTION</> clause;
2987 it causes the error currently being handled to be re-thrown to the
2988 next enclosing block.
2992 If no condition name nor SQLSTATE is specified in a
2993 <command>RAISE EXCEPTION</command> command, the default is to use
2994 <literal>RAISE_EXCEPTION</> (<literal>P0001</>). If no message
2995 text is specified, the default is to use the condition name or
2996 SQLSTATE as message text.
3001 When specifying an error code by SQLSTATE code, you are not
3002 limited to the predefined error codes, but can select any
3003 error code consisting of five digits and/or upper-case ASCII
3004 letters, other than <literal>00000</>. It is recommended that
3005 you avoid throwing error codes that end in three zeroes, because
3006 these are category codes and can only be trapped by trapping
3013 <sect1 id="plpgsql-trigger">
3014 <title>Trigger Procedures</title>
3016 <indexterm zone="plpgsql-trigger">
3017 <primary>trigger</primary>
3018 <secondary>in PL/pgSQL</secondary>
3022 <application>PL/pgSQL</application> can be used to define trigger
3023 procedures. A trigger procedure is created with the
3024 <command>CREATE FUNCTION</> command, declaring it as a function with
3025 no arguments and a return type of <type>trigger</type>. Note that
3026 the function must be declared with no arguments even if it expects
3027 to receive arguments specified in <command>CREATE TRIGGER</> —
3028 trigger arguments are passed via <varname>TG_ARGV</>, as described
3033 When a <application>PL/pgSQL</application> function is called as a
3034 trigger, several special variables are created automatically in the
3035 top-level block. They are:
3039 <term><varname>NEW</varname></term>
3042 Data type <type>RECORD</type>; variable holding the new
3043 database row for <command>INSERT</>/<command>UPDATE</> operations in row-level
3044 triggers. This variable is <symbol>NULL</symbol> in statement-level triggers
3045 and for <command>DELETE</command> operations.
3051 <term><varname>OLD</varname></term>
3054 Data type <type>RECORD</type>; variable holding the old
3055 database row for <command>UPDATE</>/<command>DELETE</> operations in row-level
3056 triggers. This variable is <symbol>NULL</symbol> in statement-level triggers
3057 and for <command>INSERT</command> operations.
3063 <term><varname>TG_NAME</varname></term>
3066 Data type <type>name</type>; variable that contains the name of the trigger actually
3073 <term><varname>TG_WHEN</varname></term>
3076 Data type <type>text</type>; a string of either
3077 <literal>BEFORE</literal> or <literal>AFTER</literal>
3078 depending on the trigger's definition.
3084 <term><varname>TG_LEVEL</varname></term>
3087 Data type <type>text</type>; a string of either
3088 <literal>ROW</literal> or <literal>STATEMENT</literal>
3089 depending on the trigger's definition.
3095 <term><varname>TG_OP</varname></term>
3098 Data type <type>text</type>; a string of
3099 <literal>INSERT</literal>, <literal>UPDATE</literal>,
3100 <literal>DELETE</literal>, or <literal>TRUNCATE</>
3101 telling for which operation the trigger was fired.
3107 <term><varname>TG_RELID</varname></term>
3110 Data type <type>oid</type>; the object ID of the table that caused the
3117 <term><varname>TG_RELNAME</varname></term>
3120 Data type <type>name</type>; the name of the table that caused the trigger
3121 invocation. This is now deprecated, and could disappear in a future
3122 release. Use <literal>TG_TABLE_NAME</> instead.
3128 <term><varname>TG_TABLE_NAME</varname></term>
3131 Data type <type>name</type>; the name of the table that
3132 caused the trigger invocation.
3138 <term><varname>TG_TABLE_SCHEMA</varname></term>
3141 Data type <type>name</type>; the name of the schema of the
3142 table that caused the trigger invocation.
3148 <term><varname>TG_NARGS</varname></term>
3151 Data type <type>integer</type>; the number of arguments given to the trigger
3152 procedure in the <command>CREATE TRIGGER</command> statement.
3158 <term><varname>TG_ARGV[]</varname></term>
3161 Data type array of <type>text</type>; the arguments from
3162 the <command>CREATE TRIGGER</command> statement.
3163 The index counts from 0. Invalid
3164 indices (less than 0 or greater than or equal to <varname>tg_nargs</>) result in a null value.
3172 A trigger function must return either <symbol>NULL</symbol> or a
3173 record/row value having exactly the structure of the table the
3174 trigger was fired for.
3178 Row-level triggers fired <literal>BEFORE</> can return null to signal the
3179 trigger manager to skip the rest of the operation for this row
3180 (i.e., subsequent triggers are not fired, and the
3181 <command>INSERT</>/<command>UPDATE</>/<command>DELETE</> does not occur
3182 for this row). If a nonnull
3183 value is returned then the operation proceeds with that row value.
3184 Returning a row value different from the original value
3185 of <varname>NEW</> alters the row that will be inserted or updated
3186 (but has no direct effect in the <command>DELETE</> case).
3187 To alter the row to be stored, it is possible to replace single values
3188 directly in <varname>NEW</> and return the modified <varname>NEW</>,
3189 or to build a complete new record/row to return.
3193 The return value of a <literal>BEFORE</> or <literal>AFTER</>
3194 statement-level trigger or an <literal>AFTER</> row-level trigger is
3195 always ignored; it might as well be null. However, any of these types of
3196 triggers might still abort the entire operation by raising an error.
3200 <xref linkend="plpgsql-trigger-example"> shows an example of a
3201 trigger procedure in <application>PL/pgSQL</application>.
3204 <example id="plpgsql-trigger-example">
3205 <title>A <application>PL/pgSQL</application> Trigger Procedure</title>
3208 This example trigger ensures that any time a row is inserted or updated
3209 in the table, the current user name and time are stamped into the
3210 row. And it checks that an employee's name is given and that the
3211 salary is a positive value.
3218 last_date timestamp,
3222 CREATE FUNCTION emp_stamp() RETURNS trigger AS $emp_stamp$
3224 -- Check that empname and salary are given
3225 IF NEW.empname IS NULL THEN
3226 RAISE EXCEPTION 'empname cannot be null';
3228 IF NEW.salary IS NULL THEN
3229 RAISE EXCEPTION '% cannot have null salary', NEW.empname;
3232 -- Who works for us when she must pay for it?
3233 IF NEW.salary < 0 THEN
3234 RAISE EXCEPTION '% cannot have a negative salary', NEW.empname;
3237 -- Remember who changed the payroll when
3238 NEW.last_date := current_timestamp;
3239 NEW.last_user := current_user;
3242 $emp_stamp$ LANGUAGE plpgsql;
3244 CREATE TRIGGER emp_stamp BEFORE INSERT OR UPDATE ON emp
3245 FOR EACH ROW EXECUTE PROCEDURE emp_stamp();
3250 Another way to log changes to a table involves creating a new table that
3251 holds a row for each insert, update, or delete that occurs. This approach
3252 can be thought of as auditing changes to a table.
3253 <xref linkend="plpgsql-trigger-audit-example"> shows an example of an
3254 audit trigger procedure in <application>PL/pgSQL</application>.
3257 <example id="plpgsql-trigger-audit-example">
3258 <title>A <application>PL/pgSQL</application> Trigger Procedure For Auditing</title>
3261 This example trigger ensures that any insert, update or delete of a row
3262 in the <literal>emp</literal> table is recorded (i.e., audited) in the <literal>emp_audit</literal> table.
3263 The current time and user name are stamped into the row, together with
3264 the type of operation performed on it.
3269 empname text NOT NULL,
3273 CREATE TABLE emp_audit(
3274 operation char(1) NOT NULL,
3275 stamp timestamp NOT NULL,
3276 userid text NOT NULL,
3277 empname text NOT NULL,
3281 CREATE OR REPLACE FUNCTION process_emp_audit() RETURNS TRIGGER AS $emp_audit$
3284 -- Create a row in emp_audit to reflect the operation performed on emp,
3285 -- make use of the special variable TG_OP to work out the operation.
3287 IF (TG_OP = 'DELETE') THEN
3288 INSERT INTO emp_audit SELECT 'D', now(), user, OLD.*;
3290 ELSIF (TG_OP = 'UPDATE') THEN
3291 INSERT INTO emp_audit SELECT 'U', now(), user, NEW.*;
3293 ELSIF (TG_OP = 'INSERT') THEN
3294 INSERT INTO emp_audit SELECT 'I', now(), user, NEW.*;
3297 RETURN NULL; -- result is ignored since this is an AFTER trigger
3299 $emp_audit$ LANGUAGE plpgsql;
3301 CREATE TRIGGER emp_audit
3302 AFTER INSERT OR UPDATE OR DELETE ON emp
3303 FOR EACH ROW EXECUTE PROCEDURE process_emp_audit();
3308 One use of triggers is to maintain a summary table
3309 of another table. The resulting summary can be used in place of the
3310 original table for certain queries — often with vastly reduced run
3312 This technique is commonly used in Data Warehousing, where the tables
3313 of measured or observed data (called fact tables) might be extremely large.
3314 <xref linkend="plpgsql-trigger-summary-example"> shows an example of a
3315 trigger procedure in <application>PL/pgSQL</application> that maintains
3316 a summary table for a fact table in a data warehouse.
3320 <example id="plpgsql-trigger-summary-example">
3321 <title>A <application>PL/pgSQL</application> Trigger Procedure For Maintaining A Summary Table</title>
3324 The schema detailed here is partly based on the <emphasis>Grocery Store
3325 </emphasis> example from <emphasis>The Data Warehouse Toolkit</emphasis>
3331 -- Main tables - time dimension and sales fact.
3333 CREATE TABLE time_dimension (
3334 time_key integer NOT NULL,
3335 day_of_week integer NOT NULL,
3336 day_of_month integer NOT NULL,
3337 month integer NOT NULL,
3338 quarter integer NOT NULL,
3339 year integer NOT NULL
3341 CREATE UNIQUE INDEX time_dimension_key ON time_dimension(time_key);
3343 CREATE TABLE sales_fact (
3344 time_key integer NOT NULL,
3345 product_key integer NOT NULL,
3346 store_key integer NOT NULL,
3347 amount_sold numeric(12,2) NOT NULL,
3348 units_sold integer NOT NULL,
3349 amount_cost numeric(12,2) NOT NULL
3351 CREATE INDEX sales_fact_time ON sales_fact(time_key);
3354 -- Summary table - sales by time.
3356 CREATE TABLE sales_summary_bytime (
3357 time_key integer NOT NULL,
3358 amount_sold numeric(15,2) NOT NULL,
3359 units_sold numeric(12) NOT NULL,
3360 amount_cost numeric(15,2) NOT NULL
3362 CREATE UNIQUE INDEX sales_summary_bytime_key ON sales_summary_bytime(time_key);
3365 -- Function and trigger to amend summarized column(s) on UPDATE, INSERT, DELETE.
3367 CREATE OR REPLACE FUNCTION maint_sales_summary_bytime() RETURNS TRIGGER AS $maint_sales_summary_bytime$
3369 delta_time_key integer;
3370 delta_amount_sold numeric(15,2);
3371 delta_units_sold numeric(12);
3372 delta_amount_cost numeric(15,2);
3375 -- Work out the increment/decrement amount(s).
3376 IF (TG_OP = 'DELETE') THEN
3378 delta_time_key = OLD.time_key;
3379 delta_amount_sold = -1 * OLD.amount_sold;
3380 delta_units_sold = -1 * OLD.units_sold;
3381 delta_amount_cost = -1 * OLD.amount_cost;
3383 ELSIF (TG_OP = 'UPDATE') THEN
3385 -- forbid updates that change the time_key -
3386 -- (probably not too onerous, as DELETE + INSERT is how most
3387 -- changes will be made).
3388 IF ( OLD.time_key != NEW.time_key) THEN
3389 RAISE EXCEPTION 'Update of time_key : % -> % not allowed', OLD.time_key, NEW.time_key;
3392 delta_time_key = OLD.time_key;
3393 delta_amount_sold = NEW.amount_sold - OLD.amount_sold;
3394 delta_units_sold = NEW.units_sold - OLD.units_sold;
3395 delta_amount_cost = NEW.amount_cost - OLD.amount_cost;
3397 ELSIF (TG_OP = 'INSERT') THEN
3399 delta_time_key = NEW.time_key;
3400 delta_amount_sold = NEW.amount_sold;
3401 delta_units_sold = NEW.units_sold;
3402 delta_amount_cost = NEW.amount_cost;
3407 -- Insert or update the summary row with the new values.
3408 <<insert_update>>
3410 UPDATE sales_summary_bytime
3411 SET amount_sold = amount_sold + delta_amount_sold,
3412 units_sold = units_sold + delta_units_sold,
3413 amount_cost = amount_cost + delta_amount_cost
3414 WHERE time_key = delta_time_key;
3416 EXIT insert_update WHEN found;
3419 INSERT INTO sales_summary_bytime (
3434 WHEN UNIQUE_VIOLATION THEN
3437 END LOOP insert_update;
3442 $maint_sales_summary_bytime$ LANGUAGE plpgsql;
3444 CREATE TRIGGER maint_sales_summary_bytime
3445 AFTER INSERT OR UPDATE OR DELETE ON sales_fact
3446 FOR EACH ROW EXECUTE PROCEDURE maint_sales_summary_bytime();
3448 INSERT INTO sales_fact VALUES(1,1,1,10,3,15);
3449 INSERT INTO sales_fact VALUES(1,2,1,20,5,35);
3450 INSERT INTO sales_fact VALUES(2,2,1,40,15,135);
3451 INSERT INTO sales_fact VALUES(2,3,1,10,1,13);
3452 SELECT * FROM sales_summary_bytime;
3453 DELETE FROM sales_fact WHERE product_key = 1;
3454 SELECT * FROM sales_summary_bytime;
3455 UPDATE sales_fact SET units_sold = units_sold * 2;
3456 SELECT * FROM sales_summary_bytime;
3462 <sect1 id="plpgsql-implementation">
3463 <title><application>PL/pgSQL</> Under the Hood</title>
3466 This section discusses some implementation details that are
3467 frequently important for <application>PL/pgSQL</> users to know.
3470 <sect2 id="plpgsql-var-subst">
3471 <title>Variable Substitution</title>
3474 When <application>PL/pgSQL</> prepares a SQL statement or expression
3475 for execution, any <application>PL/pgSQL</application> variable name
3476 appearing in the statement or expression is replaced by a parameter symbol,
3477 <literal>$<replaceable>n</replaceable></literal>. The current value
3478 of the variable is then provided as the value for the parameter whenever
3479 the statement or expression is executed. As an example, consider the
3482 CREATE FUNCTION logfunc(logtxt text) RETURNS void AS $$
3484 curtime timestamp := now();
3486 INSERT INTO logtable VALUES (logtxt, curtime);
3488 $$ LANGUAGE plpgsql;
3490 The <command>INSERT</> statement will effectively be processed as
3492 PREPARE <replaceable>statement_name</>(text, timestamp) AS
3493 INSERT INTO logtable VALUES ($1, $2);
3495 followed on each execution by <command>EXECUTE</> with the current
3496 actual values of the two variables. (Note: here we are speaking of
3497 the main SQL engine's
3498 <xref linkend="sql-execute" endterm="sql-execute-title"> command,
3499 not <application>PL/pgSQL</application>'s <command>EXECUTE</>.)
3503 <emphasis>The substitution mechanism will replace any token that matches a
3504 known variable's name.</> This poses various traps for the unwary.
3505 For example, it is a bad idea
3506 to use a variable name that is the same as any table or column name
3507 that you need to reference in queries within the function, because
3508 what you think is a table or column name will still get replaced.
3509 In the above example, suppose that <structname>logtable</> has
3510 column names <structfield>logtxt</> and <structfield>logtime</>,
3511 and we try to write the <command>INSERT</> as
3513 INSERT INTO logtable (logtxt, logtime) VALUES (logtxt, curtime);
3515 This will be fed to the main SQL parser as
3517 INSERT INTO logtable ($1, logtime) VALUES ($1, $2);
3519 resulting in a syntax error like this:
3521 ERROR: syntax error at or near "$1"
3522 LINE 1: INSERT INTO logtable ( $1 , logtime) VALUES ( $1 , $2 )
3524 QUERY: INSERT INTO logtable ( $1 , logtime) VALUES ( $1 , $2 )
3525 CONTEXT: SQL statement in PL/PgSQL function "logfunc2" near line 5
3530 This example is fairly easy to diagnose, since it leads to an
3531 obvious syntax error. Much nastier are cases where the substitution
3532 is syntactically permissible, since the only symptom may be misbehavior
3533 of the function. In one case, a user wrote something like this:
3540 FOR val IN SELECT val FROM table WHERE key = search_key LOOP ...
3542 and wondered why all his table entries seemed to be NULL. Of course
3543 what happened here was that the query became
3545 SELECT $1 FROM table WHERE key = $2
3547 and thus it was just an expensive way of assigning <literal>val</>'s
3548 current value back to itself for each row.
3552 A commonly used coding rule for avoiding such traps is to use a
3553 different naming convention for <application>PL/pgSQL</application>
3554 variables than you use for table and column names. For example,
3555 if all your variables are named
3556 <literal>v_<replaceable>something</></literal> while none of your
3557 table or column names start with <literal>v_</>, you're pretty safe.
3561 Another workaround is to use qualified (dotted) names for SQL entities.
3562 For instance we could safely have written the above example as
3564 FOR val IN SELECT table.val FROM table WHERE key = search_key LOOP ...
3566 because <application>PL/pgSQL</application> will not substitute a
3567 variable for a trailing component of a qualified name.
3568 However this solution does not work in every case — you can't
3569 qualify a name in an <command>INSERT</>'s column name list, for instance.
3570 Another point is that record and row variable names will be matched to
3571 the first components of qualified names, so a qualified SQL name is
3572 still vulnerable in some cases.
3573 In such cases choosing a non-conflicting variable name is the only way.
3577 Another technique you can use is to attach a label to the block in
3578 which your variables are declared, and then qualify the variable names
3579 in your SQL commands (see <xref linkend="plpgsql-structure">).
3587 UPDATE table SET col = pl.val WHERE ...
3589 This is not in itself a solution to the problem of conflicts,
3590 since an unqualified name in a SQL command is still at risk of being
3591 interpreted the <quote>wrong</> way. But it is useful for clarifying
3592 the intent of potentially-ambiguous code.
3596 Variable substitution does not happen in the command string given
3597 to <command>EXECUTE</> or one of its variants. If you need to
3598 insert a varying value into such a command, do so as part of
3599 constructing the string value, as illustrated in
3600 <xref linkend="plpgsql-statements-executing-dyn">.
3604 Variable substitution currently works only in <command>SELECT</>,
3605 <command>INSERT</>, <command>UPDATE</>, and <command>DELETE</> commands,
3606 because the main SQL engine allows parameter symbols only in these
3607 commands. To use a non-constant name or value in other statement
3608 types (generically called utility statements), you must construct
3609 the utility statement as a string and <command>EXECUTE</> it.
3614 <sect2 id="plpgsql-plan-caching">
3615 <title>Plan Caching</title>
3618 The <application>PL/pgSQL</> interpreter parses the function's source
3619 text and produces an internal binary instruction tree the first time the
3620 function is called (within each session). The instruction tree
3621 fully translates the
3622 <application>PL/pgSQL</> statement structure, but individual
3623 <acronym>SQL</acronym> expressions and <acronym>SQL</acronym> commands
3624 used in the function are not translated immediately.
3628 As each expression and <acronym>SQL</acronym> command is first
3629 executed in the function, the <application>PL/pgSQL</> interpreter
3630 creates a prepared execution plan (using the
3631 <acronym>SPI</acronym> manager's <function>SPI_prepare</function>
3632 and <function>SPI_saveplan</function>
3633 functions).<indexterm><primary>preparing a query</><secondary>in
3634 PL/pgSQL</></> Subsequent visits to that expression or command
3635 reuse the prepared plan. Thus, a function with conditional code
3636 that contains many statements for which execution plans might be
3637 required will only prepare and save those plans that are really
3638 used during the lifetime of the database connection. This can
3639 substantially reduce the total amount of time required to parse
3640 and generate execution plans for the statements in a
3641 <application>PL/pgSQL</> function. A disadvantage is that errors
3642 in a specific expression or command cannot be detected until that
3643 part of the function is reached in execution. (Trivial syntax
3644 errors will be detected during the initial parsing pass, but
3645 anything deeper will not be detected until execution.)
3649 Once <application>PL/pgSQL</> has made an execution plan for a particular
3650 command in a function, it will reuse that plan for the life of the
3651 database connection. This is usually a win for performance, but it
3652 can cause some problems if you dynamically
3653 alter your database schema. For example:
3656 CREATE FUNCTION populate() RETURNS integer AS $$
3660 PERFORM my_function();
3662 $$ LANGUAGE plpgsql;
3665 If you execute the above function, it will reference the OID for
3666 <function>my_function()</function> in the execution plan produced for
3667 the <command>PERFORM</command> statement. Later, if you
3668 drop and recreate <function>my_function()</function>, then
3669 <function>populate()</function> will not be able to find
3670 <function>my_function()</function> anymore. You would then have to
3671 start a new database session so that <function>populate()</function>
3672 will be compiled afresh, before it will work again. You can avoid
3673 this problem by using <command>CREATE OR REPLACE FUNCTION</command>
3674 when updating the definition of
3675 <function>my_function</function>, since when a function is
3676 <quote>replaced</quote>, its OID is not changed.
3681 In <productname>PostgreSQL</productname> 8.3 and later, saved plans
3682 will be replaced whenever any schema changes have occurred to any
3683 tables they reference. This eliminates one of the major disadvantages
3684 of saved plans. However, there is no such mechanism for function
3685 references, and thus the above example involving a reference to a
3686 deleted function is still valid.
3691 Because <application>PL/pgSQL</application> saves execution plans
3692 in this way, SQL commands that appear directly in a
3693 <application>PL/pgSQL</application> function must refer to the
3694 same tables and columns on every execution; that is, you cannot use
3695 a parameter as the name of a table or column in an SQL command. To get
3696 around this restriction, you can construct dynamic commands using
3697 the <application>PL/pgSQL</application> <command>EXECUTE</command>
3698 statement — at the price of constructing a new execution plan on
3703 Another important point is that the prepared plans are parameterized
3704 to allow the values of <application>PL/pgSQL</application> variables
3705 to change from one use to the next, as discussed in detail above.
3706 Sometimes this means that a plan is less efficient than it would be
3707 if generated for a specific variable value. As an example, consider
3709 SELECT * INTO myrec FROM dictionary WHERE word LIKE search_term;
3711 where <literal>search_term</> is a <application>PL/pgSQL</application>
3712 variable. The cached plan for this query will never use an index on
3713 <structfield>word</>, since the planner cannot assume that the
3714 <literal>LIKE</> pattern will be left-anchored at run time. To use
3715 an index the query must be planned with a specific constant
3716 <literal>LIKE</> pattern provided. This is another situation where
3717 <command>EXECUTE</command> can be used to force a new plan to be
3718 generated for each execution.
3722 The mutable nature of record variables presents another problem in this
3723 connection. When fields of a record variable are used in
3724 expressions or statements, the data types of the fields must not
3725 change from one call of the function to the next, since each
3726 expression will be planned using the data type that is present
3727 when the expression is first reached. <command>EXECUTE</command> can be
3728 used to get around this problem when necessary.
3732 If the same function is used as a trigger for more than one table,
3733 <application>PL/pgSQL</application> prepares and caches plans
3734 independently for each such table — that is, there is a cache
3735 for each trigger function and table combination, not just for each
3736 function. This alleviates some of the problems with varying
3737 data types; for instance, a trigger function will be able to work
3738 successfully with a column named <literal>key</> even if it happens
3739 to have different types in different tables.
3743 Likewise, functions having polymorphic argument types have a separate
3744 plan cache for each combination of actual argument types they have been
3745 invoked for, so that data type differences do not cause unexpected
3750 Plan caching can sometimes have surprising effects on the interpretation
3751 of time-sensitive values. For example there
3752 is a difference between what these two functions do:
3755 CREATE FUNCTION logfunc1(logtxt text) RETURNS void AS $$
3757 INSERT INTO logtable VALUES (logtxt, 'now');
3759 $$ LANGUAGE plpgsql;
3765 CREATE FUNCTION logfunc2(logtxt text) RETURNS void AS $$
3770 INSERT INTO logtable VALUES (logtxt, curtime);
3772 $$ LANGUAGE plpgsql;
3777 In the case of <function>logfunc1</function>, the
3778 <productname>PostgreSQL</productname> main parser knows when
3779 preparing the plan for the <command>INSERT</command> that the
3780 string <literal>'now'</literal> should be interpreted as
3781 <type>timestamp</type>, because the target column of
3782 <classname>logtable</classname> is of that type. Thus,
3783 <literal>'now'</literal> will be converted to a constant when the
3784 <command>INSERT</command> is planned, and then used in all
3785 invocations of <function>logfunc1</function> during the lifetime
3786 of the session. Needless to say, this isn't what the programmer
3791 In the case of <function>logfunc2</function>, the
3792 <productname>PostgreSQL</productname> main parser does not know
3793 what type <literal>'now'</literal> should become and therefore
3794 it returns a data value of type <type>text</type> containing the string
3795 <literal>now</literal>. During the ensuing assignment
3796 to the local variable <varname>curtime</varname>, the
3797 <application>PL/pgSQL</application> interpreter casts this
3798 string to the <type>timestamp</type> type by calling the
3799 <function>text_out</function> and <function>timestamp_in</function>
3800 functions for the conversion. So, the computed time stamp is updated
3801 on each execution as the programmer expects.
3808 <sect1 id="plpgsql-development-tips">
3809 <title>Tips for Developing in <application>PL/pgSQL</application></title>
3812 One good way to develop in
3813 <application>PL/pgSQL</> is to use the text editor of your
3814 choice to create your functions, and in another window, use
3815 <application>psql</application> to load and test those functions.
3816 If you are doing it this way, it
3817 is a good idea to write the function using <command>CREATE OR
3818 REPLACE FUNCTION</>. That way you can just reload the file to update
3819 the function definition. For example:
3821 CREATE OR REPLACE FUNCTION testfunc(integer) RETURNS integer AS $$
3823 $$ LANGUAGE plpgsql;
3828 While running <application>psql</application>, you can load or reload such
3829 a function definition file with:
3833 and then immediately issue SQL commands to test the function.
3837 Another good way to develop in <application>PL/pgSQL</> is with a
3838 GUI database access tool that facilitates development in a
3839 procedural language. One example of such as a tool is
3840 <application>pgAdmin</>, although others exist. These tools often
3841 provide convenient features such as escaping single quotes and
3842 making it easier to recreate and debug functions.
3845 <sect2 id="plpgsql-quote-tips">
3846 <title>Handling of Quotation Marks</title>
3849 The code of a <application>PL/pgSQL</> function is specified in
3850 <command>CREATE FUNCTION</command> as a string literal. If you
3851 write the string literal in the ordinary way with surrounding
3852 single quotes, then any single quotes inside the function body
3853 must be doubled; likewise any backslashes must be doubled (assuming
3854 escape string syntax is used).
3855 Doubling quotes is at best tedious, and in more complicated cases
3856 the code can become downright incomprehensible, because you can
3857 easily find yourself needing half a dozen or more adjacent quote marks.
3858 It's recommended that you instead write the function body as a
3859 <quote>dollar-quoted</> string literal (see <xref
3860 linkend="sql-syntax-dollar-quoting">). In the dollar-quoting
3861 approach, you never double any quote marks, but instead take care to
3862 choose a different dollar-quoting delimiter for each level of
3863 nesting you need. For example, you might write the <command>CREATE
3864 FUNCTION</command> command as:
3866 CREATE OR REPLACE FUNCTION testfunc(integer) RETURNS integer AS $PROC$
3868 $PROC$ LANGUAGE plpgsql;
3870 Within this, you might use quote marks for simple literal strings in
3871 SQL commands and <literal>$$</> to delimit fragments of SQL commands
3872 that you are assembling as strings. If you need to quote text that
3873 includes <literal>$$</>, you could use <literal>$Q$</>, and so on.
3877 The following chart shows what you have to do when writing quote
3878 marks without dollar quoting. It might be useful when translating
3879 pre-dollar quoting code into something more comprehensible.
3884 <term>1 quotation mark</term>
3887 To begin and end the function body, for example:
3889 CREATE FUNCTION foo() RETURNS integer AS '
3893 Anywhere within a single-quoted function body, quote marks
3894 <emphasis>must</> appear in pairs.
3900 <term>2 quotation marks</term>
3903 For string literals inside the function body, for example:
3905 a_output := ''Blah'';
3906 SELECT * FROM users WHERE f_name=''foobar'';
3908 In the dollar-quoting approach, you'd just write:
3911 SELECT * FROM users WHERE f_name='foobar';
3913 which is exactly what the <application>PL/pgSQL</> parser would see
3920 <term>4 quotation marks</term>
3923 When you need a single quotation mark in a string constant inside the
3924 function body, for example:
3926 a_output := a_output || '' AND name LIKE ''''foobar'''' AND xyz''
3928 The value actually appended to <literal>a_output</literal> would be:
3929 <literal> AND name LIKE 'foobar' AND xyz</literal>.
3932 In the dollar-quoting approach, you'd write:
3934 a_output := a_output || $$ AND name LIKE 'foobar' AND xyz$$
3936 being careful that any dollar-quote delimiters around this are not
3937 just <literal>$$</>.
3943 <term>6 quotation marks</term>
3946 When a single quotation mark in a string inside the function body is
3947 adjacent to the end of that string constant, for example:
3949 a_output := a_output || '' AND name LIKE ''''foobar''''''
3951 The value appended to <literal>a_output</literal> would then be:
3952 <literal> AND name LIKE 'foobar'</literal>.
3955 In the dollar-quoting approach, this becomes:
3957 a_output := a_output || $$ AND name LIKE 'foobar'$$
3964 <term>10 quotation marks</term>
3967 When you want two single quotation marks in a string constant (which
3968 accounts for 8 quotation marks) and this is adjacent to the end of that
3969 string constant (2 more). You will probably only need that if
3970 you are writing a function that generates other functions, as in
3971 <xref linkend="plpgsql-porting-ex2">.
3974 a_output := a_output || '' if v_'' ||
3975 referrer_keys.kind || '' like ''''''''''
3976 || referrer_keys.key_string || ''''''''''
3977 then return '''''' || referrer_keys.referrer_type
3978 || ''''''; end if;'';
3980 The value of <literal>a_output</literal> would then be:
3982 if v_... like ''...'' then return ''...''; end if;
3986 In the dollar-quoting approach, this becomes:
3988 a_output := a_output || $$ if v_$$ || referrer_keys.kind || $$ like '$$
3989 || referrer_keys.key_string || $$'
3990 then return '$$ || referrer_keys.referrer_type
3993 where we assume we only need to put single quote marks into
3994 <literal>a_output</literal>, because it will be re-quoted before use.
4003 <!-- **** Porting from Oracle PL/SQL **** -->
4005 <sect1 id="plpgsql-porting">
4006 <title>Porting from <productname>Oracle</productname> PL/SQL</title>
4008 <indexterm zone="plpgsql-porting">
4009 <primary>Oracle</primary>
4010 <secondary>porting from PL/SQL to PL/pgSQL</secondary>
4013 <indexterm zone="plpgsql-porting">
4014 <primary>PL/SQL (Oracle)</primary>
4015 <secondary>porting to PL/pgSQL</secondary>
4019 This section explains differences between
4020 <productname>PostgreSQL</>'s <application>PL/pgSQL</application>
4021 language and Oracle's <application>PL/SQL</application> language,
4022 to help developers who port applications from
4023 <trademark class="registered">Oracle</> to <productname>PostgreSQL</>.
4027 <application>PL/pgSQL</application> is similar to PL/SQL in many
4028 aspects. It is a block-structured, imperative language, and all
4029 variables have to be declared. Assignments, loops, conditionals
4030 are similar. The main differences you should keep in mind when
4031 porting from <application>PL/SQL</> to
4032 <application>PL/pgSQL</application> are:
4037 There are no default values for parameters in <productname>PostgreSQL</>.
4043 You can overload function names in <productname>PostgreSQL</>. This is
4044 often used to work around the lack of default parameters.
4050 If a name used in a SQL command could be either a column name of a
4051 table or a reference to a variable of the function,
4052 <application>PL/SQL</> treats it as a column name, while
4053 <application>PL/pgSQL</> treats it as a variable name. It's best
4054 to avoid such ambiguities in the first place, but if necessary you
4055 can fix them by properly qualifying the ambiguous name.
4056 (See <xref linkend="plpgsql-var-subst">.)
4062 In <productname>PostgreSQL</> the function body must be written as
4063 a string literal. Therefore you need to use dollar quoting or escape
4064 single quotes in the function body. (See <xref
4065 linkend="plpgsql-quote-tips">.)
4071 Instead of packages, use schemas to organize your functions
4078 Since there are no packages, there are no package-level variables
4079 either. This is somewhat annoying. You can keep per-session state
4080 in temporary tables instead.
4086 Integer <command>FOR</> loops with <literal>REVERSE</> work
4087 differently: <application>PL/SQL</> counts down from the second
4088 number to the first, while <application>PL/pgSQL</> counts down
4089 from the first number to the second, requiring the loop bounds
4090 to be swapped when porting. This incompatibility is unfortunate
4091 but is unlikely to be changed. (See <xref
4092 linkend="plpgsql-integer-for">.)
4098 <command>FOR</> loops over queries (other than cursors) also work
4099 differently: the target variable(s) must have been declared,
4100 whereas <application>PL/SQL</> always declares them implicitly.
4101 An advantage of this is that the variable values are still accessible
4102 after the loop exits.
4108 There are various notational differences for the use of cursor
4117 <title>Porting Examples</title>
4120 <xref linkend="pgsql-porting-ex1"> shows how to port a simple
4121 function from <application>PL/SQL</> to <application>PL/pgSQL</>.
4124 <example id="pgsql-porting-ex1">
4125 <title>Porting a Simple Function from <application>PL/SQL</> to <application>PL/pgSQL</></title>
4128 Here is an <productname>Oracle</productname> <application>PL/SQL</> function:
4130 CREATE OR REPLACE FUNCTION cs_fmt_browser_version(v_name varchar,
4134 IF v_version IS NULL THEN
4137 RETURN v_name || '/' || v_version;
4145 Let's go through this function and see the differences compared to
4146 <application>PL/pgSQL</>:
4151 The <literal>RETURN</literal> key word in the function
4152 prototype (not the function body) becomes
4153 <literal>RETURNS</literal> in
4154 <productname>PostgreSQL</productname>.
4155 Also, <literal>IS</> becomes <literal>AS</>, and you need to
4156 add a <literal>LANGUAGE</> clause because <application>PL/pgSQL</>
4157 is not the only possible function language.
4163 In <productname>PostgreSQL</>, the function body is considered
4164 to be a string literal, so you need to use quote marks or dollar
4165 quotes around it. This substitutes for the terminating <literal>/</>
4166 in the Oracle approach.
4172 The <literal>show errors</literal> command does not exist in
4173 <productname>PostgreSQL</>, and is not needed since errors are
4174 reported automatically.
4181 This is how this function would look when ported to
4182 <productname>PostgreSQL</>:
4185 CREATE OR REPLACE FUNCTION cs_fmt_browser_version(v_name varchar,
4187 RETURNS varchar AS $$
4189 IF v_version IS NULL THEN
4192 RETURN v_name || '/' || v_version;
4194 $$ LANGUAGE plpgsql;
4200 <xref linkend="plpgsql-porting-ex2"> shows how to port a
4201 function that creates another function and how to handle the
4202 ensuing quoting problems.
4205 <example id="plpgsql-porting-ex2">
4206 <title>Porting a Function that Creates Another Function from <application>PL/SQL</> to <application>PL/pgSQL</></title>
4209 The following procedure grabs rows from a
4210 <command>SELECT</command> statement and builds a large function
4211 with the results in <literal>IF</literal> statements, for the
4216 This is the Oracle version:
4218 CREATE OR REPLACE PROCEDURE cs_update_referrer_type_proc IS
4219 CURSOR referrer_keys IS
4220 SELECT * FROM cs_referrer_keys
4222 func_cmd VARCHAR(4000);
4224 func_cmd := 'CREATE OR REPLACE FUNCTION cs_find_referrer_type(v_host IN VARCHAR,
4225 v_domain IN VARCHAR, v_url IN VARCHAR) RETURN VARCHAR IS BEGIN';
4227 FOR referrer_key IN referrer_keys LOOP
4228 func_cmd := func_cmd ||
4229 ' IF v_' || referrer_key.kind
4230 || ' LIKE ''' || referrer_key.key_string
4231 || ''' THEN RETURN ''' || referrer_key.referrer_type
4235 func_cmd := func_cmd || ' RETURN NULL; END;';
4237 EXECUTE IMMEDIATE func_cmd;
4245 Here is how this function would end up in <productname>PostgreSQL</>:
4247 CREATE OR REPLACE FUNCTION cs_update_referrer_type_proc() RETURNS void AS $func$
4249 CURSOR referrer_keys IS
4250 SELECT * FROM cs_referrer_keys
4255 func_body := 'BEGIN';
4257 FOR referrer_key IN referrer_keys LOOP
4258 func_body := func_body ||
4259 ' IF v_' || referrer_key.kind
4260 || ' LIKE ' || quote_literal(referrer_key.key_string)
4261 || ' THEN RETURN ' || quote_literal(referrer_key.referrer_type)
4265 func_body := func_body || ' RETURN NULL; END;';
4268 'CREATE OR REPLACE FUNCTION cs_find_referrer_type(v_host varchar,
4271 RETURNS varchar AS '
4272 || quote_literal(func_body)
4273 || ' LANGUAGE plpgsql;' ;
4277 $func$ LANGUAGE plpgsql;
4279 Notice how the body of the function is built separately and passed
4280 through <literal>quote_literal</> to double any quote marks in it. This
4281 technique is needed because we cannot safely use dollar quoting for
4282 defining the new function: we do not know for sure what strings will
4283 be interpolated from the <structfield>referrer_key.key_string</> field.
4284 (We are assuming here that <structfield>referrer_key.kind</> can be
4285 trusted to always be <literal>host</>, <literal>domain</>, or
4286 <literal>url</>, but <structfield>referrer_key.key_string</> might be
4287 anything, in particular it might contain dollar signs.) This function
4288 is actually an improvement on the Oracle original, because it will
4289 not generate broken code when <structfield>referrer_key.key_string</> or
4290 <structfield>referrer_key.referrer_type</> contain quote marks.
4295 <xref linkend="plpgsql-porting-ex3"> shows how to port a function
4296 with <literal>OUT</> parameters and string manipulation.
4297 <productname>PostgreSQL</> does not have a built-in
4298 <function>instr</function> function, but you can create one
4299 using a combination of other
4300 functions.<indexterm><primary>instr</></indexterm> In <xref
4301 linkend="plpgsql-porting-appendix"> there is a
4302 <application>PL/pgSQL</application> implementation of
4303 <function>instr</function> that you can use to make your porting
4307 <example id="plpgsql-porting-ex3">
4308 <title>Porting a Procedure With String Manipulation and
4309 <literal>OUT</> Parameters from <application>PL/SQL</> to
4310 <application>PL/pgSQL</></title>
4313 The following <productname>Oracle</productname> PL/SQL procedure is used
4314 to parse a URL and return several elements (host, path, and query).
4318 This is the Oracle version:
4320 CREATE OR REPLACE PROCEDURE cs_parse_url(
4322 v_host OUT VARCHAR, -- This will be passed back
4323 v_path OUT VARCHAR, -- This one too
4324 v_query OUT VARCHAR) -- And this one
4332 a_pos1 := instr(v_url, '//');
4337 a_pos2 := instr(v_url, '/', a_pos1 + 2);
4339 v_host := substr(v_url, a_pos1 + 2);
4344 v_host := substr(v_url, a_pos1 + 2, a_pos2 - a_pos1 - 2);
4345 a_pos1 := instr(v_url, '?', a_pos2 + 1);
4348 v_path := substr(v_url, a_pos2);
4352 v_path := substr(v_url, a_pos2, a_pos1 - a_pos2);
4353 v_query := substr(v_url, a_pos1 + 1);
4361 Here is a possible translation into <application>PL/pgSQL</>:
4363 CREATE OR REPLACE FUNCTION cs_parse_url(
4365 v_host OUT VARCHAR, -- This will be passed back
4366 v_path OUT VARCHAR, -- This one too
4367 v_query OUT VARCHAR) -- And this one
4376 a_pos1 := instr(v_url, '//');
4381 a_pos2 := instr(v_url, '/', a_pos1 + 2);
4383 v_host := substr(v_url, a_pos1 + 2);
4388 v_host := substr(v_url, a_pos1 + 2, a_pos2 - a_pos1 - 2);
4389 a_pos1 := instr(v_url, '?', a_pos2 + 1);
4392 v_path := substr(v_url, a_pos2);
4396 v_path := substr(v_url, a_pos2, a_pos1 - a_pos2);
4397 v_query := substr(v_url, a_pos1 + 1);
4399 $$ LANGUAGE plpgsql;
4402 This function could be used like this:
4404 SELECT * FROM cs_parse_url('http://foobar.com/query.cgi?baz');
4410 <xref linkend="plpgsql-porting-ex4"> shows how to port a procedure
4411 that uses numerous features that are specific to Oracle.
4414 <example id="plpgsql-porting-ex4">
4415 <title>Porting a Procedure from <application>PL/SQL</> to <application>PL/pgSQL</></title>
4421 CREATE OR REPLACE PROCEDURE cs_create_job(v_job_id IN INTEGER) IS
4422 a_running_job_count INTEGER;
4423 PRAGMA AUTONOMOUS_TRANSACTION;<co id="co.plpgsql-porting-pragma">
4425 LOCK TABLE cs_jobs IN EXCLUSIVE MODE;<co id="co.plpgsql-porting-locktable">
4427 SELECT count(*) INTO a_running_job_count FROM cs_jobs WHERE end_stamp IS NULL;
4429 IF a_running_job_count > 0 THEN
4430 COMMIT; -- free lock<co id="co.plpgsql-porting-commit">
4431 raise_application_error(-20000, 'Unable to create a new job: a job is currently running.');
4434 DELETE FROM cs_active_job;
4435 INSERT INTO cs_active_job(job_id) VALUES (v_job_id);
4438 INSERT INTO cs_jobs (job_id, start_stamp) VALUES (v_job_id, sysdate);
4440 WHEN dup_val_on_index THEN NULL; -- don't worry if it already exists
4450 Procedures like this can easily be converted into <productname>PostgreSQL</>
4451 functions returning <type>void</type>. This procedure in
4452 particular is interesting because it can teach us some things:
4455 <callout arearefs="co.plpgsql-porting-pragma">
4457 There is no <literal>PRAGMA</literal> statement in <productname>PostgreSQL</>.
4461 <callout arearefs="co.plpgsql-porting-locktable">
4463 If you do a <command>LOCK TABLE</command> in <application>PL/pgSQL</>,
4464 the lock will not be released until the calling transaction is
4469 <callout arearefs="co.plpgsql-porting-commit">
4471 You cannot issue <command>COMMIT</> in a
4472 <application>PL/pgSQL</application> function. The function is
4473 running within some outer transaction and so <command>COMMIT</>
4474 would imply terminating the function's execution. However, in
4475 this particular case it is not necessary anyway, because the lock
4476 obtained by the <command>LOCK TABLE</command> will be released when
4484 This is how we could port this procedure to <application>PL/pgSQL</>:
4487 CREATE OR REPLACE FUNCTION cs_create_job(v_job_id integer) RETURNS void AS $$
4489 a_running_job_count integer;
4491 LOCK TABLE cs_jobs IN EXCLUSIVE MODE;
4493 SELECT count(*) INTO a_running_job_count FROM cs_jobs WHERE end_stamp IS NULL;
4495 IF a_running_job_count > 0 THEN
4496 RAISE EXCEPTION 'Unable to create a new job: a job is currently running';<co id="co.plpgsql-porting-raise">
4499 DELETE FROM cs_active_job;
4500 INSERT INTO cs_active_job(job_id) VALUES (v_job_id);
4503 INSERT INTO cs_jobs (job_id, start_stamp) VALUES (v_job_id, now());
4505 WHEN unique_violation THEN <co id="co.plpgsql-porting-exception">
4506 -- don't worry if it already exists
4509 $$ LANGUAGE plpgsql;
4513 <callout arearefs="co.plpgsql-porting-raise">
4515 The syntax of <literal>RAISE</> is considerably different from
4516 Oracle's statement, although the basic case <literal>RAISE</>
4517 <replaceable class="parameter">exception_name</replaceable> works
4521 <callout arearefs="co.plpgsql-porting-exception">
4523 The exception names supported by <application>PL/pgSQL</> are
4524 different from Oracle's. The set of built-in exception names
4525 is much larger (see <xref linkend="errcodes-appendix">). There
4526 is not currently a way to declare user-defined exception names.
4531 The main functional difference between this procedure and the
4532 Oracle equivalent is that the exclusive lock on the <literal>cs_jobs</>
4533 table will be held until the calling transaction completes. Also, if
4534 the caller later aborts (for example due to an error), the effects of
4535 this procedure will be rolled back.
4540 <sect2 id="plpgsql-porting-other">
4541 <title>Other Things to Watch For</title>
4544 This section explains a few other things to watch for when porting
4545 Oracle <application>PL/SQL</> functions to
4546 <productname>PostgreSQL</productname>.
4549 <sect3 id="plpgsql-porting-exceptions">
4550 <title>Implicit Rollback after Exceptions</title>
4553 In <application>PL/pgSQL</>, when an exception is caught by an
4554 <literal>EXCEPTION</> clause, all database changes since the block's
4555 <literal>BEGIN</> are automatically rolled back. That is, the behavior
4556 is equivalent to what you'd get in Oracle with:
4572 If you are translating an Oracle procedure that uses
4573 <command>SAVEPOINT</> and <command>ROLLBACK TO</> in this style,
4574 your task is easy: just omit the <command>SAVEPOINT</> and
4575 <command>ROLLBACK TO</>. If you have a procedure that uses
4576 <command>SAVEPOINT</> and <command>ROLLBACK TO</> in a different way
4577 then some actual thought will be required.
4582 <title><command>EXECUTE</command></title>
4585 The <application>PL/pgSQL</> version of
4586 <command>EXECUTE</command> works similarly to the
4587 <application>PL/SQL</> version, but you have to remember to use
4588 <function>quote_literal</function> and
4589 <function>quote_ident</function> as described in <xref
4590 linkend="plpgsql-statements-executing-dyn">. Constructs of the
4591 type <literal>EXECUTE 'SELECT * FROM $1';</literal> will not work
4592 reliably unless you use these functions.
4596 <sect3 id="plpgsql-porting-optimization">
4597 <title>Optimizing <application>PL/pgSQL</application> Functions</title>
4600 <productname>PostgreSQL</> gives you two function creation
4601 modifiers to optimize execution: <quote>volatility</> (whether
4602 the function always returns the same result when given the same
4603 arguments) and <quote>strictness</quote> (whether the function
4604 returns null if any argument is null). Consult the <xref
4605 linkend="sql-createfunction" endterm="sql-createfunction-title">
4606 reference page for details.
4610 When making use of these optimization attributes, your
4611 <command>CREATE FUNCTION</command> statement might look something
4615 CREATE FUNCTION foo(...) RETURNS integer AS $$
4617 $$ LANGUAGE plpgsql STRICT IMMUTABLE;
4623 <sect2 id="plpgsql-porting-appendix">
4624 <title>Appendix</title>
4627 This section contains the code for a set of Oracle-compatible
4628 <function>instr</function> functions that you can use to simplify
4629 your porting efforts.
4634 -- instr functions that mimic Oracle's counterpart
4635 -- Syntax: instr(string1, string2, [n], [m]) where [] denotes optional parameters.
4637 -- Searches string1 beginning at the nth character for the mth occurrence
4638 -- of string2. If n is negative, search backwards. If m is not passed,
4639 -- assume 1 (search starts at first character).
4642 CREATE FUNCTION instr(varchar, varchar) RETURNS integer AS $$
4646 pos:= instr($1, $2, 1);
4649 $$ LANGUAGE plpgsql STRICT IMMUTABLE;
4652 CREATE FUNCTION instr(string varchar, string_to_search varchar, beg_index integer)
4653 RETURNS integer AS $$
4655 pos integer NOT NULL DEFAULT 0;
4661 IF beg_index > 0 THEN
4662 temp_str := substring(string FROM beg_index);
4663 pos := position(string_to_search IN temp_str);
4668 RETURN pos + beg_index - 1;
4671 ss_length := char_length(string_to_search);
4672 length := char_length(string);
4673 beg := length + beg_index - ss_length + 2;
4675 WHILE beg > 0 LOOP
4676 temp_str := substring(string FROM beg FOR ss_length);
4677 pos := position(string_to_search IN temp_str);
4689 $$ LANGUAGE plpgsql STRICT IMMUTABLE;
4692 CREATE FUNCTION instr(string varchar, string_to_search varchar,
4693 beg_index integer, occur_index integer)
4694 RETURNS integer AS $$
4696 pos integer NOT NULL DEFAULT 0;
4697 occur_number integer NOT NULL DEFAULT 0;
4704 IF beg_index > 0 THEN
4706 temp_str := substring(string FROM beg_index);
4708 FOR i IN 1..occur_index LOOP
4709 pos := position(string_to_search IN temp_str);
4712 beg := beg + pos - 1;
4717 temp_str := substring(string FROM beg + 1);
4726 ss_length := char_length(string_to_search);
4727 length := char_length(string);
4728 beg := length + beg_index - ss_length + 2;
4730 WHILE beg > 0 LOOP
4731 temp_str := substring(string FROM beg FOR ss_length);
4732 pos := position(string_to_search IN temp_str);
4735 occur_number := occur_number + 1;
4737 IF occur_number = occur_index THEN
4748 $$ LANGUAGE plpgsql STRICT IMMUTABLE;