Functions

About

Postgres function can be written in many different programming languages.

They are a way to extend the Postgres functionality.

Functions created will have the same privileges and ability that the built-in function possess.

triangle-exclamation

Creating

circle-exclamation
/*
    p1 type..      Make a list of parameters separated by commas
    RETURNS        Specify the return data type
    LANGUAGE       Define the language in which the function was written
*/
CREATE OR REPLACE FUNCTION function_name (p1 type, p2 type, ...)
RETURNS return_type AS
BEGIN
    -- function logic
END;
LANGUAGE language_name
circle-info

It is a good practice to name functions with fn prefix, since your created functions will stay along side all the builtin Postgres function. (Easier to differentiate)

Examples

circle-info

Postgres engine accepts the function logic to be wrapped with ' instead of the BEGIN and END keywords.

circle-info

Also use $$ to wrap the logic, if you need to use ' inside. This way you don't need to escape it.

Calling

You can call your functions, by just calling them in queries.

Deleting

triangle-exclamation

Usage

Returning void

Returning composite

Use RETURN table_name to return all columns of a table.

When accessing the returned data, wrap it with ().* to get the result spread the data into columns, instead of all the data as a single column.

Returning multiple rows

Use RETURNS SETOF to be able to return multiple rows.

Access parameters

You can access the parameters with $1, $2, and etc without specifying names.

Or if specifying parameter names.

triangle-exclamation

Default values

Using as source

You can use functions as table sources.

Last updated