PostgreSQL – COUNT Function
The count()
function in PostgreSQL is used to count the number of rows in a table or the number of values in a specific column that meet a certain condition.
Below is the basic syntax of the count()
function:
SELECT count(*)
FROM table_name;
Above query will count the total number of rows in the specified table. You can also specify a specific column to count the number of non-null values in that column:
SELECT count(column_name)
FROM table_name;
If you want to count the number of rows that meet a certain condition, you can add a WHERE
clause to the query:
SELECT count(*)
FROM table_name
WHERE column_name = 'value';
You can also count the number of distinct values in a column by using the DISTINCT
keyword. This will count the number of unique values in the specified column.
SELECT count(DISTINCT column_name)
FROM table_name;
To count the number of rows that meet multiple conditions, you can use the AND
or OR
operators in the WHERE
clause.
SELECT count(*)
FROM table_name
WHERE column1 = 'value1' AND column2 = 'value2';