← Back to PostgreSQL Course | Chapter 10: Advanced Features | Lesson 3 of 7

Stored procedures

Stored procedures and functions store reusable logic inside the database, written in PL/pgSQL or other languages.

In this page:

  1. Stored procedures
Syntax
sql
CREATE FUNCTION function_name(param type) RETURNS type AS $$
BEGIN
  RETURN expression;
END;
$$ LANGUAGE plpgsql;

CREATE PROCEDURE procedure_name(param type) AS $$
BEGIN
  -- statements
END;
$$ LANGUAGE plpgsql;
CALL procedure_name(value);

Stored procedures

CREATE FUNCTION returns a value and can be used inside queries, while CREATE PROCEDURE (PostgreSQL 11 and later) is invoked with CALL and can control transactions.

PL/pgSQL adds variables, IF, loops and exceptions. Use them for data-heavy logic close to the data, but keep business logic testable.

Note: Functions are used in queries; procedures are run with CALL.

Example: Stored procedures

bash
shop=# CREATE FUNCTION add_tax(price numeric, rate numeric DEFAULT 0.2) RETURNS numeric
shop-# LANGUAGE sql IMMUTABLE AS $$ SELECT round(price * (1 + rate), 2) $$;
shop=# SELECT add_tax(100), add_tax(100, 0.1);
 add_tax | add_tax
---------+---------
  120.00 |  110.00
shop=# CREATE PROCEDURE archive_old_orders(cutoff date) LANGUAGE plpgsql AS $$
shop$# BEGIN
shop$#   INSERT INTO orders_archive SELECT * FROM orders WHERE created_at < cutoff;
shop$#   DELETE FROM orders WHERE created_at < cutoff;
shop$# END $$;
shop=# CALL archive_old_orders('2023-01-01');
CALL

⚠️ Run this in your own terminal or Node.js environment.

Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. Putting all business logic in the database
  2. Forgetting to declare variables
  3. Confusing functions and procedures
Chapter Summary
  • FUNCTION returns a value
  • PROCEDURE is run with CALL
  • PL/pgSQL adds control flow
  • Keep logic testable
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.