Get psycopg2 count(*) number of results
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.