It's time to write your first function. Before you do so, let's look in more detail at the syntax of a function.
Every function has a name, body, some optional arguments, and a return type.
In PostgreSQL, we can use many languages to create functions (Perl, Python, etc.). However, PL/pgSQL is the most common language in PostgreSQL, and it's the one we'll be using in this course. The syntax of PL/pgSQL is modelled after Oracle's procedural language PL/SQL (hence the name PL/pgSQL):
CREATE FUNCTION function_name (arg1 type, ... , argN type)
RETURNS return_type AS $$
-- function body
$$ LANGUAGE PLpgSQL;
The syntax of creating functions in PostgreSQL is a bit verbose. First we use the
CREATE FUNCTION keyword. Then we specify the name of the function and its parameters in parentheses. Next, after the
RETURNS keyword, we specify the return type of the function.
The body function is surrounded with a bit of boilerplate code:
AS $$ BEGIN before the function body and
END; $$ after the function body. Finally, after the
LANGUAGE keyword, we specify the programming language we use to create the function (
PLpgSQL in our case).