5 <refentry id=
"SQL-CREATEFUNCTION">
7 <refentrytitle id=
"SQL-CREATEFUNCTION-TITLE">CREATE FUNCTION
</refentrytitle>
8 <refmiscinfo>SQL - Language Statements
</refmiscinfo>
12 <refname>CREATE FUNCTION
</refname>
13 <refpurpose>define a new function
</refpurpose>
16 <indexterm zone=
"sql-createfunction">
17 <primary>CREATE FUNCTION
</primary>
22 CREATE [ OR REPLACE ] FUNCTION
23 <replaceable class=
"parameter">name
</replaceable> ( [ [
<replaceable class=
"parameter">argmode
</replaceable> ] [
<replaceable class=
"parameter">argname
</replaceable> ]
<replaceable class=
"parameter">argtype
</replaceable> [, ...] ] )
24 [ RETURNS
<replaceable class=
"parameter">rettype
</replaceable>
25 | RETURNS TABLE (
<replaceable class=
"parameter">colname
</replaceable> <replaceable class=
"parameter">coltype
</replaceable> [, ...] ) ]
26 { LANGUAGE
<replaceable class=
"parameter">langname
</replaceable>
27 | IMMUTABLE | STABLE | VOLATILE
28 | CALLED ON NULL INPUT | RETURNS NULL ON NULL INPUT | STRICT
29 | [ EXTERNAL ] SECURITY INVOKER | [ EXTERNAL ] SECURITY DEFINER
30 | COST
<replaceable class=
"parameter">execution_cost
</replaceable>
31 | ROWS
<replaceable class=
"parameter">result_rows
</replaceable>
32 | SET
<replaceable class=
"parameter">configuration_parameter
</replaceable> { TO
<replaceable class=
"parameter">value
</replaceable> | =
<replaceable class=
"parameter">value
</replaceable> | FROM CURRENT }
33 | AS '
<replaceable class=
"parameter">definition
</replaceable>'
34 | AS '
<replaceable class=
"parameter">obj_file
</replaceable>', '
<replaceable class=
"parameter">link_symbol
</replaceable>'
36 [ WITH (
<replaceable class=
"parameter">attribute
</replaceable> [, ...] ) ]
40 <refsect1 id=
"sql-createfunction-description">
41 <title>Description
</title>
44 <command>CREATE FUNCTION
</command> defines a new function.
45 <command>CREATE OR REPLACE FUNCTION
</command> will either create a
46 new function, or replace an existing definition.
50 If a schema name is included, then the function is created in the
51 specified schema. Otherwise it is created in the current schema.
52 The name of the new function must not match any existing function
53 with the same input argument types in the same schema. However,
54 functions of different argument types can share a name (this is
55 called
<firstterm>overloading<
/>).
59 To replace the current definition of an existing function, use
60 <command>CREATE OR REPLACE FUNCTION
</command>. It is not possible
61 to change the name or argument types of a function this way (if you
62 tried, you would actually be creating a new, distinct function).
63 Also,
<command>CREATE OR REPLACE FUNCTION
</command> will not let
64 you change the return type of an existing function. To do that,
65 you must drop and recreate the function. (When using
<literal>OUT<
/>
66 parameters, that means you cannot change the names or types of any
67 <literal>OUT<
/> parameters except by dropping the function.)
71 If you drop and then recreate a function, the new function is not
72 the same entity as the old; you will have to drop existing rules, views,
73 triggers, etc. that refer to the old function. Use
74 <command>CREATE OR REPLACE FUNCTION
</command> to change a function
75 definition without breaking objects that refer to the function.
76 Also,
<command>ALTER FUNCTION<
/> can be used to change most of the
77 auxiliary properties of an existing function.
81 The user that creates the function becomes the owner of the function.
86 <title>Parameters
</title>
91 <term><replaceable class=
"parameter">name
</replaceable></term>
95 The name (optionally schema-qualified) of the function to create.
101 <term><replaceable class=
"parameter">argmode
</replaceable></term>
105 The mode of an argument:
<literal>IN<
/>,
<literal>OUT<
/>,
106 <literal>INOUT<
/>, or
<literal>VARIADIC<
/>.
107 If omitted, the default is
<literal>IN<
/>.
108 Only
<literal>OUT<
/> arguments can follow a
<literal>VARIADIC<
/> one.
109 Also,
<literal>OUT<
/> and
<literal>INOUT<
/> arguments cannot be used
110 together with the
<literal>RETURNS TABLE<
/> notation.
116 <term><replaceable class=
"parameter">argname
</replaceable></term>
120 The name of an argument. Some languages (currently only PL/pgSQL) let
121 you use the name in the function body. For other languages the
122 name of an input argument is just extra documentation. But the name
123 of an output argument is significant, since it defines the column
124 name in the result row type. (If you omit the name for an output
125 argument, the system will choose a default column name.)
131 <term><replaceable class=
"parameter">argtype
</replaceable></term>
135 The data type(s) of the function's arguments (optionally
136 schema-qualified), if any. The argument types can be base, composite,
137 or domain types, or can reference the type of a table column.
140 Depending on the implementation language it might also be allowed
141 to specify
<quote>pseudotypes<
/> such as
<type>cstring<
/>.
142 Pseudotypes indicate that the actual argument type is either
143 incompletely specified, or outside the set of ordinary SQL data types.
146 The type of a column is referenced by writing
147 <literal><replaceable
148 class=
"parameter">tablename
</replaceable>.
<replaceable
149 class=
"parameter">columnname
</replaceable>%TYPE
</literal>.
150 Using this feature can sometimes help make a function independent of
151 changes to the definition of a table.
157 <term><replaceable class=
"parameter">rettype
</replaceable></term>
161 The return data type (optionally schema-qualified). The return type
162 can be a base, composite, or domain type,
163 or can reference the type of a table column.
164 Depending on the implementation language it might also be allowed
165 to specify
<quote>pseudotypes<
/> such as
<type>cstring<
/>.
166 If the function is not supposed to return a value, specify
167 <type>void<
/> as the return type.
170 When there are
<literal>OUT<
/> or
<literal>INOUT<
/> parameters,
171 the
<literal>RETURNS<
/> clause can be omitted. If present, it
172 must agree with the result type implied by the output parameters:
173 <literal>RECORD<
/> if there are multiple output parameters, or
174 the same type as the single output parameter.
177 The
<literal>SETOF
</literal>
178 modifier indicates that the function will return a set of
179 items, rather than a single item.
182 The type of a column is referenced by writing
183 <literal><replaceable
184 class=
"parameter">tablename
</replaceable>.
<replaceable
185 class=
"parameter">columnname
</replaceable>%TYPE
</literal>.
191 <term><replaceable class=
"parameter">colname
</replaceable></term>
195 The name of an output column in the
<literal>RETURNS TABLE<
/>
196 syntax. This is effectively another way of declaring a named
197 <literal>OUT<
/> parameter, except that
<literal>RETURNS TABLE<
/>
198 also implies
<literal>RETURNS SETOF<
/>.
204 <term><replaceable class=
"parameter">coltype
</replaceable></term>
208 The data type of an output column in the
<literal>RETURNS TABLE<
/>
215 <term><replaceable class=
"parameter">langname
</replaceable></term>
219 The name of the language that the function is implemented in.
220 Can be
<literal>SQL
</literal>,
<literal>C
</literal>,
221 <literal>internal
</literal>, or the name of a user-defined
222 procedural language. For backward compatibility,
223 the name can be enclosed by single quotes.
229 <term><literal>IMMUTABLE
</literal></term>
230 <term><literal>STABLE
</literal></term>
231 <term><literal>VOLATILE
</literal></term>
235 These attributes inform the query optimizer about the behavior
236 of the function. At most one choice
237 can be specified. If none of these appear,
238 <literal>VOLATILE
</literal> is the default assumption.
242 <literal>IMMUTABLE
</literal> indicates that the function
243 cannot modify the database and always
244 returns the same result when given the same argument values; that
245 is, it does not do database lookups or otherwise use information not
246 directly present in its argument list. If this option is given,
247 any call of the function with all-constant arguments can be
248 immediately replaced with the function value.
252 <literal>STABLE
</literal> indicates that the function
253 cannot modify the database,
254 and that within a single table scan it will consistently
255 return the same result for the same argument values, but that its
256 result could change across SQL statements. This is the appropriate
257 selection for functions whose results depend on database lookups,
258 parameter variables (such as the current time zone), etc. Also note
259 that the
<function>current_timestamp<
/> family of functions qualify
260 as stable, since their values do not change within a transaction.
264 <literal>VOLATILE
</literal> indicates that the function value can
265 change even within a single table scan, so no optimizations can be
266 made. Relatively few database functions are volatile in this sense;
267 some examples are
<literal>random()<
/>,
<literal>currval()<
/>,
268 <literal>timeofday()<
/>. But note that any function that has
269 side-effects must be classified volatile, even if its result is quite
270 predictable, to prevent calls from being optimized away; an example is
271 <literal>setval()<
/>.
275 For additional details see
<xref linkend=
"xfunc-volatility">.
281 <term><literal>CALLED ON NULL INPUT
</literal></term>
282 <term><literal>RETURNS NULL ON NULL INPUT
</literal></term>
283 <term><literal>STRICT
</literal></term>
287 <literal>CALLED ON NULL INPUT
</literal> (the default) indicates
288 that the function will be called normally when some of its
289 arguments are null. It is then the function author's
290 responsibility to check for null values if necessary and respond
295 <literal>RETURNS NULL ON NULL INPUT
</literal> or
296 <literal>STRICT
</literal> indicates that the function always
297 returns null whenever any of its arguments are null. If this
298 parameter is specified, the function is not executed when there
299 are null arguments; instead a null result is assumed
306 <term><literal><optional>EXTERNAL
</optional> SECURITY INVOKER
</literal></term>
307 <term><literal><optional>EXTERNAL
</optional> SECURITY DEFINER
</literal></term>
311 <literal>SECURITY INVOKER
</literal> indicates that the function
312 is to be executed with the privileges of the user that calls it.
313 That is the default.
<literal>SECURITY DEFINER
</literal>
314 specifies that the function is to be executed with the
315 privileges of the user that created it.
319 The key word
<literal>EXTERNAL
</literal> is allowed for SQL
320 conformance, but it is optional since, unlike in SQL, this feature
321 applies to all functions not only external ones.
327 <term><replaceable class=
"parameter">execution_cost
</replaceable></term>
331 A positive number giving the estimated execution cost for the function,
332 in units of
<xref linkend=
"guc-cpu-operator-cost">. If the function
333 returns a set, this is the cost per returned row. If the cost is
334 not specified,
1 unit is assumed for C-language and internal functions,
335 and
100 units for functions in all other languages. Larger values
336 cause the planner to try to avoid evaluating the function more often
343 <term><replaceable class=
"parameter">result_rows
</replaceable></term>
347 A positive number giving the estimated number of rows that the planner
348 should expect the function to return. This is only allowed when the
349 function is declared to return a set. The default assumption is
356 <term><replaceable>configuration_parameter
</replaceable></term>
357 <term><replaceable>value
</replaceable></term>
360 The
<literal>SET<
/> clause causes the specified configuration
361 parameter to be set to the specified value when the function is
362 entered, and then restored to its prior value when the function exits.
363 <literal>SET FROM CURRENT<
/> saves the session's current value of
364 the parameter as the value to be applied when the function is entered.
368 See
<xref linkend=
"sql-set" endterm=
"sql-set-title"> and
369 <xref linkend=
"runtime-config">
370 for more information about allowed parameter names and values.
376 <term><replaceable class=
"parameter">definition
</replaceable></term>
380 A string constant defining the function; the meaning depends on the
381 language. It can be an internal function name, the path to an
382 object file, an SQL command, or text in a procedural language.
388 <term><literal><replaceable class=
"parameter">obj_file
</replaceable>,
<replaceable class=
"parameter">link_symbol
</replaceable></literal></term>
392 This form of the
<literal>AS
</literal> clause is used for
393 dynamically loadable C language functions when the function name
394 in the C language source code is not the same as the name of
395 the SQL function. The string
<replaceable
396 class=
"parameter">obj_file
</replaceable> is the name of the
397 file containing the dynamically loadable object, and
398 <replaceable class=
"parameter">link_symbol
</replaceable> is the
399 function's link symbol, that is, the name of the function in the C
400 language source code. If the link symbol is omitted, it is assumed
401 to be the same as the name of the SQL function being defined.
407 <term><replaceable class=
"parameter">attribute
</replaceable></term>
411 The historical way to specify optional pieces of information
412 about the function. The following attributes can appear here:
416 <term><literal>isStrict<
/></term>
419 Equivalent to
<literal>STRICT
</literal> or
<literal>RETURNS NULL ON NULL INPUT
</literal>.
425 <term><literal>isCachable<
/></term>
428 <literal>isCachable
</literal> is an obsolete equivalent of
429 <literal>IMMUTABLE
</literal>; it's still accepted for
430 backwards-compatibility reasons.
437 Attribute names are not case-sensitive.
446 <refsect1 id=
"sql-createfunction-notes">
450 Refer to
<xref linkend=
"xfunc"> for further information on writing
455 The full
<acronym>SQL
</acronym> type syntax is allowed for
456 input arguments and return value. However, some details of the
457 type specification (e.g., the precision field for
458 type
<type>numeric
</type>) are the responsibility of the
459 underlying function implementation and are silently swallowed
460 (i.e., not recognized or
461 enforced) by the
<command>CREATE FUNCTION
</command> command.
465 <productname>PostgreSQL
</productname> allows function
466 <firstterm>overloading
</firstterm>; that is, the same name can be
467 used for several different functions so long as they have distinct
468 input argument types. However, the C names of all functions must be
469 different, so you must give overloaded C functions different C
470 names (for example, use the argument types as part of the C
475 Two functions are considered the same if they have the same names and
476 <emphasis>input<
/> argument types, ignoring any
<literal>OUT<
/>
477 parameters. Thus for example these declarations conflict:
479 CREATE FUNCTION foo(int) ...
480 CREATE FUNCTION foo(int, out text) ...
485 When repeated
<command>CREATE FUNCTION
</command> calls refer to
486 the same object file, the file is only loaded once per session.
488 reload the file (perhaps during development), use the
<xref
489 linkend=
"sql-load" endterm=
"sql-load-title"> command.
493 Use
<xref linkend=
"sql-dropfunction"
494 endterm=
"sql-dropfunction-title"> to remove user-defined
499 It is often helpful to use dollar quoting (see
<xref
500 linkend=
"sql-syntax-dollar-quoting">) to write the function definition
501 string, rather than the normal single quote syntax. Without dollar
502 quoting, any single quotes or backslashes in the function definition must
503 be escaped by doubling them.
507 If a
<literal>SET<
/> clause is attached to a function, then
508 the effects of a
<command>SET LOCAL<
/> command executed inside the
509 function for the same variable are restricted to the function: the
510 configuration parameter's prior value is still restored at function exit.
512 <command>SET<
/> command (without
<literal>LOCAL<
/>) overrides the
513 <literal>SET<
/> clause, much as it would do for a previous
<command>SET
514 LOCAL<
/> command: the effects of such a command will persist after
515 function exit, unless the current transaction is rolled back.
519 To be able to define a function, the user must have the
520 <literal>USAGE
</literal> privilege on the language.
525 <refsect1 id=
"sql-createfunction-examples">
526 <title>Examples
</title>
529 Here are some trivial examples to help you get started. For more
530 information and examples, see
<xref linkend=
"xfunc">.
532 CREATE FUNCTION add(integer, integer) RETURNS integer
536 RETURNS NULL ON NULL INPUT;
541 Increment an integer, making use of an argument name, in
542 <application>PL/pgSQL
</application>:
544 CREATE OR REPLACE FUNCTION increment(i integer) RETURNS integer AS $$
553 Return a record containing multiple output parameters:
555 CREATE FUNCTION dup(in int, out f1 int, out f2 text)
556 AS $$ SELECT $
1, CAST($
1 AS text) || ' is text' $$
559 SELECT * FROM dup(
42);
561 You can do the same thing more verbosely with an explicitly named
564 CREATE TYPE dup_result AS (f1 int, f2 text);
566 CREATE FUNCTION dup(int) RETURNS dup_result
567 AS $$ SELECT $
1, CAST($
1 AS text) || ' is text' $$
570 SELECT * FROM dup(
42);
572 Another way to return multiple columns is to use a
<literal>TABLE<
/>
575 CREATE FUNCTION dup(int) RETURNS TABLE(f1 int, f2 text)
576 AS $$ SELECT $
1, CAST($
1 AS text) || ' is text' $$
579 SELECT * FROM dup(
42);
581 However, a
<literal>TABLE<
/> function is different from the
582 preceding examples, because it actually returns a
<emphasis>set<
/>
583 of records, not just one record.
587 <refsect1 id=
"sql-createfunction-security">
588 <title>Writing
<literal>SECURITY DEFINER
</literal> Functions Safely
</title>
591 Because a
<literal>SECURITY DEFINER
</literal> function is executed
592 with the privileges of the user that created it, care is needed to
593 ensure that the function cannot be misused. For security,
594 <xref linkend=
"guc-search-path"> should be set to exclude any schemas
595 writable by untrusted users. This prevents
596 malicious users from creating objects that mask objects used by the
597 function. Particularly important in this regard is the
598 temporary-table schema, which is searched first by default, and
599 is normally writable by anyone. A secure arrangement can be had
600 by forcing the temporary schema to be searched last. To do this,
601 write
<literal>pg_temp<
/> as the last entry in
<varname>search_path<
/>.
602 This function illustrates safe usage:
606 CREATE FUNCTION check_password(uname TEXT, pass TEXT)
607 RETURNS BOOLEAN AS $$
608 DECLARE passed BOOLEAN;
610 SELECT (pwd = $
2) INTO passed
618 -- Set a secure search_path: trusted schema(s), then 'pg_temp'.
619 SET search_path = admin, pg_temp;
623 Before
<productname>PostgreSQL
</productname> version
8.3, the
624 <literal>SET<
/> option was not available, and so older functions may
625 contain rather complicated logic to save, set, and restore
626 <varname>search_path<
/>. The
<literal>SET<
/> option is far easier
627 to use for this purpose.
631 Another point to keep in mind is that by default, execute privilege
632 is granted to
<literal>PUBLIC<
/> for newly created functions
633 (see
<xref linkend=
"sql-grant" endterm=
"sql-grant-title"> for more
634 information). Frequently you will wish to restrict use of a security
635 definer function to only some users. To do that, you must revoke
636 the default
<literal>PUBLIC<
/> privileges and then grant execute
637 privilege selectively. To avoid having a window where the new function
638 is accessible to all, create it and set the privileges within a single
639 transaction. For example:
644 CREATE FUNCTION check_password(uname TEXT, pass TEXT) ... SECURITY DEFINER;
645 REVOKE ALL ON FUNCTION check_password(uname TEXT, pass TEXT) FROM PUBLIC;
646 GRANT EXECUTE ON FUNCTION check_password(uname TEXT, pass TEXT) TO admins;
653 <refsect1 id=
"sql-createfunction-compat">
654 <title>Compatibility
</title>
657 A
<command>CREATE FUNCTION
</command> command is defined in SQL:
1999 and later.
658 The
<productname>PostgreSQL
</productname> version is similar but
659 not fully compatible. The attributes are not portable, neither are the
660 different available languages.
664 For compatibility with some other database systems,
665 <replaceable class=
"parameter">argmode
</replaceable> can be written
666 either before or after
<replaceable class=
"parameter">argname
</replaceable>.
667 But only the first way is standard-compliant.
673 <title>See Also
</title>
675 <simplelist type=
"inline">
676 <member><xref linkend=
"sql-alterfunction" endterm=
"sql-alterfunction-title"></member>
677 <member><xref linkend=
"sql-dropfunction" endterm=
"sql-dropfunction-title"></member>
678 <member><xref linkend=
"sql-grant" endterm=
"sql-grant-title"></member>
679 <member><xref linkend=
"sql-load" endterm=
"sql-load-title"></member>
680 <member><xref linkend=
"sql-revoke" endterm=
"sql-revoke-title"></member>
681 <member><xref linkend=
"app-createlang" endterm=
"app-createlang-title"></member>