On a broader level, PostgreSQL supports several procedural languages that help sustain data models that repeat previous values. PostgreSQL Stored Procedures support procedural operations, which are helpful while building powerful database apps — they increase their performance, productivity, and scalability. Like UDFs, stored procedures are a sequence of SQL statements available to apps that access an RDBMS.

In short, developing custom functions becomes easier using the PostgreSQL Stored Procedures. Moreover, once created, you can deploy stored procedures in any app based on your requirements. So, with this ultimate guide, you will learn about Stored Procedures in PostgreSQL in detail. And, through some workflow examples, you will also be able to apply the learnings in real-life situations, too. Let’s begin.

How to CREATE OR REPLACE PostgreSQL Stored Procedures?

In PostgreSQL, CREATE OR REPLACE PROCEDURE exists to create a new procedure or deploy a new definition in place of an existing one. To be able to CREATE OR REPLACE PROCEDURE, for a user in PostgreSQL, having a USAGE privilege on the language is a prerequisite.

The syntax to CREATE or REPLACE PostgreSQL Stored Procedures is given below:

CREATE [ OR REPLACE ] PROCEDURE
    name ( [ [ argmode ] [ argname ] argtype [ { DEFAULT | = } default_expr ] [, ...] ] )
  { LANGUAGE lang_name
    | TRANSFORM { FOR TYPE type_name } [, ... ]
    | [ EXTERNAL ] SECURITY INVOKER | [ EXTERNAL ] SECURITY DEFINER
    | SET configuration_parameter { TO value | = value | FROM CURRENT }
    | AS 'definition'
    | AS 'obj_file', 'link_symbol'
    | sql_body
  }
  1. A procedure is generated in the schema if a schema name is provided. Otherwise, the existing schema captures the newly built one within itself.
  2. CREATE or REPLACE PROCEDURE can be used to change/replace the existing definition of the current procedure. The ownership and permissions will not change.
  3. You must have USAGE privilege on the argument types to build a procedure.
  4. The user who creates the procedure becomes the procedure’s owner.

The syntax given above is more generic to stored procedures. The one below is for PostgreSQL. 

create [or replace] procedure procedure_name(parameter_list)
language plpgsql
as $$
declare
-- variable declaration
begin
-- stored procedure body
end; $$
Code language: SQL (Structured Query Language) (sql)

Let’s break down the components In this syntax:

  • Write the name of the stored procedure after the create procedure keywords.
  • Set the parameters for the stored procedure. If not, a stored procedure can accept zero as well.
  • Mention plpgsql as the procedural language for the stored procedure.
  • Utilize the dollar-quoted string constant syntax to write the body of the stored procedure.

Note that parameters in stored procedures can’t have the out mode, but in and inout modes. As a stored procedure can’t return a value, you won’t be able to use the return statement with a value inside a store procedure like this:

return expression;
Code language: JavaScript (javascript)

But to stop the stored procedure immediately, you can utilitze the return statement without the expression as given: 

return;
Code language: SQL (Structured Query Language) (sql)
Scale your data integration effortlessly with Hevo’s Fault-Tolerant No Code Data Pipeline

Looking for an easy way to replicate data from PostgreSQL? 1000+ data teams rely on Hevo’s Data Pipeline Platform to integrate data from over 150+ sources in a matter of minutes. Hevo puts complete control in the hands of data teams with intuitive dashboards for pipeline monitoring, auto-schema management, and custom ingestion/loading schedules. 

This, combined with transparent pricing and 24×7 support, makes us the most loved data pipeline software on review sites. Take our 14-day free trial to experience a better way to manage data pipelines.

Get Started for Free with Hevo

Workflow Example

Let’s use a stored_Procedure_Prac table to understand the PostgreSQL Stored Procedure better. We will use an online editor, OneCompiler, to write and run PostgreSQL queries for demo purposes.

Step 1: Create a table with the following inputs, as shown in the code block below.

create table stored_Procedure_Prac (
    id int generated by default as identity,
    name varchar(100) not null,
    balance dec(15, 2) not null,
    primary key(id)
);

insert into stored_Procedure_Prac(name, balance)
values('Don', 400000);

insert into stored_Procedure_Prac(name, balance)
values('Bob', 400000);

Step 2: Now run an SQL query to show the table.

select * from stored_Procedure_Prac;

The following shall be the result:

Output of SQL Query to Show Table
Output of SQL Query to Show Table

Step 3: The query below produces a stored procedure called prac_transfer, which transfers a specific amount of money from one account to another.

create or replace procedure prac_transfer(
   sender int,
   receiver int, 
   amount dec
)
language plpgsql    
as $$
begin
    -- subtracting the amount from the sender's account 
    update accounts 
    set balance = balance - amount 
    where id = sender;

    -- adding the amount to the receiver's account
    update accounts 
    set balance = balance + amount 
    where id = receiver;

    commit;
end;$$;

Step 4: Now call a stored procedure. Use the below-given query; a CALL statement is used.

call prac_transfer(1, 2, 1000);

The result would look like this:

Output of CALL Statement
Output of CALL Statement

Step 5: Now verify the results by running the following query.

SELECT * FROM stored_Procedure_Prac;
Query for Verifying Results
Query for Verifying Results

PostgreSQL Stored Procedure vs Function

A function returns a result, but a stored procedure does not. The reason is simple: the sole purpose of a stored procedure is to proceed with an action to complete it. Post that, the control is returned to the caller.

Do you know? Before PostgreSQL 11, stored procedures were functions that did not return data.

Using one of the PostgreSQL Stored Procedures examples query, let’s distinguish:

PostgreSQL Stored Procedures’ Query 

CREATE PROCEDURE deactivate_unpaid_accounts()
LANGUAGE SQL
AS $$
  UPDATE accounts SET active = false WHERE balance < 0;
$$;

For calling purposes, post PostgreSQL 11, we use the CALL statement as shown below:

CALL deactivate_unpaid_accounts();

PostgreSQL Function’s Query

CREATE FUNCTION deactivate_unpaid_accounts() RETURNS void
LANGUAGE SQL
AS $$
  UPDATE accounts SET active = false WHERE balance < 0;
$$;

For calling purposes, we used the SELECT statement, not CALL statement, as shown below:

SELECT deactivate_unpaid_accounts();

How Do PostgreSQL Stored Procedures Affect Your Workflow (Advantages vs Disadvantages)?

AdvantagesDisadvantages
As stored Procedures can be reintroduced as often as possible, the number of visits between application and database servers is dramatically reduced. Using PostgreSQL Stored Procedures can slow down the software development process because stored procedure programming necessitates specific abilities that many developers lack. (This is a human resources challenge)
To retrieve the results and remove the waiting time to get a response, now the app simply has to issue a function call instead of sending SQL statements.It is difficult to manage workflow as many versions exist, and difficulty when debugging can not be undermined either.
The application’s performance is increased. The user-defined functions and stored procedures are now pre-combined in the PostgreSQL database server.A portability issue exists. Other DBMS systems like MySQL and MS SQL Server are not supported.
Pros and Cons of PostgreSQL Stored Procedures

Conclusion

This article provided an in-depth knowledge of PostgreSQL Stored procedures. Through this article and a workflow example, we learned to CREATE OR REPLACE a stored procedure. We also discussed how Stored Procedures are different from Functions.

If you want to continue your learning of PostgreSQL Commands and operations, go through either of the two articles provided below:

  1. The Ultimate Guide to PostgreSQL Subquery for 2022
  2. PostgreSQL MAX() Function: Syntax, Working & Examples

Hevo is the only real-time ELT No-code Data Pipeline platform that cost-effectively automates data pipelines that are flexible to your needs. With integration with 150+ Data Sources (40+ free sources), we help you not only export data from sources & load data to the destinations but also transform & enrich your data, & make it analysis-ready. 

Want to give Hevo a try? Sign Up for a 14-day free trial and experience the feature-rich Hevo suite first hand. You may also look at the price, which will assist you in selecting the best plan for your requirements.

Reference: PostgreSQL tutorial

Yash Arora
Former Content Manager, Hevo Data

Yash is a Content Marketing professinal with experience in data-driven marketing campaigns. He has expertise in strategic thinking, integrated marketing, and customer acquisition. She has driven growth for startups and established brands through comprehensive marketing communications, and digital strategies.

No-code Data Pipeline for PostgreSQL