Skip to content
Advertisement

Get psycopg2 count(*) number of results

Whats the correct way to get the number or rows returned by this query? I’m specifically looking to see if no results are returned.

sql = 'SELECT count(*) from table WHERE guid = %s;'
data=[guid]
cur.execute(sql,data)
results = cur.fetchone()
for r in results:
  print type(r) # Returns as string {'count': 0L} Or {'count': 1L}

Thanks.

Advertisement

Answer

results is itself a row object, in your case (judging by the claimed print output), a dictionary (you probably configured a dict-like cursor subclass); simply access the count key:

result = cur.fetchone()
print result['count']

Because you used .fetchone() only one row is returned, not a list of rows.

If you are not using a dict(-like) row cursor, rows are tuples and the count value is the first value:

result = cur.fetchone()
print result[0]
Advertisement