Skip to content
Related Articles
Open in App
Not now

Related Articles

Get psycopg2 count(*) number of results

Improve Article
Save Article
Like Article
  • Last Updated : 23 Aug, 2021
Improve Article
Save Article
Like Article

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. 


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.


# importing psycopg2
import psycopg2
# Creating a cursor object using the cursor()
# method
cursor = conn.cursor()
# query to count total number of rows
sql = 'SELECT count(*) from products;'
# execute the query
results = cursor.fetchone()
#loop to print all the fetched details
for r in results:
print("Total number of rows in the table:", r)
# query to count number of rows
# where country name is India  
sql1 = 'SELECT count(*) from products WHERE "price" = 1.99;'
# execute query
result = cursor.fetchone()
for r1 in result:
print("Total Number of rows where country name is India:",r1)
# Commit your changes in the database
# Closing the connection


Count number of rows in the cursor

My Personal Notes arrow_drop_up
Like Article
Save Article
Related Articles

Start Your Coding Journey Now!