The solution Burhan pointed out reduces the memory usage for large datasets by only fetching single rows:

row = cursor.fetchone()

However, I noticed a significant slowdown in fetching rows one-by-one. I access an external database over an internet connection, that might be a reason for it.

Having a server side cursor and fetching bunches of rows proved to be the most performant solution. You can change the sql statements (as in alecxe answers) but there is also pure python approach using the feature provided by psycopg2:

cursor = conn.cursor('name_of_the_new_server_side_cursor')
cursor.execute(""" SELECT * FROM table LIMIT 1000000 """)

while True:
    rows = cursor.fetchmany(5000)
    if not rows:
        break

    for row in rows:
        # do something with row
        pass

you find more about server side cursors in the psycopg2 wiki

Answer from linqu on Stack Overflow
🌐
Psycopg
psycopg.org › docs › usage.html
Basic module usage — Psycopg 2.9.12 documentation
conn = psycopg2.connect(DSN) try: ... transaction also on autocommit connections. When a database query is executed, the Psycopg cursor usually fetches all the records returned by the backend, transferring them to the client process....
🌐
GeeksforGeeks
geeksforgeeks.org › python › how-to-fetch-all-rows-with-psycopg2fetchall-in-python
How to Fetch All Rows with psycopg2.fetchall in Python - GeeksforGeeks
July 31, 2024 - Fetch All Rows: After the query is executed, you call fetchall to retrieve all rows from the result set. Connecting to the Database: Establish a connection using psycopg2.connect.
🌐
Psycopg
psycopg.org › docs › cursor.html
The cursor class — Psycopg 2.9.12 documentation
The method returns None. If a query was executed, the returned values can be retrieved using fetch*() methods.
🌐
PYnative
pynative.com › home › python › databases › python select from postgresql table using psycopg2
Python Select from PostgreSQL Table using psycopg2
March 9, 2021 - You’ll learn the following PostgreSQL SELECT operations from Python: Retrieve all rows from the PostgreSQL table using fetchall(), and fetch limited rows using fetchmany() and fetchone().
Top answer
1 of 6
50

The solution Burhan pointed out reduces the memory usage for large datasets by only fetching single rows:

row = cursor.fetchone()

However, I noticed a significant slowdown in fetching rows one-by-one. I access an external database over an internet connection, that might be a reason for it.

Having a server side cursor and fetching bunches of rows proved to be the most performant solution. You can change the sql statements (as in alecxe answers) but there is also pure python approach using the feature provided by psycopg2:

cursor = conn.cursor('name_of_the_new_server_side_cursor')
cursor.execute(""" SELECT * FROM table LIMIT 1000000 """)

while True:
    rows = cursor.fetchmany(5000)
    if not rows:
        break

    for row in rows:
        # do something with row
        pass

you find more about server side cursors in the psycopg2 wiki

2 of 6
33

Consider using server side cursor:

When a database query is executed, the Psycopg cursor usually fetches all the records returned by the backend, transferring them to the client process. If the query returned an huge amount of data, a proportionally large amount of memory will be allocated by the client.

If the dataset is too large to be practically handled on the client side, it is possible to create a server side cursor. Using this kind of cursor it is possible to transfer to the client only a controlled amount of data, so that a large dataset can be examined without keeping it entirely in memory.

Here's an example:

cursor.execute("DECLARE super_cursor BINARY CURSOR FOR SELECT names FROM myTable")
while True:
    cursor.execute("FETCH 1000 FROM super_cursor")
    rows = cursor.fetchall()

    if not rows:
        break

    for row in rows:
        doSomething(row)
🌐
Neon
neon.com › postgresql › python › query
PostgreSQL Python: Querying Data
May 19, 2024 - The following get_vendor() function selects data from the vendors table and fetches the rows using the fetchone() method. import psycopg2 from config import load_config def get_vendors(): """ Retrieve data from the vendors table """ config = ...
🌐
ObjectRocket
kb.objectrocket.com › postgresql › use-pythons-psycopg2-adapter-for-postgresql-to-fetch-records-from-a-table-754
Use Python’s Psycopg2 Adapter For PostgreSQL To Fetch Records From A Table | ObjectRocket
September 19, 2019 - When you connect to PostgreSQL in Python, using the psycopg2 Python adapter, you can created a cursor that allows you to execute SQL statements. This article will demonstrate how to use the SELECT SQL keyword, and the fetchall() psycopg2 method, to return all of the records, iterate the rows, and parse the data.
🌐
PostgreSQL Wiki
wiki.postgresql.org › wiki › Using_psycopg2_with_PostgreSQL
Using psycopg2 with PostgreSQL - PostgreSQL wiki
We will also use Psycopg2's prinf-style variable replacement, as well as a different fetch method to return a row (fetchone).
Find elsewhere
🌐
GeeksforGeeks
geeksforgeeks.org › python-psycopg-cursor-class
Python Psycopg - Cursor class - GeeksforGeeks
January 26, 2022 - A connection is established to the "Employee_db" database. a cursor is created using the conn.cursor() method, select SQL statement is executed by the execute() method and all the rows of the Table are fetched using the fetchall() method.
🌐
<buggycoder>
buggycoder.com › fetching-millions-of-rows-in-python-psycopg2
Fetching millions of rows in Python w/ psycopg2
September 10, 2017 - You can also control the no. of records fetched over the network in each go by setting the cursor.itersize property to a reasonable value (default 2000). #!/usr/bin/python import psycopg2 def main(): conn_url = 'postgresql://{username}:{password}@{host}:{port}/{dbname}'.format( username='', password='', host='', port='', dbname='') conn = psycopg2.connect(conn_url) cursor = conn.cursor(name='fetch_large_result') cursor.execute('SELECT * FROM <large_table>') while True: # consume result over a series of iterations # with each iteration fetching 2000 records records = cursor.fetchmany(size=2000) if not records: break for r in records: # do something with record here cursor.close() # don't forget to cleanup conn.close() if __name__ == "__main__": main()
🌐
GeeksforGeeks
geeksforgeeks.org › python-select-from-postgresql-table-using-psycopg2
Python Select from PostgreSQL Table using Psycopg2 - GeeksforGeeks
April 28, 2025 - fetchall() function to fetch the data from a table in the database and return it in the form of a tuple and practice various operations on the fetched data. psycopg2: It is a most useful module to connect the database of PostgreSQL, because ...
🌐
GitHub
github.com › psycopg › psycopg2 › issues › 346
Issue with cursor.fetchone() raising an exception after doing 'SELECT' on a non-existent row · Issue #346 · psycopg/psycopg2
September 9, 2015 - According to pretty much everything I read about psycopg2, doing cursor.fetchone() on a result of a 'SELECT' command that finds nothing should return a 'None' object (which makes sense and makes it easy to work with). Instead, however, it throws a "psycopg2.ProgrammingError: no results to fetch," as if a cursor.fetchone() was used on a result of a command that's not supposed to return something by default (e.g.
Author   psycopg
🌐
Medium
varun-verma.medium.com › use-psycopg2-to-return-dictionary-like-values-key-value-pairs-4d3047d8de1b
Use psycopg2 to return dictionary like values (key-value pairs) | by Verma Varun | Medium
April 20, 2021 - #!/usr/bin/python import psycopg2 import psycopg2.extrasDB_CONNECTION_STRING = "host=%s dbname=%s user=%s password=%s" % (DB_HOST, DB_DATABASE, DB_USER, DB_PASSWORD)dbConn = psycopg2.connect(DB_CONNECTION_STRING)cursor = dbConn.cursor(cursor_factory = psycopg2.extras.RealDictCursor)qSelect = "SELECT first_name, last_name, address FROM employee"cursor.execute(qSelect)results = cur.fetchall() for row in results: print("First Name: {}".format(row['first_name'])) print("Last Name: {}".format(row['last_name'])) print("Email: {}".format(row['email'])) Python ·
🌐
Medium
medium.com › dev-bits › understanding-postgresql-cursors-with-python-ebc3da591fe7
Understanding PostgreSQL Cursors with Python | by Naren Yellavula | Dev bits | Medium
August 8, 2023 - When I do docker logs <db_container>, I can see exactly how the database reacts to the cursor from Psycopg2. db_1 LOG: statement: BEGIN db_1 LOG: statement: DECLARE "actor" CURSOR WITHOUT HOLD FOR SELECT * FROM actor WHERE first_name LIKE 'John%' db_1 LOG: statement: FETCH FORWARD ALL FROM "actor" db_1 LOG: statement: CLOSE "actor" db_1 LOG: statement: COMMIT
🌐
ZetCode
zetcode.com › python › psycopg2
Python PostgreSQL proramming with psycopg2 module
January 29, 2024 - In this article we show how to program PostgreSQL databases in Python with psycopg2 module.
🌐
Earthly
earthly.dev › blog › psycopg2-postgres-python
PostgreSQL in Python Using Psycopg2 - Earthly Blog
July 19, 2023 - The connect() Function in Psycopg2 ... · Inserting Records Into a Table · How to Retrieve Data from Tables · Fetch the Next Record with fetchone() Fetch the Next n Records with fetchmany() Fetch All the Remaining Rows with ...
🌐
Psycopg
psycopg.org › docs › extras.html
psycopg2.extras – Miscellaneous goodies for Psycopg 2 — Psycopg 2.9.12 documentation
class psycopg2.extras.RealDictRow(*args, **kwargs)¶ · A dict subclass representing a data record. Added in version 2.3. ... A cursor that generates results as namedtuple. fetch*() methods will return named tuples instead of regular tuples, so their elements can be accessed both as regular ...
🌐
PostgreSQL Wiki
wiki.postgresql.org › wiki › Psycopg2_Tutorial
Psycopg2 Tutorial - PostgreSQL wiki
Psycopg2 is a DB API 2.0 compliant PostgreSQL driver that is actively developed.