Open In App

PostgreSQL – CREATE FUNCTION Statement

In PostgreSQL CREATE FUNCTION statement to develop user-defined functions.

Syntax:
create [or replace] function function_name(param_list)
   returns return_type 
   language plpgsql
  as
$$
declare 
-- variable declaration
begin
 -- logic
end;
$$

Let’s analyze the above syntax:



For the purpose of example, we will use the sample database ie, dvdrental.

Example:



The following statement creates a function that counts the films whose length between the len_from and len_to parameters:

create function get_film_count(len_from int, len_to int)
returns int
language plpgsql
as
$$
declare
   film_count integer;
begin
   select count(*) 
   into film_count
   from film
   where length between len_from and len_to;
   
   return film_count;
end;
$$;

The function get_film_count has two main sections: header and body. 

In the Header section:

In the Body section:

Now that we got familiar with the structure of the CREATE FUNCTION statement, let’s create a function using the same.

First, launch the psql interactive tool and connect to the dvdrental database and enter the above code in the psql to create the function like this:

create function get_film_count(len_from int, len_to int)
 returns int
 language plpgsql
 as
 $$
 declare
    film_count integer;
 begin
   select count(*)
    into film_count
   from film
   where length between len_from and len_to;

   return film_count;
 end;
$$;

You will see the following message if the function is created successfully as shown below:

Finally, use the below command to list all user-defined in the current database:

\df

This will show you all the user-defined functions in the database as shown below:

Article Tags :