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.
User defined functions CANNOT execute Transactions.
Creating
Functions can be overloaded (created with the same name, but different arguments).
/*
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_nameExamples
Calling
You can call your functions, by just calling them in queries.
Deleting
Since functions can be overloaded, Postgres need to know which function you want to remove by checking the argument_list.
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.
Avoid using parameter's names the same as table column's names, or it may conflict.
Default values
Using as source
You can use functions as table sources.
Last updated