postgresqlHow do I create a PostgreSQL function?
Creating a PostgreSQL function is simple and straightforward. To create a function, you must use the CREATE FUNCTION
statement. The syntax is as follows:
CREATE FUNCTION function_name(parameter_list)
RETURNS return_type AS
$$
BEGIN
-- function body
END;
$$
LANGUAGE language_name;
The function_name
is the name of the function to be created. The parameter_list
is a comma-separated list of parameters that the function will accept. The return_type
is the data type of the value that the function will return. The language_name
is the programming language used to write the function body.
For example, the following function takes two parameters, a
and b
, and returns the sum of the two parameters:
CREATE FUNCTION add_two_numbers(a INT, b INT)
RETURNS INT AS
$$
BEGIN
RETURN a + b;
END;
$$
LANGUAGE plpgsql;
The output of the above code is:
CREATE FUNCTION
List of code parts explanation
CREATE FUNCTION
: This is the statement used to create a PostgreSQL function.function_name
: This is the name of the function to be created.parameter_list
: This is a comma-separated list of parameters that the function will accept.return_type
: This is the data type of the value that the function will return.language_name
: This is the programming language used to write the function body.RETURN
: This statement is used to return a value from the function.
Relevant Links
More of Postgresql
- How do I use PostgreSQL ZonedDateTime to store date and time information?
- How can I use PostgreSQL XOR to compare two values?
- How can I troubleshoot zero damaged pages in PostgreSQL?
- How do I use PostgreSQL's XMLTABLE to parse XML data?
- How do I parse XML data using PostgreSQL?
- How do I access the PostgreSQL wiki?
- How do I show tables in PostgreSQL?
- How can I set a PostgreSQL interval to zero?
- How can Zalando use PostgreSQL to improve its software development?
- How can I use PostgreSQL with YAML?
See more codes...