DEV Community

Sami Tariq
Sami Tariq

Posted on

What is a PostgreSQL stored procedure?

A PostgreSQL stored procedure is a collection of SQL statements that are grouped together and saved as a single unit. Stored procedures can be used to perform a variety of tasks, such as:

  • Encapsulating business logic: Stored procedures can be used to encapsulate business logic, making it easier to maintain and reuse.
  • Providing security: Stored procedures can be used to provide security by restricting access to certain data or functions.
  • Improving performance: Stored procedures can improve performance by reducing the number of times that SQL statements have to be executed.

Creating a PostgreSQL stored procedure

To create a PostgreSQL stored procedure, you use the CREATE PROCEDURE statement. The CREATE PROCEDURE statement has the following syntax:

CREATE PROCEDURE procedure_name
(
  [parameter_name [type] [default_value] [, ...]
)
AS
BEGIN
  [statement_1];
  [statement_2];
  [...];
END;
Enter fullscreen mode Exit fullscreen mode

The procedure_name is the name of the stored procedure. The parameter_name is the name of the parameter. The type is the type of the parameter. The default_value is the default value of the parameter. The BEGIN and END keywords mark the beginning and end of the stored procedure body.

Example of a PostgreSQL stored procedure

The following is an example of a PostgreSQL stored procedure that is defined to calculate the total sales of a product:

CREATE PROCEDURE calculate_total_sales
(
  product_id integer
)
AS
BEGIN
  DECLARE total_sales numeric;

  SELECT sum(price * quantity) INTO total_sales
  FROM orders
  WHERE product_id = product_id;

  RETURN total_sales;
END;
Enter fullscreen mode Exit fullscreen mode

This stored procedure takes a product ID as input and returns the total sales of the product.

Calling a PostgreSQL stored procedure

To call a PostgreSQL stored procedure, you use the CALL statement. The CALL statement has the following syntax:

CALL procedure_name([parameter_value [, ...]]);
Enter fullscreen mode Exit fullscreen mode

The procedure_name is the name of the stored procedure. The parameter_value is the value of the parameter.

Example of calling a PostgreSQL stored procedure

The following is an example of calling the calculate_total_sales stored procedure:

SELECT CALL calculate_total_sales(12345);
Enter fullscreen mode Exit fullscreen mode

This statement will call the calculate_total_sales stored procedure and return the total sales of the product with ID 12345.

Conclusion

PostgreSQL stored procedures are a powerful tool that can be used to encapsulate business logic, provide security, and improve performance. By understanding how to create and call PostgreSQL stored procedures, you can improve the functionality and performance of your PostgreSQL databases.

I hope this article has been helpful. Please let me know if you have any questions.

Top comments (0)