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 aSELECTquery - Pass positional and named arguments, and read the results
- Call a stored procedure with
CALLand read its INOUT parameters
Also, Solve:
Table of contents
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 withCALL 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:
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:
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
- Import psycopg2
Install psycopg2 with pip and import it with
import psycopg2. - Connect to PostgreSQL from Python
Connect to the database with
psycopg2.connect(). - Get Cursor Object from Connection
Create a cursor with
connection.cursor(). - Execute the stored procedure or function
Call a function with
cursor.callproc('function_name', (arg1, arg2)). Run a stored procedure withcursor.execute('CALL procedure_name(%s, %s)', (arg1, arg2)). - Fetch results
Read the rows the function returns with
fetchall(),fetchone(), orfetchmany(). Commit if the function or procedure changed data. - Close the cursor object and database connection object
Close the cursor and the connection when your work is done.

Example to execute PostgreSQL Function and stored procedure
This program calls get_production_deployment for application 72 and prints the employees it returns:
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)runsSELECT * 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 returnsNone. Read the function’s result with the usualfetchall(),fetchone(), orfetchmany()methods. - Unquoted names in PostgreSQL are case-insensitive, so
get_production_Deploymentwould 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:
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:
Run it with a CALL statement through execute(), and commit the change:
Output:
Deployment recorded [(23, 'Scot', 'Application Developer'), (24, 'Emma', 'QA Engineer')]
Note:
callproc('record_deployment', ...)fails with an error saying thatrecord_deploymentis a procedure, becausecallproc()usesSELECT. Always useCALLfor procedures.- A procedure can run
COMMITorROLLBACKinside its body only when it isn’t called inside an open transaction block. Because psycopg2 starts a transaction automatically, setconnection.autocommit = Truebefore 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():
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
Summary
- Call a function with
cursor.callproc(name, args)or withSELECT * 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
CALLreturns, 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.

Hi, I tried to connect Apache airflow with python but not able to connect , is there any solution for that?
Hi Vishal ,
I have a stored procedure, which takes input as a table structure. How can I execute it.
Where is the table definitions?
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 …
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.
If prod_movement is a table you’re checking id ,then what is employee.
Is it another table ?
Please explain …
Executed Function Using Python.
Understood your query with the explanation given.
Thanks
@Vishal
You are welcome.
What about named stored procedure arguments instead of sequential?
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!
Hi Vishal can i get some support to call a postgresql function from python