Get psycopg2 count(*) number of results
Last Updated :
23 Aug, 2021
In this article, we are going to see how to get psycopg2 count(*) number of results.
psycopg2 count(*) returns the number of rows from a database table holding some specific conditions. If no condition is given then it returns the total number of tuples present in the relation.
Syntax:
SELECT COUNT(*) FROM table_name; # to return total no. of rows in the table
SELECT COUNT(*) FROM table_name WHERE condition; # to return no. of rows with some specified condition
Let’s see the following syntax in PostgreSql prompt:
First of all, we will import psycopg2 module that will deal with postgreSQL database, and then a database connection is established. Then we will create a cursor object that allows Python code to execute PostgreSQL command in a database session. We will then write a query to execute the total number of rows with specific details.
For ex- in the code given below, we are writing the first query to return the total no. of rows present in the table and the second query is written to return the total number of rows where the price name is 1.99. Finally, the number of rows has been fetched and displayed.
Python3
import psycopg2
conn = psycopg2.connect(
database = "geeks" ,
user = "postgres" ,
password = "root" ,
host = "localhost" ,
port = "5432"
)
cursor = conn.cursor()
sql = 'SELECT count(*) from products;'
data = []
cursor.execute(sql,data)
results = cursor.fetchone()
for r in results:
print (r)
print ( "Total number of rows in the table:" , r)
sql1 = 'SELECT count(*) from products WHERE "price" = 1.99;'
data1 = [ 'India' ]
cursor.execute(sql1,data1)
result = cursor.fetchone()
for r1 in result:
print (r1)
print ( "Total Number of rows where country name is India:" ,r1)
conn.commit()
conn.close()
|
Output:
Count number of rows in the cursor
Share your thoughts in the comments
Please Login to comment...