Creating user-defined functions
As in almost all other programming or scripting languages, functions in SQL contain sections of code that provide a lot of benefits, such as efficient code reuse and simplified troubleshooting processes. You can use functions to repeat or modify statements or queries without re-entering the statement each time or searching for its use throughout longer code segments. Another powerful aspect of functions is that they allow you to break code into smaller, testable chunks, which makes the application easier to manage.
So, how do you define functions in SQL? There is a relatively straightforward syntax, with the SQL syntax keywords:
CREATE FUNCTION function_name (function_arguments)
RETURNS return_type AS $return_name$
DECLARE return_name return_type;
BEGIN
  <function statements>;
  RETURN <return_value>;
END;
$return_name$
LANGUAGE PLPGSQL;
The following is a short explanation of the functions used in the preceding...