# How to use server-side SQL cursors with Python and QuestDB?

**URL:** <https://community.questdb.com/t/how-to-use-server-side-sql-cursors-with-python-and-questdb/37>\
**Category:** Community\
**Tags:** question, client\
**Created:** [June 26, 2024, 6:12pm UTC](https://community.questdb.com/t/how-to-use-server-side-sql-cursors-with-python-and-questdb/37 "2024-06-26T18:12:47Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![system](https://canada1.discourse-cdn.com/flex004/uploads/questdb/original/1X/b6b1b349e598d0550947e63d7923a9d7df0279eb.png) [@system](https://community.questdb.com/u/system)\
**Post date:** [June 26, 2024, 6:12pm UTC](https://community.questdb.com/t/how-to-use-server-side-sql-cursors-with-python-and-questdb/37/1 "2024-06-26T18:12:47Z")

</div>

I’m trying to fetch a few million rows from QuestDB with psycopg2, but I’m getting an SQL error:

```auto
2024-02-01T07:09:55.952335Z I i.q.g.SqlCompilerImpl parse [fd=24, thread=31, q=DECLARE "test" CURSOR FOR SELECT * FROM test;]

```

That’s probably because my code is trying to create a server-side cursor to avoid fetching all records into RAM in one go:

```auto
sql = "SELECT * FROM test;"
with self._conn.cursor('test') as cur:
    cur.itersize = 1000
    cur.execute(sql)
    while _records := cur.fetchmany(size=1000):
        ...

```

Does QuestDB support server-side cursors?

---

<div class="post-metadata">

**Author:** ![nwoolmer](https://yyz2.discourse-cdn.com/flex004/user_avatar/community.questdb.com/nwoolmer/32/24_2.png) [@nwoolmer](https://community.questdb.com/u/nwoolmer)\
**Post date:** [June 26, 2024, 6:13pm UTC](https://community.questdb.com/t/how-to-use-server-side-sql-cursors-with-python-and-questdb/37/2 "2024-06-26T18:13:10Z")

</div>

psycopg2 uses so-called scrollable cursors ([PostgreSQL: Documentation: 16: 43.7.&nbsp;Cursors](https://www.postgresql.org/docs/current/plpgsql-cursors.html)), i.e. cursors that have to be created explicitly with DECLARE CURSOR and that can go forward and backward. QuestDB doesn’t support these cursors, but it supports so-called non-scrollable cursors, i.e. forward-only cursors, and that’s what you need.

asyncpg driver supports non-scrollable cursors: [API Reference — asyncpg Documentation](https://magicstack.github.io/asyncpg/current/api/index.html#cursors)

Here is a snippet that would prefetch rows in 1K batches and print them:

```python
import asyncio
import asyncpg
import datetime

async def main():
    conn = await asyncpg.connect(dsn='postgresql://admin:quest@localhost:8812/qdb',ssl=False)

    async with conn.transaction():
        async for record in conn.cursor('SELECT * FROM test;', prefetch=1000):
            print(record)

    await conn.close()

asyncio.get_event_loop().run_until_complete(main())

```
