4 41.3.1. Declaring Function Parameters
9 41.3.6. Collation of PL/pgSQL Variables
11 All variables used in a block must be declared in the declarations
12 section of the block. (The only exceptions are that the loop variable
13 of a FOR loop iterating over a range of integer values is automatically
14 declared as an integer variable, and likewise the loop variable of a
15 FOR loop iterating over a cursor's result is automatically declared as
18 PL/pgSQL variables can have any SQL data type, such as integer,
21 Here are some examples of variable declarations:
25 myrow tablename%ROWTYPE;
26 myfield tablename.columnname%TYPE;
29 The general syntax of a variable declaration is:
30 name [ CONSTANT ] type [ COLLATE collation_name ] [ NOT NULL ] [ { DEFAULT | :=
33 The DEFAULT clause, if given, specifies the initial value assigned to
34 the variable when the block is entered. If the DEFAULT clause is not
35 given then the variable is initialized to the SQL null value. The
36 CONSTANT option prevents the variable from being assigned to after
37 initialization, so that its value will remain constant for the duration
38 of the block. The COLLATE option specifies a collation to use for the
39 variable (see Section 41.3.6). If NOT NULL is specified, an assignment
40 of a null value results in a run-time error. All variables declared as
41 NOT NULL must have a nonnull default value specified. Equal (=) can be
42 used instead of PL/SQL-compliant :=.
44 A variable's default value is evaluated and assigned to the variable
45 each time the block is entered (not just once per function call). So,
46 for example, assigning now() to a variable of type timestamp causes the
47 variable to have the time of the current function call, not the time
48 when the function was precompiled.
51 quantity integer DEFAULT 32;
52 url varchar := 'http://mysite.com';
53 transaction_time CONSTANT timestamp with time zone := now();
55 Once declared, a variable's value can be used in later initialization
56 expressions in the same block, for example:
61 41.3.1. Declaring Function Parameters #
63 Parameters passed to functions are named with the identifiers $1, $2,
64 etc. Optionally, aliases can be declared for $n parameter names for
65 increased readability. Either the alias or the numeric identifier can
66 then be used to refer to the parameter value.
68 There are two ways to create an alias. The preferred way is to give a
69 name to the parameter in the CREATE FUNCTION command, for example:
70 CREATE FUNCTION sales_tax(subtotal real) RETURNS real AS $$
72 RETURN subtotal * 0.06;
76 The other way is to explicitly declare an alias, using the declaration
80 The same example in this style looks like:
81 CREATE FUNCTION sales_tax(real) RETURNS real AS $$
83 subtotal ALIAS FOR $1;
85 RETURN subtotal * 0.06;
91 These two examples are not perfectly equivalent. In the first case,
92 subtotal could be referenced as sales_tax.subtotal, but in the second
93 case it could not. (Had we attached a label to the inner block,
94 subtotal could be qualified with that label, instead.)
97 CREATE FUNCTION instr(varchar, integer) RETURNS integer AS $$
99 v_string ALIAS FOR $1;
102 -- some computations using v_string and index here
107 CREATE FUNCTION concat_selected_fields(in_t sometablename) RETURNS text AS $$
109 RETURN in_t.f1 || in_t.f3 || in_t.f5 || in_t.f7;
113 When a PL/pgSQL function is declared with output parameters, the output
114 parameters are given $n names and optional aliases in just the same way
115 as the normal input parameters. An output parameter is effectively a
116 variable that starts out NULL; it should be assigned to during the
117 execution of the function. The final value of the parameter is what is
118 returned. For instance, the sales-tax example could also be done this
120 CREATE FUNCTION sales_tax(subtotal real, OUT tax real) AS $$
122 tax := subtotal * 0.06;
126 Notice that we omitted RETURNS real — we could have included it, but it
129 To call a function with OUT parameters, omit the output parameter(s) in
131 SELECT sales_tax(100.00);
133 Output parameters are most useful when returning multiple values. A
135 CREATE FUNCTION sum_n_product(x int, y int, OUT sum int, OUT prod int) AS $$
142 SELECT * FROM sum_n_product(2, 4);
147 As discussed in Section 36.5.4, this effectively creates an anonymous
148 record type for the function's results. If a RETURNS clause is given,
149 it must say RETURNS record.
151 This also works with procedures, for example:
152 CREATE PROCEDURE sum_n_product(x int, y int, OUT sum int, OUT prod int) AS $$
159 In a call to a procedure, all the parameters must be specified. For
160 output parameters, NULL may be specified when calling the procedure
162 CALL sum_n_product(2, 4, NULL, NULL);
167 However, when calling a procedure from PL/pgSQL, you should instead
168 write a variable for any output parameter; the variable will receive
169 the result of the call. See Section 41.6.3 for details.
171 Another way to declare a PL/pgSQL function is with RETURNS TABLE, for
173 CREATE FUNCTION extended_sales(p_itemno int)
174 RETURNS TABLE(quantity int, total numeric) AS $$
176 RETURN QUERY SELECT s.quantity, s.quantity * s.price FROM sales AS s
177 WHERE s.itemno = p_itemno;
181 This is exactly equivalent to declaring one or more OUT parameters and
182 specifying RETURNS SETOF sometype.
184 When the return type of a PL/pgSQL function is declared as a
185 polymorphic type (see Section 36.2.5), a special parameter $0 is
186 created. Its data type is the actual return type of the function, as
187 deduced from the actual input types. This allows the function to access
188 its actual return type as shown in Section 41.3.3. $0 is initialized to
189 null and can be modified by the function, so it can be used to hold the
190 return value if desired, though that is not required. $0 can also be
191 given an alias. For example, this function works on any data type that
193 CREATE FUNCTION add_three_values(v1 anyelement, v2 anyelement, v3 anyelement)
194 RETURNS anyelement AS $$
198 result := v1 + v2 + v3;
203 The same effect can be obtained by declaring one or more output
204 parameters as polymorphic types. In this case the special $0 parameter
205 is not used; the output parameters themselves serve the same purpose.
207 CREATE FUNCTION add_three_values(v1 anyelement, v2 anyelement, v3 anyelement,
215 In practice it might be more useful to declare a polymorphic function
216 using the anycompatible family of types, so that automatic promotion of
217 the input arguments to a common type will occur. For example:
218 CREATE FUNCTION add_three_values(v1 anycompatible, v2 anycompatible, v3 anycompa
220 RETURNS anycompatible AS $$
226 With this example, a call such as
227 SELECT add_three_values(1, 2, 4.7);
229 will work, automatically promoting the integer inputs to numeric. The
230 function using anyelement would require you to cast the three inputs to
231 the same type manually.
235 newname ALIAS FOR oldname;
237 The ALIAS syntax is more general than is suggested in the previous
238 section: you can declare an alias for any variable, not just function
239 parameters. The main practical use for this is to assign a different
240 name for variables with predetermined names, such as NEW or OLD within
246 updated ALIAS FOR new;
248 Since ALIAS creates two different ways to name the same object,
249 unrestricted use can be confusing. It's best to use it only for the
250 purpose of overriding predetermined names.
252 41.3.3. Copying Types #
254 name table.column%TYPE
257 %TYPE provides the data type of a table column or a previously-declared
258 PL/pgSQL variable. You can use this to declare variables that will hold
259 database values. For example, let's say you have a column named user_id
260 in your users table. To declare a variable with the same data type as
261 users.user_id you write:
262 user_id users.user_id%TYPE;
264 It is also possible to write array decoration after %TYPE, thereby
265 creating a variable that holds an array of the referenced type:
266 user_ids users.user_id%TYPE[];
267 user_ids users.user_id%TYPE ARRAY[4]; -- equivalent to the above
269 Just as when declaring table columns that are arrays, it doesn't matter
270 whether you write multiple bracket pairs or specific array dimensions:
271 PostgreSQL treats all arrays of a given element type as the same type,
272 regardless of dimensionality. (See Section 8.15.1.)
274 By using %TYPE you don't need to know the data type of the structure
275 you are referencing, and most importantly, if the data type of the
276 referenced item changes in the future (for instance: you change the
277 type of user_id from integer to real), you might not need to change
278 your function definition.
280 %TYPE is particularly valuable in polymorphic functions, since the data
281 types needed for internal variables can change from one call to the
282 next. Appropriate variables can be created by applying %TYPE to the
283 function's arguments or result placeholders.
287 name table_name%ROWTYPE;
288 name composite_type_name;
290 A variable of a composite type is called a row variable (or row-type
291 variable). Such a variable can hold a whole row of a SELECT or FOR
292 query result, so long as that query's column set matches the declared
293 type of the variable. The individual fields of the row value are
294 accessed using the usual dot notation, for example rowvar.field.
296 A row variable can be declared to have the same type as the rows of an
297 existing table or view, by using the table_name%ROWTYPE notation; or it
298 can be declared by giving a composite type's name. (Since every table
299 has an associated composite type of the same name, it actually does not
300 matter in PostgreSQL whether you write %ROWTYPE or not. But the form
301 with %ROWTYPE is more portable.)
303 As with %TYPE, %ROWTYPE can be followed by array decoration to declare
304 a variable that holds an array of the referenced composite type.
306 Parameters to a function can be composite types (complete table rows).
307 In that case, the corresponding identifier $n will be a row variable,
308 and fields can be selected from it, for example $1.user_id.
310 Here is an example of using composite types. table1 and table2 are
311 existing tables having at least the mentioned fields:
312 CREATE FUNCTION merge_fields(t_row table1) RETURNS text AS $$
314 t2_row table2%ROWTYPE;
316 SELECT * INTO t2_row FROM table2 WHERE ... ;
317 RETURN t_row.f1 || t2_row.f3 || t_row.f5 || t2_row.f7;
321 SELECT merge_fields(t.*) FROM table1 t WHERE ... ;
323 41.3.5. Record Types #
327 Record variables are similar to row-type variables, but they have no
328 predefined structure. They take on the actual row structure of the row
329 they are assigned during a SELECT or FOR command. The substructure of a
330 record variable can change each time it is assigned to. A consequence
331 of this is that until a record variable is first assigned to, it has no
332 substructure, and any attempt to access a field in it will draw a
335 Note that RECORD is not a true data type, only a placeholder. One
336 should also realize that when a PL/pgSQL function is declared to return
337 type record, this is not quite the same concept as a record variable,
338 even though such a function might use a record variable to hold its
339 result. In both cases the actual row structure is unknown when the
340 function is written, but for a function returning record the actual
341 structure is determined when the calling query is parsed, whereas a
342 record variable can change its row structure on-the-fly.
344 41.3.6. Collation of PL/pgSQL Variables #
346 When a PL/pgSQL function has one or more parameters of collatable data
347 types, a collation is identified for each function call depending on
348 the collations assigned to the actual arguments, as described in
349 Section 23.2. If a collation is successfully identified (i.e., there
350 are no conflicts of implicit collations among the arguments) then all
351 the collatable parameters are treated as having that collation
352 implicitly. This will affect the behavior of collation-sensitive
353 operations within the function. For example, consider
354 CREATE FUNCTION less_than(a text, b text) RETURNS boolean AS $$
360 SELECT less_than(text_field_1, text_field_2) FROM table1;
361 SELECT less_than(text_field_1, text_field_2 COLLATE "C") FROM table1;
363 The first use of less_than will use the common collation of
364 text_field_1 and text_field_2 for the comparison, while the second use
365 will use C collation.
367 Furthermore, the identified collation is also assumed as the collation
368 of any local variables that are of collatable types. Thus this function
369 would not work any differently if it were written as
370 CREATE FUNCTION less_than(a text, b text) RETURNS boolean AS $$
375 RETURN local_a < local_b;
379 If there are no parameters of collatable data types, or no common
380 collation can be identified for them, then parameters and local
381 variables use the default collation of their data type (which is
382 usually the database's default collation, but could be different for
383 variables of domain types).
385 A local variable of a collatable data type can have a different
386 collation associated with it by including the COLLATE option in its
387 declaration, for example
389 local_a text COLLATE "en_US";
391 This option overrides the collation that would otherwise be given to
392 the variable according to the rules above.
394 Also, of course explicit COLLATE clauses can be written inside a
395 function if it is desired to force a particular collation to be used in
396 a particular operation. For example,
397 CREATE FUNCTION less_than_c(a text, b text) RETURNS boolean AS $$
399 RETURN a < b COLLATE "C";
403 This overrides the collations associated with the table columns,
404 parameters, or local variables used in the expression, just as would
405 happen in a plain SQL command.