I have a table with 4million rows and I use psycopg2 to execture a:
SELECT * FROM ..WHERE query
I haven't heard before of the server side cursor and I am reading its a good practice when you expect lots of results.
I find the documentation a bit limited and I have some basic questions.
First I declare the server-side cursor as:
cur = conn.cursor('cursor-name')
then I execute the query as:
cur.itersize = 10000
sqlstr = "SELECT clmn1, clmn2 FROM public.table WHERE clmn1 LIKE 'At%'"
cur.execute(sqlstr)
My question is: What do I do now? How do I get the results?
Do I iterate through the rows as:
row = cur.fetchone()
while row:
row = cur.fetchone()
or I use fetchmany() and I do this:
row = cur.fetchmany(10)
But in the second case how can I "scroll" the results?
Also what is the point of itersize?
Additionally to
cur.fetchmany(n)
you can use PostgreSQL cursors:Psycopg2 has a nice interface for working with server side cursors. This is a possible template to use:
The code above creates the connection and automatically places the query result into a server side cursor. The value
itersize
sets the number of rows that the client will pull down at a time from the server side cursor. The value you use should balance number of network calls versus memory usage on the client. For example, if your result count is three million, anitersize
value of 2000 (the default value) will result in 1500 network calls. If the memory consumed by 2000 rows is light, increase that number.When using
for row in cursor
you are of course working with one row at a time, but Psycopg2 will prefetchitersize
rows at a time for you.If you want to use
fetchmany
for some reason, you could do something like this:This usage of
fetchmany
will not trigger a network call to the server for more rows until the prefetched batch has been exhausted. (This is a convoluted example that provides nothing over the code above, but demonstrates how to usefetchmany
should there be a need.)