PYnative

Practice Coding

  • Python ▼
    • Python Tutorials
    • Python Basics
    • Python Interview Q&As
  • Coding Exercises ▼
    • Python Exercises
    • C++ Exercises
    • C Programming Exercises
    • Java Exercises
    • C# Exercises
  • MCQs▼
    • Python MCQ Quizzes
    • Java MCQ Quizzes
    • C++ MCQ Quizzes
  • Compilers▼
    • Online Python Compiler
    • Online C Compiler
    • Online C++ Compiler
    • Online Java Compiler
    • Online C# Compiler
Home » Python » Databases » Execute PostgreSQL Stored Procedure and Function in Python

Execute PostgreSQL Stored Procedure and Function in Python

Updated on: December 4, 2026 | 11 Comments

In this lesson, you will learn how to execute PostgreSQL functions and stored procedures from Python with psycopg2. Functions and procedures keep logic on the server, for example to fetch related data or to change several tables in one step.

Goals of this lesson:

  • Call a PostgreSQL function with cursor.callproc() and with a SELECT query
  • Pass positional and named arguments, and read the results
  • Call a stored procedure with CALL and read its INOUT parameters

Also, Solve:

  • Python PostgreSQL Exercise
  • Read Python PostgreSQL Tutorial (Complete Guide)

Table of contents

  • Functions vs stored procedures
  • Prerequisites
  • Steps to call PostgreSQL Function and stored procedure from Python
    • Example to execute PostgreSQL Function and stored procedure
    • Call a function with a SELECT query
    • Pass named arguments
  • Call a stored procedure
    • Read INOUT parameters
  • Summary
  • Next Steps

Functions vs stored procedures

  • A function (CREATE FUNCTION) returns a value or a set of rows, and you call it inside a query: SELECT * FROM my_function(1). It runs inside the caller’s transaction.
  • A stored procedure (CREATE PROCEDURE, PostgreSQL 11 and later) doesn’t return a result set, and you run it with CALL my_procedure(1). It can return values through INOUT parameters (and OUT parameters from PostgreSQL 14).

This difference matters in Python: psycopg2’s callproc() works only with functions. Procedures must be run with execute("CALL ...").

Prerequisites

You need the user name and password to connect to PostgreSQL, and the functions and procedures you want to call.

This lesson uses two tables: employee, and prod_movement, which records which employee deployed which application to production. Run this SQL in psql or pgAdmin to create them with sample data:

CREATE TABLE employee (
    id INTEGER PRIMARY KEY,
    name VARCHAR(100) NOT NULL,
    designation VARCHAR(100) NOT NULL
);

CREATE TABLE prod_movement (
    app_id INTEGER NOT NULL,
    emp_id INTEGER NOT NULL REFERENCES employee (id)
);

INSERT INTO employee VALUES
    (23, 'Scot', 'Application Developer'),
    (24, 'Emma', 'QA Engineer'),
    (25, 'Jason', 'DevOps Engineer');

INSERT INTO prod_movement VALUES (72, 23), (72, 25), (80, 24);Code language: Python (python)

Next, create the function get_production_deployment. It takes an application id and returns the id, name, and designation of every employee who deployed that application:

CREATE OR REPLACE FUNCTION get_production_deployment(p_app_id INTEGER)
RETURNS TABLE (emp_id INTEGER, emp_name VARCHAR, designation VARCHAR)
LANGUAGE sql
AS $$
    SELECT e.id, e.name, e.designation
    FROM employee e
    JOIN prod_movement pm ON pm.emp_id = e.id
    WHERE pm.app_id = p_app_id
    ORDER BY e.id;
$$;Code language: Python (python)

The function body sits between $$ markers (dollar quoting), so it can contain quotes and semicolons. The parameter is named p_app_id so it can’t be confused with a column name.

Steps to call PostgreSQL Function and stored procedure from Python

How to execute PostgreSQL functions and stored procedure in Python

  1. Import psycopg2

    Install psycopg2 with pip and import it with import psycopg2.

  2. Connect to PostgreSQL from Python

    Connect to the database with psycopg2.connect().

  3. Get Cursor Object from Connection

    Create a cursor with connection.cursor().

  4. Execute the stored procedure or function

    Call a function with cursor.callproc('function_name', (arg1, arg2)). Run a stored procedure with cursor.execute('CALL procedure_name(%s, %s)', (arg1, arg2)).

  5. Fetch results

    Read the rows the function returns with fetchall(), fetchone(), or fetchmany(). Commit if the function or procedure changed data.

  6. Close the cursor object and database connection object

    Close the cursor and the connection when your work is done.

python execute PostgreSQL function and stored procedure
Python execute PostgreSQL function and stored procedure

Example to execute PostgreSQL Function and stored procedure

This program calls get_production_deployment for application 72 and prints the employees it returns:

import psycopg2

connection = None
try:
    connection = psycopg2.connect(user="postgres",
                                  password="pynative@#29",
                                  host="127.0.0.1",
                                  port="5432",
                                  dbname="postgres_db")

    with connection.cursor() as cursor:
        # call the function with one argument
        cursor.callproc('get_production_deployment', (72,))

        print("Employees who deployed application 72 to production:")
        for emp_id, name, designation in cursor.fetchall():
            print(f"Id = {emp_id}, Name = {name}, Designation = {designation}")

except psycopg2.Error as error:
    print("Error while calling the function:", error)

finally:
    if connection is not None:
        connection.close()
        print("PostgreSQL connection is closed")Code language: Python (python)

Output:

Employees who deployed application 72 to production:
Id = 23, Name = Scot, Designation = Application Developer
Id = 25, Name = Jason, Designation = DevOps Engineer
PostgreSQL connection is closed

Let’s understand the above program:

  • callproc(name, args) runs SELECT * FROM name(args) on the server. The sequence must contain one value for each argument the function expects; a single value needs a trailing comma.
  • In psycopg2, callproc() itself returns None. Read the function’s result with the usual fetchall(), fetchone(), or fetchmany() methods.
  • Unquoted names in PostgreSQL are case-insensitive, so get_production_Deployment would find the same function. Using lowercase everywhere avoids confusion.

Call a function with a SELECT query

Because callproc() only builds a SELECT for you, you can write that query yourself. This gives you full SQL: you can pick columns, filter, or call a function that returns a single value:

import psycopg2

connection = psycopg2.connect(user="postgres", password="pynative@#29",
                              host="127.0.0.1", port="5432", dbname="postgres_db")
try:
    with connection.cursor() as cursor:
        # pick only the columns you need
        cursor.execute("SELECT emp_name FROM get_production_deployment(%s)", (72,))
        print("Names:", [row[0] for row in cursor.fetchall()])

        # a built-in function that returns a single value
        cursor.execute("SELECT upper(%s)", ("scot",))
        print("Upper case:", cursor.fetchone()[0])
finally:
    connection.close()Code language: Python (python)

Output:

Names: ['Scot', 'Jason']
Upper case: SCOT

Pass named arguments

Pass a dictionary to callproc() to name each argument. The keys must match the parameter names in the function definition:

cursor.callproc('get_production_deployment', {'p_app_id': 80})
print(cursor.fetchall())  # [(24, 'Emma', 'QA Engineer')]Code language: Python (python)

Call a stored procedure

Create a procedure that records a new deployment:

CREATE OR REPLACE PROCEDURE record_deployment(p_app_id INTEGER, p_emp_id INTEGER)
LANGUAGE sql
AS $$
    INSERT INTO prod_movement (app_id, emp_id) VALUES (p_app_id, p_emp_id);
$$;Code language: Python (python)

Run it with a CALL statement through execute(), and commit the change:

import psycopg2

connection = psycopg2.connect(user="postgres", password="pynative@#29",
                              host="127.0.0.1", port="5432", dbname="postgres_db")
try:
    with connection:  # commits when the block ends without an error
        with connection.cursor() as cursor:
            cursor.execute("CALL record_deployment(%s, %s)", (80, 23))
    print("Deployment recorded")

    with connection.cursor() as cursor:
        cursor.callproc('get_production_deployment', (80,))
        print(cursor.fetchall())
finally:
    connection.close()Code language: Python (python)

Output:

Deployment recorded
[(23, 'Scot', 'Application Developer'), (24, 'Emma', 'QA Engineer')]

Note:

  • callproc('record_deployment', ...) fails with an error saying that record_deployment is a procedure, because callproc() uses SELECT. Always use CALL for procedures.
  • A procedure can run COMMIT or ROLLBACK inside its body only when it isn’t called inside an open transaction block. Because psycopg2 starts a transaction automatically, set connection.autocommit = True before calling such procedures.

Read INOUT parameters

A procedure returns values through its INOUT parameters. CALL then produces a single row with their values, which you read with fetchone():

CREATE OR REPLACE PROCEDURE count_app_deployments(p_app_id INTEGER, INOUT total BIGINT)
LANGUAGE plpgsql
AS $$
BEGIN
    SELECT count(*) INTO total FROM prod_movement WHERE app_id = p_app_id;
END;
$$;Code language: Python (python)
import psycopg2

connection = psycopg2.connect(user="postgres", password="pynative@#29",
                              host="127.0.0.1", port="5432", dbname="postgres_db")
try:
    with connection.cursor() as cursor:
        # pass None as a placeholder for the INOUT parameter
        cursor.execute("CALL count_app_deployments(%s, %s)", (72, None))
        total = cursor.fetchone()[0]
        print("Deployments of application 72:", total)
finally:
    connection.close()Code language: Python (python)

Output:

Deployments of application 72: 2

From PostgreSQL 14, you can declare the parameter as OUT instead of INOUT; you still pass a placeholder such as None for it in the CALL.

Practice Problem:

Create a function count_employee_deployments(p_emp_id INTEGER) that returns how many deployments an employee has made, and call it from Python for employee 23.

Show Solution
CREATE OR REPLACE FUNCTION count_employee_deployments(p_emp_id INTEGER)
RETURNS BIGINT
LANGUAGE sql
AS $$
    SELECT count(*) FROM prod_movement WHERE emp_id = p_emp_id;
$$;Code language: Python (python)
import psycopg2

connection = psycopg2.connect(user="postgres", password="pynative@#29",
                              host="127.0.0.1", port="5432", dbname="postgres_db")
try:
    with connection.cursor() as cursor:
        cursor.callproc('count_employee_deployments', (23,))
        print("Deployments:", cursor.fetchone()[0])  # 2 after the CALL example
finally:
    connection.close()Code language: Python (python)

Summary

  • Call a function with cursor.callproc(name, args) or with SELECT * FROM name(%s), then fetch the rows.
  • Pass a dictionary to callproc() to use named arguments.
  • Run a stored procedure with cursor.execute("CALL name(%s)", args); callproc() doesn’t work for procedures.
  • Read INOUT values from the row that CALL returns, and commit when the function or procedure changed data.

Next Steps

Learn how to manage PostgreSQL transactions with commit and rollback. To practice, solve the Python Database Exercise project.

Filed Under: Python, Python Databases

Did you find this page helpful? Let others know about it. Sharing helps me continue to create free Python resources.

TweetF  sharein  shareP  Pin

About Vishal

I’m Vishal Hule, the Founder of PYnative.com. As a Python developer, I enjoy assisting students, developers, and learners. Follow me on Twitter.

Related Tutorial Topics:

Python Python Databases

All Coding Exercises:

C Exercises
C++ Exercises
Python Exercises
Java Exercises
C# Exercises

Python Exercises and Quizzes

Free coding exercises and quizzes cover Python basics, data structure, data analytics, and more.

  • 15+ Topic-specific Exercises and Quizzes
  • Each Exercise contains 25+ questions
  • Each Quiz contains 25 MCQ
Exercises
Quizzes

Comments

  1. mohamed Asif says

    April 13, 2022 at 12:01 pm

    Hi, I tried to connect Apache airflow with python but not able to connect , is there any solution for that?

    Reply
  2. vedha says

    July 19, 2021 at 3:27 pm

    Hi Vishal ,

    I have a stored procedure, which takes input as a table structure. How can I execute it.

    Reply
  3. jk says

    February 1, 2020 at 8:32 am

    Where is the table definitions?

    Reply
  4. Pranay says

    September 13, 2019 at 5:21 pm

    What is prod_movement in the following statement :

    (SELECT empId FROM prod_movement where prod_movement.appId = appId)

    I tried to understand what should be placed while I’m executing ,failed.
    I ended up trying Database name , table name, column names.
    Nothing works.
    I got this error : Error relation “demo” does not exist
    Please explain …

    Reply
    • Vishal says

      September 13, 2019 at 6:45 pm

      Hi Pranay, prod_movement is a table present in my database. If you want to execute your function from Python please use your PostgreSQL function and pass the IN and OUT parameters if any.

      Reply
      • Pranay says

        September 15, 2019 at 4:38 pm

        If prod_movement is a table you’re checking id ,then what is employee.
        Is it another table ?
        Please explain …

        Reply
        • Pranay says

          September 15, 2019 at 5:09 pm

          Executed Function Using Python.
          Understood your query with the explanation given.
          Thanks
          @Vishal

          Reply
          • Vishal says

            September 15, 2019 at 11:14 pm

            You are welcome.

  5. Michael Goldshteyn says

    January 3, 2019 at 2:23 am

    What about named stored procedure arguments instead of sequential?

    Reply
    • Vishal says

      January 3, 2019 at 7:13 am

      Hi, Michael is the order of stored procedure input parameter always changes. in this, you can try this

      query = """\EXEC procedureName @param1=?, @param2=?"""
      tuple = ('value1','value2')
      cursor.execute(query , tuple)
      

      You can also refer this StackOverflow question https://stackoverflow.com/questions/30964608/python-pyodbc-call-stored-procedure-with-parameter-name

      Hope it helps!

      Reply
      • madhu sudhanan says

        September 9, 2021 at 3:35 pm

        Hi Vishal can i get some support to call a postgresql function from python

        Reply

Leave a Reply Cancel reply

your email address will NOT be published. all comments are moderated according to our comment policy.

Use <pre> tag for posting code. E.g. <pre> Your entire code </pre>

In: Python Python Databases
TweetF  sharein  shareP  Pin

  Python PostgreSQL

  • Python PostgreSQL Guide
  • Python PostgreSQL Select
  • Python PostgreSQL CRUD
  • Python PostgreSQL call Function
  • Python PostgreSQL Transactions
  • Python PostgreSQL Connection Pool
  • Python Database Exercise

 Explore Python

  • Python Tutorials
  • Python Exercises
  • Python Quizzes
  • Python Interview Q&A
  • Python Programs

All Python Topics

Python Basics Python Exercises Python Quizzes Python Interview Python File Handling Python OOP Python Date and Time Python Random Python Regex Python Pandas Python Databases Python MySQL Python PostgreSQL Python SQLite Python JSON

About PYnative

PYnative.com is a platform built to help developers learn by doing. Solve coding exercises, take MCQs, and run code directly in built-in online compilers.

Follow Us

To get New Python Tutorials, Exercises, and Quizzes

  • Twitter
  • Facebook
  • Sitemap

Explore Python

  • Learn Python
  • Python Basics
  • Python Databases
  • Python Exercises
  • Python Quizzes
  • Online Python Code Editor
  • Python Tricks

Coding Exercises

  • C Exercises
  • C++ Exercises
  • Python Exercises
  • Java Exercises
  • C# Exercises

MCQ Quizzes

  • Python MCQs
  • Java MCQs
  • C++ MCQs

Legal Stuff

  • About Us
  • Contact Us

We use cookies to improve your experience. While using PYnative, you agree to have read and accepted our:

  • Terms Of Use
  • Privacy Policy
  • Cookie Policy

Copyright © 2018–2026 pynative.com