Consider the two following Python code examples, which achieves the same but with significant and surprising performance difference.
import psycopg2, time
conn = psycopg2.connect("dbname=mydatabase user=postgres")
cur = conn.cursor('cursor_unique_name')
cur2 = conn.cursor()
startTime = time.clock()
cur.execute("SELECT * FROM test for update;")
print ("Finished: SELECT * FROM test for update;: " + str(time.clock() - startTime));
for i in range (100000):
cur.fetchone()
cur2.execute("update test set num = num + 1 where current of cursor_unique_name;")
print ("Finished: update starting commit: " + str(time.clock() - startTime));
conn.commit()
print ("Finished: update : " + str(time.clock() - startTime));
cur2.close()
conn.close()
And:
import psycopg2, time
conn = psycopg2.connect("dbname=mydatabase user=postgres")
cur = conn.cursor('cursor_unique_name')
cur2 = conn.cursor()
startTime = time.clock()
for i in range (100000):
cur2.execute("update test set num = num + 1 where id = " + str(i) + ";")
print ("Finished: update starting commit: " + str(time.clock() - startTime));
conn.commit()
print ("Finished: update : " + str(time.clock() - startTime));
cur2.close()
conn.close()
The create statement for the table test is:
CREATE TABLE test (id serial PRIMARY KEY, num integer, data varchar);
And that table contains 100000 rows and VACUUM ANALYZE TEST; has been run.
I got the following results consistently on several attempts.
First code example:
Finished: SELECT * FROM test for update;: 0.00609304950429
Finished: update starting commit: 37.3272754429
Finished: update : 37.4449708474
Second code example:
Finished: update starting commit: 24.574401185
Finished committing: 24.7331461431
This is very surprising to me as I would think is should be exactly opposite, meaning that an update using cursor should be significantly faster according to this answer.