Skip to main content
The CREATE FUNCTION creates a . The CREATE FUNCTION statement performs a schema change. For more information about how online schema changes work in CockroachDB, see .

Required privileges

  • To define a function, a user must have on the schema of the function.
  • To define a function with a , a user must have USAGE privilege on the user-defined type.
  • To resolve a function, a user must have at least the USAGE privilege on the schema of the function.
  • To call a function, a user must have EXECUTE privilege on the function.
  • At function definition and execution time, a user must have privileges on all the objects referenced in the function body. Privileges on referenced objects can be revoked and later function calls can fail due to lack of permission.
If you grant EXECUTE privilege as a default privilege at the database level, newly created functions inherit that privilege from the database.

Synopsis

create_func syntax diagram

Parameters

ParameterDescription
routine\_create\_nameThe name of the function.
routine\_paramA comma-separated list of function parameters.
routine\_return\_typeThe type returned by the function.
routine\_body\_strThe body of the function. For allowed contents, see .

Example of a simple function

The following statement creates a function to compute the square of integers:
The following statement invokes the sq function:

Examples of functions that reference tables

Setup

To follow along, run to start a temporary, in-memory cluster with the sample dataset preloaded:

Create a function that references a table

The following statement defines a function that returns the total number of MovR application users.

Create a function that modifies a table

The following statement defines a function that updates the rules value for a specified row in promo_codes.
Given the promo_codes row:

Create a function that uses a WHERE clause

The following statement defines a function that returns the total revenue for rides taken in European cities.

Create a function that returns a set of results

The following statement defines a function that returns information for all vehicles not in use. The SETOF clause specifies that the function should return each row as the query executes to completion.

Create a function that returns a RECORD type

The following statement defines a function that returns the information for the user that most recently completed a ride. The information is returned as a record, which takes the structure of the row that is retrieved by the selection query. In the function subquery, the latest end_time timestamp is used to determine the most recently completed ride.

Create a function that uses a loop

The following user-defined function returns the nth integer in the Fibonacci sequence. It uses the syntax to iterate through a simple calculation, and to return an error message if the specified n is negative.

See also