How to Create a Function in PostgreSQL
Although PostgreSQL offers a wide variety of built-in functions, there are times you’ll want to create your own function to meet your application’s requirements. It’s easy to accomplish this task with the help of the
CREATE FUNCTION statement, which allows you to build a new PostgreSQL function or replace an existing one. In this article, we’ll explain how to create PostgreSQL functions and show you some real-life examples.
Let’s begin our discussion by reviewing some prerequisites that need to be in place before you can create PostgreSQL functions:
- You’ll need to ensure that PostgreSQL server has been properly installed and configured. The service must be running in the background.
You can download PostgreSQL for Windows and Linux here.
To start up the PostgreSQL server using Linux, you can use the following command:
sudo service postgresql start
- You can confirm that the PostgreSQL service is running with the following command:
service postgresql status
The output of this command should look something like the following:
â— postgresql.service - PostgreSQL RDBMS
Loaded: loaded (/lib/systemd/system/postgresql.service; enabled; vendor prese
Active: active (exited) since Thu 2019-08-01 14:51:20 PST; 36min ago
Process: 1230 ExecStart=/bin/true (code=exited, status=0/SUCCESS)
Main PID: 1230 (code=exited, status=0/SUCCESS)
Aug 01 14:51:20 user-UX330UAK systemd: Starting PostgreSQL RDBMS...
Aug 01 14:51:20 user-UX330UAK systemd: Started PostgreSQL RDBMS.
lines 1-8/8 (END)
- The instructions for starting, stopping and restarting PostgreSQL server in a Windows environment are somewhat different:
- First, open Control Panel
- Next, open Administrative Tools
- Open Services
- In the Services area, find the PostgreSQL Server service
- Finally, start, stop or restart the service
What is a PostgreSQL Function?
PostgreSQL functions are somewhat similar to stored procedures. These functions are composed of a series of statements– assignments, declarations, flow-of-control, loops and more– that get saved on the server and can then be called using SQL. PostgreSQL functions allow users to perform operations that would otherwise take multiple queries and back-and-forth trips in the database.
Shown below is the syntax used to create PostgreSQL functions:
CREATE [OR REPLACE] FUNCTION your_function_name (your_parameters)
RETURNS return_datatype AS
< function_body >
There’s a lot going on inside this SQL statement, so let’s look at it one part at a time:
First, we indicate the name of the function following the keywords
REPLACE. These keywords specify whether we will be creating a brand-new function or replacing an existing function.
We can create a group of parameters separated by commas inside the parentheses that come after the defined function name.
We can indicate the data type to be returned by our function after the keyword
ENDblock, we insert the code or the logic of the function.
Finally, we specify the language to be used by the function; in this case, it is
Example of How to Create a PostgreSQL Function
Now that we have a basic understanding of how to create PostgreSQL functions, let’s put our knowledge to work in a basic application.
We’ll start by making sure that the PostgreSQL server service is running in the background.
Then, we’ll use the following syntax on the command line to create a function that will add two numeric parameters and return the result:
CREATE FUNCTION add_int(val1 INTEGER, val2 INTEGER) RETURNS INTEGER AS $$
RETURN val1 + val2;
The “$” in this example is used as part of a PostgreSQL feature called dollar quoting. This feature enables us to include string constants without escaping any characters. When you run this statement, PostgreSQL will notify you by outputting the words “CREATE FUNCTION” to confirm that the function was successfully created; otherwise, an error will be returned.
Let’s test the basic function that we created by using the syntax shown below:
You can see that we called our newly-created function
add_int() and provided two numeric values, separated by commas, as its parameters.
The output of this function should look something like this:
As we expected, the function returns a numeric value calculated by adding the two parameters.
When you’re working with data in PostgreSQL, it’s important to know how to create your own functions. User-defined functions allow you to build reusable bits of code instead of creating the same sets of queries over and over again. In this article, we introduced the concept of functions in PostgreSQL and provided examples that demonstrate how to create PostgreSQL functions. With the information provided in this tutorial, you’ll be able to define your own PostgreSQL functions and streamline your database tasks.
Pilot the ObjectRocket Platform Free!
Try Fully-Managed CockroachDB, Elasticsearch, MongoDB, PostgreSQL (Beta) or Redis.Get Started