1 <?xml version="1.0" encoding="UTF-8" standalone="no"?>
2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /><title>41.3. Declarations</title><link rel="stylesheet" type="text/css" href="stylesheet.css" /><link rev="made" href="pgsql-docs@lists.postgresql.org" /><meta name="generator" content="DocBook XSL Stylesheets Vsnapshot" /><link rel="prev" href="plpgsql-structure.html" title="41.2. Structure of PL/pgSQL" /><link rel="next" href="plpgsql-expressions.html" title="41.4. Expressions" /></head><body id="docContent" class="container-fluid col-10"><div class="navheader"><table width="100%" summary="Navigation header"><tr><th colspan="5" align="center">41.3. Declarations</th></tr><tr><td width="10%" align="left"><a accesskey="p" href="plpgsql-structure.html" title="41.2. Structure of PL/pgSQL">Prev</a> </td><td width="10%" align="left"><a accesskey="u" href="plpgsql.html" title="Chapter 41. PL/pgSQL — SQL Procedural Language">Up</a></td><th width="60%" align="center">Chapter 41. <span class="application">PL/pgSQL</span> — <acronym class="acronym">SQL</acronym> Procedural Language</th><td width="10%" align="right"><a accesskey="h" href="index.html" title="PostgreSQL 18.0 Documentation">Home</a></td><td width="10%" align="right"> <a accesskey="n" href="plpgsql-expressions.html" title="41.4. Expressions">Next</a></td></tr></table><hr /></div><div class="sect1" id="PLPGSQL-DECLARATIONS"><div class="titlepage"><div><div><h2 class="title" style="clear: both">41.3. Declarations <a href="#PLPGSQL-DECLARATIONS" class="id_link">#</a></h2></div></div></div><div class="toc"><dl class="toc"><dt><span class="sect2"><a href="plpgsql-declarations.html#PLPGSQL-DECLARATION-PARAMETERS">41.3.1. Declaring Function Parameters</a></span></dt><dt><span class="sect2"><a href="plpgsql-declarations.html#PLPGSQL-DECLARATION-ALIAS">41.3.2. <code class="literal">ALIAS</code></a></span></dt><dt><span class="sect2"><a href="plpgsql-declarations.html#PLPGSQL-DECLARATION-TYPE">41.3.3. Copying Types</a></span></dt><dt><span class="sect2"><a href="plpgsql-declarations.html#PLPGSQL-DECLARATION-ROWTYPES">41.3.4. Row Types</a></span></dt><dt><span class="sect2"><a href="plpgsql-declarations.html#PLPGSQL-DECLARATION-RECORDS">41.3.5. Record Types</a></span></dt><dt><span class="sect2"><a href="plpgsql-declarations.html#PLPGSQL-DECLARATION-COLLATION">41.3.6. Collation of <span class="application">PL/pgSQL</span> Variables</a></span></dt></dl></div><p>
3 All variables used in a block must be declared in the
4 declarations section of the block.
5 (The only exceptions are that the loop variable of a <code class="literal">FOR</code> loop
6 iterating over a range of integer values is automatically declared as an
7 integer variable, and likewise the loop variable of a <code class="literal">FOR</code> loop
8 iterating over a cursor's result is automatically declared as a
11 <span class="application">PL/pgSQL</span> variables can have any SQL data type, such as
12 <code class="type">integer</code>, <code class="type">varchar</code>, and
13 <code class="type">char</code>.
15 Here are some examples of variable declarations:
16 </p><pre class="programlisting">
20 myrow tablename%ROWTYPE;
21 myfield tablename.columnname%TYPE;
25 The general syntax of a variable declaration is:
26 </p><pre class="synopsis">
27 <em class="replaceable"><code>name</code></em> [<span class="optional"> CONSTANT </span>] <em class="replaceable"><code>type</code></em> [<span class="optional"> COLLATE <em class="replaceable"><code>collation_name</code></em> </span>] [<span class="optional"> NOT NULL </span>] [<span class="optional"> { DEFAULT | := | = } <em class="replaceable"><code>expression</code></em> </span>];
29 The <code class="literal">DEFAULT</code> clause, if given, specifies the initial value assigned
30 to the variable when the block is entered. If the <code class="literal">DEFAULT</code> clause
31 is not given then the variable is initialized to the
32 <acronym class="acronym">SQL</acronym> null value.
33 The <code class="literal">CONSTANT</code> option prevents the variable from being
34 assigned to after initialization, so that its value will remain constant
35 for the duration of the block.
36 The <code class="literal">COLLATE</code> option specifies a collation to use for the
37 variable (see <a class="xref" href="plpgsql-declarations.html#PLPGSQL-DECLARATION-COLLATION" title="41.3.6. Collation of PL/pgSQL Variables">Section 41.3.6</a>).
38 If <code class="literal">NOT NULL</code>
39 is specified, an assignment of a null value results in a run-time
40 error. All variables declared as <code class="literal">NOT NULL</code>
41 must have a nonnull default value specified.
42 Equal (<code class="literal">=</code>) can be used instead of PL/SQL-compliant
43 <code class="literal">:=</code>.
45 A variable's default value is evaluated and assigned to the variable
46 each time the block is entered (not just once per function call).
47 So, for example, assigning <code class="literal">now()</code> to a variable of type
48 <code class="type">timestamp</code> causes the variable to have the
49 time of the current function call, not the time when the function was
53 </p><pre class="programlisting">
54 quantity integer DEFAULT 32;
55 url varchar := 'http://mysite.com';
56 transaction_time CONSTANT timestamp with time zone := now();
59 Once declared, a variable's value can be used in later initialization
60 expressions in the same block, for example:
61 </p><pre class="programlisting">
66 </p><div class="sect2" id="PLPGSQL-DECLARATION-PARAMETERS"><div class="titlepage"><div><div><h3 class="title">41.3.1. Declaring Function Parameters <a href="#PLPGSQL-DECLARATION-PARAMETERS" class="id_link">#</a></h3></div></div></div><p>
67 Parameters passed to functions are named with the identifiers
68 <code class="literal">$1</code>, <code class="literal">$2</code>,
69 etc. Optionally, aliases can be declared for
70 <code class="literal">$<em class="replaceable"><code>n</code></em></code>
71 parameter names for increased readability. Either the alias or the
72 numeric identifier can then be used to refer to the parameter value.
74 There are two ways to create an alias. The preferred way is to give a
75 name to the parameter in the <code class="command">CREATE FUNCTION</code> command,
77 </p><pre class="programlisting">
78 CREATE FUNCTION sales_tax(subtotal real) RETURNS real AS $$
80 RETURN subtotal * 0.06;
84 The other way is to explicitly declare an alias, using the
87 </p><pre class="synopsis">
88 <em class="replaceable"><code>name</code></em> ALIAS FOR $<em class="replaceable"><code>n</code></em>;
91 The same example in this style looks like:
92 </p><pre class="programlisting">
93 CREATE FUNCTION sales_tax(real) RETURNS real AS $$
95 subtotal ALIAS FOR $1;
97 RETURN subtotal * 0.06;
101 </p><div class="note"><h3 class="title">Note</h3><p>
102 These two examples are not perfectly equivalent. In the first case,
103 <code class="literal">subtotal</code> could be referenced as
104 <code class="literal">sales_tax.subtotal</code>, but in the second case it could not.
105 (Had we attached a label to the inner block, <code class="literal">subtotal</code> could
106 be qualified with that label, instead.)
109 </p><pre class="programlisting">
110 CREATE FUNCTION instr(varchar, integer) RETURNS integer AS $$
112 v_string ALIAS FOR $1;
115 -- some computations using v_string and index here
120 CREATE FUNCTION concat_selected_fields(in_t sometablename) RETURNS text AS $$
122 RETURN in_t.f1 || in_t.f3 || in_t.f5 || in_t.f7;
127 When a <span class="application">PL/pgSQL</span> function is declared
128 with output parameters, the output parameters are given
129 <code class="literal">$<em class="replaceable"><code>n</code></em></code> names and optional
130 aliases in just the same way as the normal input parameters. An
131 output parameter is effectively a variable that starts out NULL;
132 it should be assigned to during the execution of the function.
133 The final value of the parameter is what is returned. For instance,
134 the sales-tax example could also be done this way:
136 </p><pre class="programlisting">
137 CREATE FUNCTION sales_tax(subtotal real, OUT tax real) AS $$
139 tax := subtotal * 0.06;
144 Notice that we omitted <code class="literal">RETURNS real</code> — we could have
145 included it, but it would be redundant.
147 To call a function with <code class="literal">OUT</code> parameters, omit the
148 output parameter(s) in the function call:
149 </p><pre class="programlisting">
150 SELECT sales_tax(100.00);
153 Output parameters are most useful when returning multiple values.
154 A trivial example is:
156 </p><pre class="programlisting">
157 CREATE FUNCTION sum_n_product(x int, y int, OUT sum int, OUT prod int) AS $$
164 SELECT * FROM sum_n_product(2, 4);
170 As discussed in <a class="xref" href="xfunc-sql.html#XFUNC-OUTPUT-PARAMETERS" title="36.5.4. SQL Functions with Output Parameters">Section 36.5.4</a>, this
171 effectively creates an anonymous record type for the function's
172 results. If a <code class="literal">RETURNS</code> clause is given, it must say
173 <code class="literal">RETURNS record</code>.
175 This also works with procedures, for example:
177 </p><pre class="programlisting">
178 CREATE PROCEDURE sum_n_product(x int, y int, OUT sum int, OUT prod int) AS $$
186 In a call to a procedure, all the parameters must be specified. For
187 output parameters, <code class="literal">NULL</code> may be specified when
188 calling the procedure from plain SQL:
189 </p><pre class="programlisting">
190 CALL sum_n_product(2, 4, NULL, NULL);
196 However, when calling a procedure
197 from <span class="application">PL/pgSQL</span>, you should instead write a
198 variable for any output parameter; the variable will receive the result
199 of the call. See <a class="xref" href="plpgsql-control-structures.html#PLPGSQL-STATEMENTS-CALLING-PROCEDURE" title="41.6.3. Calling a Procedure">Section 41.6.3</a>
202 Another way to declare a <span class="application">PL/pgSQL</span> function
203 is with <code class="literal">RETURNS TABLE</code>, for example:
205 </p><pre class="programlisting">
206 CREATE FUNCTION extended_sales(p_itemno int)
207 RETURNS TABLE(quantity int, total numeric) AS $$
209 RETURN QUERY SELECT s.quantity, s.quantity * s.price FROM sales AS s
210 WHERE s.itemno = p_itemno;
215 This is exactly equivalent to declaring one or more <code class="literal">OUT</code>
216 parameters and specifying <code class="literal">RETURNS SETOF
217 <em class="replaceable"><code>sometype</code></em></code>.
219 When the return type of a <span class="application">PL/pgSQL</span> function
220 is declared as a polymorphic type (see
221 <a class="xref" href="extend-type-system.html#EXTEND-TYPES-POLYMORPHIC" title="36.2.5. Polymorphic Types">Section 36.2.5</a>), a special
222 parameter <code class="literal">$0</code> is created. Its data type is the actual
223 return type of the function, as deduced from the actual input types.
224 This allows the function to access its actual return type
225 as shown in <a class="xref" href="plpgsql-declarations.html#PLPGSQL-DECLARATION-TYPE" title="41.3.3. Copying Types">Section 41.3.3</a>.
226 <code class="literal">$0</code> is initialized to null and can be modified by
227 the function, so it can be used to hold the return value if desired,
228 though that is not required. <code class="literal">$0</code> can also be
229 given an alias. For example, this function works on any data type
230 that has a <code class="literal">+</code> operator:
232 </p><pre class="programlisting">
233 CREATE FUNCTION add_three_values(v1 anyelement, v2 anyelement, v3 anyelement)
234 RETURNS anyelement AS $$
238 result := v1 + v2 + v3;
244 The same effect can be obtained by declaring one or more output parameters as
245 polymorphic types. In this case the
246 special <code class="literal">$0</code> parameter is not used; the output
247 parameters themselves serve the same purpose. For example:
249 </p><pre class="programlisting">
250 CREATE FUNCTION add_three_values(v1 anyelement, v2 anyelement, v3 anyelement,
259 In practice it might be more useful to declare a polymorphic function
260 using the <code class="type">anycompatible</code> family of types, so that automatic
261 promotion of the input arguments to a common type will occur.
264 </p><pre class="programlisting">
265 CREATE FUNCTION add_three_values(v1 anycompatible, v2 anycompatible, v3 anycompatible)
266 RETURNS anycompatible AS $$
273 With this example, a call such as
275 </p><pre class="programlisting">
276 SELECT add_three_values(1, 2, 4.7);
279 will work, automatically promoting the integer inputs to numeric.
280 The function using <code class="type">anyelement</code> would require you to
281 cast the three inputs to the same type manually.
282 </p></div><div class="sect2" id="PLPGSQL-DECLARATION-ALIAS"><div class="titlepage"><div><div><h3 class="title">41.3.2. <code class="literal">ALIAS</code> <a href="#PLPGSQL-DECLARATION-ALIAS" class="id_link">#</a></h3></div></div></div><pre class="synopsis">
283 <em class="replaceable"><code>newname</code></em> ALIAS FOR <em class="replaceable"><code>oldname</code></em>;
285 The <code class="literal">ALIAS</code> syntax is more general than is suggested in the
286 previous section: you can declare an alias for any variable, not just
287 function parameters. The main practical use for this is to assign
288 a different name for variables with predetermined names, such as
289 <code class="varname">NEW</code> or <code class="varname">OLD</code> within
293 </p><pre class="programlisting">
296 updated ALIAS FOR new;
299 Since <code class="literal">ALIAS</code> creates two different ways to name the same
300 object, unrestricted use can be confusing. It's best to use it only
301 for the purpose of overriding predetermined names.
302 </p></div><div class="sect2" id="PLPGSQL-DECLARATION-TYPE"><div class="titlepage"><div><div><h3 class="title">41.3.3. Copying Types <a href="#PLPGSQL-DECLARATION-TYPE" class="id_link">#</a></h3></div></div></div><pre class="synopsis">
303 <em class="replaceable"><code>name</code></em> <em class="replaceable"><code>table</code></em>.<em class="replaceable"><code>column</code></em>%TYPE
304 <em class="replaceable"><code>name</code></em> <em class="replaceable"><code>variable</code></em>%TYPE
306 <code class="literal">%TYPE</code> provides the data type of a table column
307 or a previously-declared <span class="application">PL/pgSQL</span>
308 variable. You can use this to declare variables that will hold
309 database values. For example, let's say you have a column named
310 <code class="literal">user_id</code> in your <code class="literal">users</code>
311 table. To declare a variable with the same data type as
312 <code class="literal">users.user_id</code> you write:
313 </p><pre class="programlisting">
314 user_id users.user_id%TYPE;
317 It is also possible to write array decoration
318 after <code class="literal">%TYPE</code>, thereby creating a variable that holds
319 an array of the referenced type:
320 </p><pre class="programlisting">
321 user_ids users.user_id%TYPE[];
322 user_ids users.user_id%TYPE ARRAY[4]; -- equivalent to the above
324 Just as when declaring table columns that are arrays, it doesn't
325 matter whether you write multiple bracket pairs or specific array
326 dimensions: <span class="productname">PostgreSQL</span> treats all arrays of
327 a given element type as the same type, regardless of dimensionality.
328 (See <a class="xref" href="arrays.html#ARRAYS-DECLARATION" title="8.15.1. Declaration of Array Types">Section 8.15.1</a>.)
330 By using <code class="literal">%TYPE</code> you don't need to know the data
331 type of the structure you are referencing, and most importantly,
332 if the data type of the referenced item changes in the future (for
333 instance: you change the type of <code class="literal">user_id</code>
334 from <code class="type">integer</code> to <code class="type">real</code>), you might not need
335 to change your function definition.
337 <code class="literal">%TYPE</code> is particularly valuable in polymorphic
338 functions, since the data types needed for internal variables can
339 change from one call to the next. Appropriate variables can be
340 created by applying <code class="literal">%TYPE</code> to the function's
341 arguments or result placeholders.
342 </p></div><div class="sect2" id="PLPGSQL-DECLARATION-ROWTYPES"><div class="titlepage"><div><div><h3 class="title">41.3.4. Row Types <a href="#PLPGSQL-DECLARATION-ROWTYPES" class="id_link">#</a></h3></div></div></div><pre class="synopsis">
343 <em class="replaceable"><code>name</code></em> <em class="replaceable"><code>table_name</code></em><code class="literal">%ROWTYPE</code>;
344 <em class="replaceable"><code>name</code></em> <em class="replaceable"><code>composite_type_name</code></em>;
346 A variable of a composite type is called a <em class="firstterm">row</em>
347 variable (or <em class="firstterm">row-type</em> variable). Such a variable
348 can hold a whole row of a <code class="command">SELECT</code> or <code class="command">FOR</code>
349 query result, so long as that query's column set matches the
350 declared type of the variable.
351 The individual fields of the row value
352 are accessed using the usual dot notation, for example
353 <code class="literal">rowvar.field</code>.
355 A row variable can be declared to have the same type as the rows of
356 an existing table or view, by using the
357 <em class="replaceable"><code>table_name</code></em><code class="literal">%ROWTYPE</code>
358 notation; or it can be declared by giving a composite type's name.
359 (Since every table has an associated composite type of the same name,
360 it actually does not matter in <span class="productname">PostgreSQL</span> whether you
361 write <code class="literal">%ROWTYPE</code> or not. But the form with
362 <code class="literal">%ROWTYPE</code> is more portable.)
364 As with <code class="literal">%TYPE</code>, <code class="literal">%ROWTYPE</code> can be
365 followed by array decoration to declare a variable that holds an array
366 of the referenced composite type.
368 Parameters to a function can be
369 composite types (complete table rows). In that case, the
370 corresponding identifier <code class="literal">$<em class="replaceable"><code>n</code></em></code> will be a row variable, and fields can
371 be selected from it, for example <code class="literal">$1.user_id</code>.
373 Here is an example of using composite types. <code class="structname">table1</code>
374 and <code class="structname">table2</code> are existing tables having at least the
377 </p><pre class="programlisting">
378 CREATE FUNCTION merge_fields(t_row table1) RETURNS text AS $$
380 t2_row table2%ROWTYPE;
382 SELECT * INTO t2_row FROM table2 WHERE ... ;
383 RETURN t_row.f1 || t2_row.f3 || t_row.f5 || t2_row.f7;
387 SELECT merge_fields(t.*) FROM table1 t WHERE ... ;
389 </p></div><div class="sect2" id="PLPGSQL-DECLARATION-RECORDS"><div class="titlepage"><div><div><h3 class="title">41.3.5. Record Types <a href="#PLPGSQL-DECLARATION-RECORDS" class="id_link">#</a></h3></div></div></div><pre class="synopsis">
390 <em class="replaceable"><code>name</code></em> RECORD;
392 Record variables are similar to row-type variables, but they have no
393 predefined structure. They take on the actual row structure of the
394 row they are assigned during a <code class="command">SELECT</code> or <code class="command">FOR</code> command. The substructure
395 of a record variable can change each time it is assigned to.
396 A consequence of this is that until a record variable is first assigned
397 to, it has no substructure, and any attempt to access a
398 field in it will draw a run-time error.
400 Note that <code class="literal">RECORD</code> is not a true data type, only a placeholder.
401 One should also realize that when a <span class="application">PL/pgSQL</span>
402 function is declared to return type <code class="type">record</code>, this is not quite the
403 same concept as a record variable, even though such a function might
404 use a record variable to hold its result. In both cases the actual row
405 structure is unknown when the function is written, but for a function
406 returning <code class="type">record</code> the actual structure is determined when the
407 calling query is parsed, whereas a record variable can change its row
408 structure on-the-fly.
409 </p></div><div class="sect2" id="PLPGSQL-DECLARATION-COLLATION"><div class="titlepage"><div><div><h3 class="title">41.3.6. Collation of <span class="application">PL/pgSQL</span> Variables <a href="#PLPGSQL-DECLARATION-COLLATION" class="id_link">#</a></h3></div></div></div><a id="id-1.8.8.5.14.2" class="indexterm"></a><p>
410 When a <span class="application">PL/pgSQL</span> function has one or more
411 parameters of collatable data types, a collation is identified for each
412 function call depending on the collations assigned to the actual
413 arguments, as described in <a class="xref" href="collation.html" title="23.2. Collation Support">Section 23.2</a>. If a collation is
414 successfully identified (i.e., there are no conflicts of implicit
415 collations among the arguments) then all the collatable parameters are
416 treated as having that collation implicitly. This will affect the
417 behavior of collation-sensitive operations within the function.
418 For example, consider
420 </p><pre class="programlisting">
421 CREATE FUNCTION less_than(a text, b text) RETURNS boolean AS $$
427 SELECT less_than(text_field_1, text_field_2) FROM table1;
428 SELECT less_than(text_field_1, text_field_2 COLLATE "C") FROM table1;
431 The first use of <code class="function">less_than</code> will use the common collation
432 of <code class="structfield">text_field_1</code> and <code class="structfield">text_field_2</code> for
433 the comparison, while the second use will use <code class="literal">C</code> collation.
435 Furthermore, the identified collation is also assumed as the collation of
436 any local variables that are of collatable types. Thus this function
437 would not work any differently if it were written as
439 </p><pre class="programlisting">
440 CREATE FUNCTION less_than(a text, b text) RETURNS boolean AS $$
445 RETURN local_a < local_b;
450 If there are no parameters of collatable data types, or no common
451 collation can be identified for them, then parameters and local variables
452 use the default collation of their data type (which is usually the
453 database's default collation, but could be different for variables of
456 A local variable of a collatable data type can have a different collation
457 associated with it by including the <code class="literal">COLLATE</code> option in its
458 declaration, for example
460 </p><pre class="programlisting">
462 local_a text COLLATE "en_US";
465 This option overrides the collation that would otherwise be
466 given to the variable according to the rules above.
468 Also, of course explicit <code class="literal">COLLATE</code> clauses can be written inside
469 a function if it is desired to force a particular collation to be used in
470 a particular operation. For example,
472 </p><pre class="programlisting">
473 CREATE FUNCTION less_than_c(a text, b text) RETURNS boolean AS $$
475 RETURN a < b COLLATE "C";
480 This overrides the collations associated with the table columns,
481 parameters, or local variables used in the expression, just as would
482 happen in a plain SQL command.
483 </p></div></div><div class="navfooter"><hr /><table width="100%" summary="Navigation footer"><tr><td width="40%" align="left"><a accesskey="p" href="plpgsql-structure.html" title="41.2. Structure of PL/pgSQL">Prev</a> </td><td width="20%" align="center"><a accesskey="u" href="plpgsql.html" title="Chapter 41. PL/pgSQL — SQL Procedural Language">Up</a></td><td width="40%" align="right"> <a accesskey="n" href="plpgsql-expressions.html" title="41.4. Expressions">Next</a></td></tr><tr><td width="40%" align="left" valign="top">41.2. Structure of <span class="application">PL/pgSQL</span> </td><td width="20%" align="center"><a accesskey="h" href="index.html" title="PostgreSQL 18.0 Documentation">Home</a></td><td width="40%" align="right" valign="top"> 41.4. Expressions</td></tr></table></div></body></html>