Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get psycopg2 count(*) number of results

Tags:

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.

like image 305
Matt Avatar asked Oct 04 '13 22:10

Matt


People also ask

How do I find the number of records in PostgreSQL?

The basic SQL standard query to count the rows in a table is: SELECT count(*) FROM table_name; This can be rather slow because PostgreSQL has to check visibility for all rows, due to the MVCC model.

How do I count unique values in PostgreSQL?

In this form, the COUNT(DISTINCT column) returns the number of unique non-null values in the column. We often use the COUNT() function with the GROUP BY clause to return the number of items for each group. For example, we can use the COUNT() with the GROUP BY clause to return the number of films in each film category.

What is count in PostgreSQL?

The PostgreSQL COUNT function counts a number of rows or non-NULL values against a specific column from a table. When an asterisk(*) is used with count function the total number of rows returns. Syntax: COUNT (* | [DISTINCT] ALL | column_name) Parameters.

How do I know if psycopg2 is alive?

In order to make sure a connection is still valid, read the property connection. isolation_level . This will raise an OperationalError with pgcode == "57P01" in case the connection is dead. This adds a bit of latency for a roundtrip to the database but should be preferable to a SELECT 1 or similar.


1 Answers

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] 
like image 198
Martijn Pieters Avatar answered Oct 07 '22 02:10

Martijn Pieters