4 CREATE FUNCTION — define a new function
8 CREATE [ OR REPLACE ] FUNCTION
9 name ( [ [ argmode ] [ argname ] argtype [ { DEFAULT | = } default_expr ] [,
12 | RETURNS TABLE ( column_name column_type [, ...] ) ]
14 | TRANSFORM { FOR TYPE type_name } [, ... ]
16 | { IMMUTABLE | STABLE | VOLATILE }
18 | { CALLED ON NULL INPUT | RETURNS NULL ON NULL INPUT | STRICT }
19 | { [ EXTERNAL ] SECURITY INVOKER | [ EXTERNAL ] SECURITY DEFINER }
20 | PARALLEL { UNSAFE | RESTRICTED | SAFE }
23 | SUPPORT support_function
24 | SET configuration_parameter { TO value | = value | FROM CURRENT }
26 | AS 'obj_file', 'link_symbol'
32 CREATE FUNCTION defines a new function. CREATE OR REPLACE FUNCTION will
33 either create a new function, or replace an existing definition. To be
34 able to define a function, the user must have the USAGE privilege on
37 If a schema name is included, then the function is created in the
38 specified schema. Otherwise it is created in the current schema. The
39 name of the new function must not match any existing function or
40 procedure with the same input argument types in the same schema.
41 However, functions and procedures of different argument types can share
42 a name (this is called overloading).
44 To replace the current definition of an existing function, use CREATE
45 OR REPLACE FUNCTION. It is not possible to change the name or argument
46 types of a function this way (if you tried, you would actually be
47 creating a new, distinct function). Also, CREATE OR REPLACE FUNCTION
48 will not let you change the return type of an existing function. To do
49 that, you must drop and recreate the function. (When using OUT
50 parameters, that means you cannot change the types of any OUT
51 parameters except by dropping the function.)
53 When CREATE OR REPLACE FUNCTION is used to replace an existing
54 function, the ownership and permissions of the function do not change.
55 All other function properties are assigned the values specified or
56 implied in the command. You must own the function to replace it (this
57 includes being a member of the owning role).
59 If you drop and then recreate a function, the new function is not the
60 same entity as the old; you will have to drop existing rules, views,
61 triggers, etc. that refer to the old function. Use CREATE OR REPLACE
62 FUNCTION to change a function definition without breaking objects that
63 refer to the function. Also, ALTER FUNCTION can be used to change most
64 of the auxiliary properties of an existing function.
66 The user that creates the function becomes the owner of the function.
68 To be able to create a function, you must have USAGE privilege on the
69 argument types and the return type.
71 Refer to Section 36.3 for further information on writing functions.
76 The name (optionally schema-qualified) of the function to
80 The mode of an argument: IN, OUT, INOUT, or VARIADIC. If
81 omitted, the default is IN. Only OUT arguments can follow a
82 VARIADIC one. Also, OUT and INOUT arguments cannot be used
83 together with the RETURNS TABLE notation.
86 The name of an argument. Some languages (including SQL and
87 PL/pgSQL) let you use the name in the function body. For other
88 languages the name of an input argument is just extra
89 documentation, so far as the function itself is concerned; but
90 you can use input argument names when calling a function to
91 improve readability (see Section 4.3). In any case, the name of
92 an output argument is significant, because it defines the column
93 name in the result row type. (If you omit the name for an output
94 argument, the system will choose a default column name.)
97 The data type(s) of the function's arguments (optionally
98 schema-qualified), if any. The argument types can be base,
99 composite, or domain types, or can reference the type of a table
102 Depending on the implementation language it might also be
103 allowed to specify “pseudo-types” such as cstring. Pseudo-types
104 indicate that the actual argument type is either incompletely
105 specified, or outside the set of ordinary SQL data types.
107 The type of a column is referenced by writing
108 table_name.column_name%TYPE. Using this feature can sometimes
109 help make a function independent of changes to the definition of
113 An expression to be used as default value if the parameter is
114 not specified. The expression has to be coercible to the
115 argument type of the parameter. Only input (including INOUT)
116 parameters can have a default value. All input parameters
117 following a parameter with a default value must have default
121 The return data type (optionally schema-qualified). The return
122 type can be a base, composite, or domain type, or can reference
123 the type of a table column. Depending on the implementation
124 language it might also be allowed to specify “pseudo-types” such
125 as cstring. If the function is not supposed to return a value,
126 specify void as the return type.
128 When there are OUT or INOUT parameters, the RETURNS clause can
129 be omitted. If present, it must agree with the result type
130 implied by the output parameters: RECORD if there are multiple
131 output parameters, or the same type as the single output
134 The SETOF modifier indicates that the function will return a set
135 of items, rather than a single item.
137 The type of a column is referenced by writing
138 table_name.column_name%TYPE.
141 The name of an output column in the RETURNS TABLE syntax. This
142 is effectively another way of declaring a named OUT parameter,
143 except that RETURNS TABLE also implies RETURNS SETOF.
146 The data type of an output column in the RETURNS TABLE syntax.
149 The name of the language that the function is implemented in. It
150 can be sql, c, internal, or the name of a user-defined
151 procedural language, e.g., plpgsql. The default is sql if
152 sql_body is specified. Enclosing the name in single quotes is
153 deprecated and requires matching case.
155 TRANSFORM { FOR TYPE type_name } [, ... ] }
156 Lists which transforms a call to the function should apply.
157 Transforms convert between SQL types and language-specific data
158 types; see CREATE TRANSFORM. Procedural language implementations
159 usually have hardcoded knowledge of the built-in types, so those
160 don't need to be listed here. If a procedural language
161 implementation does not know how to handle a type and no
162 transform is supplied, it will fall back to a default behavior
163 for converting data types, but this depends on the
167 WINDOW indicates that the function is a window function rather
168 than a plain function. This is currently only useful for
169 functions written in C. The WINDOW attribute cannot be changed
170 when replacing an existing function definition.
175 These attributes inform the query optimizer about the behavior
176 of the function. At most one choice can be specified. If none of
177 these appear, VOLATILE is the default assumption.
179 IMMUTABLE indicates that the function cannot modify the database
180 and always returns the same result when given the same argument
181 values; that is, it does not do database lookups or otherwise
182 use information not directly present in its argument list. If
183 this option is given, any call of the function with all-constant
184 arguments can be immediately replaced with the function value.
186 STABLE indicates that the function cannot modify the database,
187 and that within a single table scan it will consistently return
188 the same result for the same argument values, but that its
189 result could change across SQL statements. This is the
190 appropriate selection for functions whose results depend on
191 database lookups, parameter variables (such as the current time
192 zone), etc. (It is inappropriate for AFTER triggers that wish to
193 query rows modified by the current command.) Also note that the
194 current_timestamp family of functions qualify as stable, since
195 their values do not change within a transaction.
197 VOLATILE indicates that the function value can change even
198 within a single table scan, so no optimizations can be made.
199 Relatively few database functions are volatile in this sense;
200 some examples are random(), currval(), timeofday(). But note
201 that any function that has side-effects must be classified
202 volatile, even if its result is quite predictable, to prevent
203 calls from being optimized away; an example is setval().
205 For additional details see Section 36.7.
208 LEAKPROOF indicates that the function has no side effects. It
209 reveals no information about its arguments other than by its
210 return value. For example, a function which throws an error
211 message for some argument values but not others, or which
212 includes the argument values in any error message, is not
213 leakproof. This affects how the system executes queries against
214 views created with the security_barrier option or tables with
215 row level security enabled. The system will enforce conditions
216 from security policies and security barrier views before any
217 user-supplied conditions from the query itself that contain
218 non-leakproof functions, in order to prevent the inadvertent
219 exposure of data. Functions and operators marked as leakproof
220 are assumed to be trustworthy, and may be executed before
221 conditions from security policies and security barrier views. In
222 addition, functions which do not take arguments or which are not
223 passed any arguments from the security barrier view or table do
224 not have to be marked as leakproof to be executed before
225 security conditions. See CREATE VIEW and Section 39.5. This
226 option can only be set by the superuser.
229 RETURNS NULL ON NULL INPUT
231 CALLED ON NULL INPUT (the default) indicates that the function
232 will be called normally when some of its arguments are null. It
233 is then the function author's responsibility to check for null
234 values if necessary and respond appropriately.
236 RETURNS NULL ON NULL INPUT or STRICT indicates that the function
237 always returns null whenever any of its arguments are null. If
238 this parameter is specified, the function is not executed when
239 there are null arguments; instead a null result is assumed
242 [EXTERNAL] SECURITY INVOKER
243 [EXTERNAL] SECURITY DEFINER
244 SECURITY INVOKER indicates that the function is to be executed
245 with the privileges of the user that calls it. That is the
246 default. SECURITY DEFINER specifies that the function is to be
247 executed with the privileges of the user that owns it. For
248 information on how to write SECURITY DEFINER functions safely,
251 The key word EXTERNAL is allowed for SQL conformance, but it is
252 optional since, unlike in SQL, this feature applies to all
253 functions not only external ones.
256 PARALLEL UNSAFE indicates that the function can't be executed in
257 parallel mode; the presence of such a function in an SQL
258 statement forces a serial execution plan. This is the default.
259 PARALLEL RESTRICTED indicates that the function can be executed
260 in parallel mode, but only in the parallel group leader process.
261 PARALLEL SAFE indicates that the function is safe to run in
262 parallel mode without restriction, including in parallel worker
265 Functions should be labeled parallel unsafe if they modify any
266 database state, change the transaction state (other than by
267 using a subtransaction for error recovery), access sequences
268 (e.g., by calling currval) or make persistent changes to
269 settings. They should be labeled parallel restricted if they
270 access temporary tables, client connection state, cursors,
271 prepared statements, or miscellaneous backend-local state which
272 the system cannot synchronize in parallel mode (e.g., setseed
273 cannot be executed other than by the group leader because a
274 change made by another process would not be reflected in the
275 leader). In general, if a function is labeled as being safe when
276 it is restricted or unsafe, or if it is labeled as being
277 restricted when it is in fact unsafe, it may throw errors or
278 produce wrong answers when used in a parallel query. C-language
279 functions could in theory exhibit totally undefined behavior if
280 mislabeled, since there is no way for the system to protect
281 itself against arbitrary C code, but in most likely cases the
282 result will be no worse than for any other function. If in
283 doubt, functions should be labeled as UNSAFE, which is the
287 A positive number giving the estimated execution cost for the
288 function, in units of cpu_operator_cost. If the function returns
289 a set, this is the cost per returned row. If the cost is not
290 specified, 1 unit is assumed for C-language and internal
291 functions, and 100 units for functions in all other languages.
292 Larger values cause the planner to try to avoid evaluating the
293 function more often than necessary.
296 A positive number giving the estimated number of rows that the
297 planner should expect the function to return. This is only
298 allowed when the function is declared to return a set. The
299 default assumption is 1000 rows.
301 SUPPORT support_function
302 The name (optionally schema-qualified) of a planner support
303 function to use for this function. See Section 36.11 for
304 details. You must be superuser to use this option.
306 configuration_parameter
308 The SET clause causes the specified configuration parameter to
309 be set to the specified value when the function is entered, and
310 then restored to its prior value when the function exits. SET
311 FROM CURRENT saves the value of the parameter that is current
312 when CREATE FUNCTION is executed as the value to be applied when
313 the function is entered.
315 If a SET clause is attached to a function, then the effects of a
316 SET LOCAL command executed inside the function for the same
317 variable are restricted to the function: the configuration
318 parameter's prior value is still restored at function exit.
319 However, an ordinary SET command (without LOCAL) overrides the
320 SET clause, much as it would do for a previous SET LOCAL
321 command: the effects of such a command will persist after
322 function exit, unless the current transaction is rolled back.
324 See SET and Chapter 19 for more information about allowed
325 parameter names and values.
328 A string constant defining the function; the meaning depends on
329 the language. It can be an internal function name, the path to
330 an object file, an SQL command, or text in a procedural
333 It is often helpful to use dollar quoting (see Section 4.1.2.4)
334 to write the function definition string, rather than the normal
335 single quote syntax. Without dollar quoting, any single quotes
336 or backslashes in the function definition must be escaped by
339 obj_file, link_symbol
340 This form of the AS clause is used for dynamically loadable C
341 language functions when the function name in the C language
342 source code is not the same as the name of the SQL function. The
343 string obj_file is the name of the shared library file
344 containing the compiled C function, and is interpreted as for
345 the LOAD command. The string link_symbol is the function's link
346 symbol, that is, the name of the function in the C language
347 source code. If the link symbol is omitted, it is assumed to be
348 the same as the name of the SQL function being defined. The C
349 names of all functions must be different, so you must give
350 overloaded C functions different C names (for example, use the
351 argument types as part of the C names).
353 When repeated CREATE FUNCTION calls refer to the same object
354 file, the file is only loaded once per session. To unload and
355 reload the file (perhaps during development), start a new
359 The body of a LANGUAGE SQL function. This can either be a single
373 This is similar to writing the text of the function body as a
374 string constant (see definition above), but there are some
375 differences: This form only works for LANGUAGE SQL, the string
376 constant form works for all languages. This form is parsed at
377 function definition time, the string constant form is parsed at
378 execution time; therefore this form cannot support polymorphic
379 argument types and other constructs that are not resolvable at
380 function definition time. This form tracks dependencies between
381 the function and objects used in the function body, so DROP ...
382 CASCADE will work correctly, whereas the form using string
383 literals may leave dangling functions. Finally, this form is
384 more compatible with the SQL standard and other SQL
389 PostgreSQL allows function overloading; that is, the same name can be
390 used for several different functions so long as they have distinct
391 input argument types. Whether or not you use it, this capability
392 entails security precautions when calling functions in databases where
393 some users mistrust other users; see Section 10.3.
395 Two functions are considered the same if they have the same names and
396 input argument types, ignoring any OUT parameters. Thus for example
397 these declarations conflict:
398 CREATE FUNCTION foo(int) ...
399 CREATE FUNCTION foo(int, out text) ...
401 Functions that have different argument type lists will not be
402 considered to conflict at creation time, but if defaults are provided
403 they might conflict in use. For example, consider
404 CREATE FUNCTION foo(int) ...
405 CREATE FUNCTION foo(int, int default 42) ...
407 A call foo(10) will fail due to the ambiguity about which function
412 The full SQL type syntax is allowed for declaring a function's
413 arguments and return value. However, parenthesized type modifiers
414 (e.g., the precision field for type numeric) are discarded by CREATE
415 FUNCTION. Thus for example CREATE FUNCTION foo (varchar(10)) ... is
416 exactly the same as CREATE FUNCTION foo (varchar) ....
418 When replacing an existing function with CREATE OR REPLACE FUNCTION,
419 there are restrictions on changing parameter names. You cannot change
420 the name already assigned to any input parameter (although you can add
421 names to parameters that had none before). If there is more than one
422 output parameter, you cannot change the names of the output parameters,
423 because that would change the column names of the anonymous composite
424 type that describes the function's result. These restrictions are made
425 to ensure that existing calls of the function do not stop working when
428 If a function is declared STRICT with a VARIADIC argument, the
429 strictness check tests that the variadic array as a whole is non-null.
430 The function will still be called if the array has null elements.
434 Add two integers using an SQL function:
435 CREATE FUNCTION add(integer, integer) RETURNS integer
439 RETURNS NULL ON NULL INPUT;
441 The same function written in a more SQL-conforming style, using
442 argument names and an unquoted body:
443 CREATE FUNCTION add(a integer, b integer) RETURNS integer
446 RETURNS NULL ON NULL INPUT
449 Increment an integer, making use of an argument name, in PL/pgSQL:
450 CREATE OR REPLACE FUNCTION increment(i integer) RETURNS integer AS $$
456 Return a record containing multiple output parameters:
457 CREATE FUNCTION dup(in int, out f1 int, out f2 text)
458 AS $$ SELECT $1, CAST($1 AS text) || ' is text' $$
461 SELECT * FROM dup(42);
463 You can do the same thing more verbosely with an explicitly named
465 CREATE TYPE dup_result AS (f1 int, f2 text);
467 CREATE FUNCTION dup(int) RETURNS dup_result
468 AS $$ SELECT $1, CAST($1 AS text) || ' is text' $$
471 SELECT * FROM dup(42);
473 Another way to return multiple columns is to use a TABLE function:
474 CREATE FUNCTION dup(int) RETURNS TABLE(f1 int, f2 text)
475 AS $$ SELECT $1, CAST($1 AS text) || ' is text' $$
478 SELECT * FROM dup(42);
480 However, a TABLE function is different from the preceding examples,
481 because it actually returns a set of records, not just one record.
483 Writing SECURITY DEFINER Functions Safely
485 Because a SECURITY DEFINER function is executed with the privileges of
486 the user that owns it, care is needed to ensure that the function
487 cannot be misused. For security, search_path should be set to exclude
488 any schemas writable by untrusted users. This prevents malicious users
489 from creating objects (e.g., tables, functions, and operators) that
490 mask objects intended to be used by the function. Particularly
491 important in this regard is the temporary-table schema, which is
492 searched first by default, and is normally writable by anyone. A secure
493 arrangement can be obtained by forcing the temporary schema to be
494 searched last. To do this, write pg_temp as the last entry in
495 search_path. This function illustrates safe usage:
496 CREATE FUNCTION check_password(uname TEXT, pass TEXT)
497 RETURNS BOOLEAN AS $$
498 DECLARE passed BOOLEAN;
500 SELECT (pwd = $2) INTO passed
508 -- Set a secure search_path: trusted schema(s), then 'pg_temp'.
509 SET search_path = admin, pg_temp;
511 This function's intention is to access a table admin.pwds. But without
512 the SET clause, or with a SET clause mentioning only admin, the
513 function could be subverted by creating a temporary table named pwds.
515 If the security definer function intends to create roles, and if it is
516 running as a non-superuser, createrole_self_grant should also be set to
517 a known value using the SET clause.
519 Another point to keep in mind is that by default, execute privilege is
520 granted to PUBLIC for newly created functions (see Section 5.8 for more
521 information). Frequently you will wish to restrict use of a security
522 definer function to only some users. To do that, you must revoke the
523 default PUBLIC privileges and then grant execute privilege selectively.
524 To avoid having a window where the new function is accessible to all,
525 create it and set the privileges within a single transaction. For
528 CREATE FUNCTION check_password(uname TEXT, pass TEXT) ... SECURITY DEFINER;
529 REVOKE ALL ON FUNCTION check_password(uname TEXT, pass TEXT) FROM PUBLIC;
530 GRANT EXECUTE ON FUNCTION check_password(uname TEXT, pass TEXT) TO admins;
535 A CREATE FUNCTION command is defined in the SQL standard. The
536 PostgreSQL implementation can be used in a compatible way but has many
537 extensions. Conversely, the SQL standard specifies a number of optional
538 features that are not implemented in PostgreSQL.
540 The following are important compatibility issues:
541 * OR REPLACE is a PostgreSQL extension.
542 * For compatibility with some other database systems, argmode can be
543 written either before or after argname. But only the first way is
545 * For parameter defaults, the SQL standard specifies only the syntax
546 with the DEFAULT key word. The syntax with = is used in T-SQL and
548 * The SETOF modifier is a PostgreSQL extension.
549 * Only SQL is standardized as a language.
550 * All other attributes except CALLED ON NULL INPUT and RETURNS NULL
551 ON NULL INPUT are not standardized.
552 * For the body of LANGUAGE SQL functions, the SQL standard only
553 specifies the sql_body form.
555 Simple LANGUAGE SQL functions can be written in a way that is both
556 standard-conforming and portable to other implementations. More complex
557 functions using advanced features, optimization attributes, or other
558 languages will necessarily be specific to PostgreSQL in a significant
563 ALTER FUNCTION, DROP FUNCTION, GRANT, LOAD, REVOKE