CREATE FUNCTION

Synopsis

Use the CREATE FUNCTION statement to define a new function in a database.

Syntax

  1. create_function ::= CREATE [ OR REPLACE ] FUNCTION name (
  2. [ arg_decl [ , ... ] ] )
  3. [ RETURNS type_name
  4. | RETURNS TABLE ( { column_name type_name }
  5. [ , ... ] ) ]
  6. { LANGUAGE lang_name
  7. | TRANSFORM { FOR TYPE type_name } [ , ... ]
  8. | WINDOW
  9. | IMMUTABLE
  10. | STABLE
  11. | VOLATILE
  12. | [ NOT ] LEAKPROOF
  13. | CALLED ON NULL INPUT
  14. | RETURNS NULL ON NULL INPUT
  15. | STRICT
  16. | [ EXTERNAL ] SECURITY INVOKER
  17. | [ EXTERNAL ] SECURITY DEFINER
  18. | PARALLEL { UNSAFE | RESTRICTED | SAFE }
  19. | COST int_literal
  20. | ROWS int_literal
  21. | SET configuration_parameter
  22. { TO value | = value | FROM CURRENT }
  23. | AS 'definition'
  24. | AS 'obj_file' 'link_symbol' } [ ... ]
  25. arg_decl ::= [ argmode ] [ argname ] argtype
  26. [ { DEFAULT | = } expression ]

create_function

CREATE FUNCTION - 图1

arg_decl

CREATE FUNCTION - 图2

Semantics

  • If a function with the given name and argument types already exists then CREATE FUNCTION will throw an error unless the CREATE OR REPLACE FUNCTION version is used.In that case it will replace any existing definition instead.

  • The languages supported by default are sql, plpgsql and C.

  • VOLATILE, STABLE and IMMUTABLE inform the query optimizer about the behavior the function.

    • VOLATILE is the default and indicates that the function result could be different for every call. For instance random() or now().
    • STABLE indicates that the function cannot modify the database so that within a single scan it will return the same result given the same arguments.
    • IMMUTABLE indicates that the function cannot modify the database and always returns the same results given the same arguments.
  • CALLED ON NULL INPUT, RETURNS NULL ON NULL INPUT and STRICT define the function’s behavior with respect to ‘null’s.

    • CALLED ON NULL INPUT indicates that input arguments may be null.
    • RETURNS NULL ON NULL INPUT or STRICT indicate that the function always returns null if any of its arguments are null.

Examples

Define a function using the SQL language.

  1. CREATE FUNCTION mul(integer, integer) RETURNS integer
  2. AS 'SELECT $1 * $2;'
  3. LANGUAGE SQL
  4. IMMUTABLE
  5. RETURNS NULL ON NULL INPUT;
  6. SELECT mul(2,3), mul(10, 12);
  1. mul | mul
  2. -----+-----
  3. 6 | 120
  4. (1 row)

Define a function using the PL/pgSQL language.

  1. CREATE OR REPLACE FUNCTION inc(i integer) RETURNS integer AS $$
  2. BEGIN
  3. RAISE NOTICE 'Incrementing %', i ;
  4. RETURN i + 1;
  5. END;
  6. $$ LANGUAGE plpgsql;
  7. SELECT inc(2), inc(5), inc(10);
  1. NOTICE: Incrementing 2
  2. NOTICE: Incrementing 5
  3. NOTICE: Incrementing 10
  4. inc | inc | inc
  5. -----+-----+-----
  6. 3 | 6 | 11
  7. (1 row)

See also