
Count in PostgreSql
COUNT()
in PostgreSQL
The COUNT()
function in PostgreSQL is used to count the number of rows in a table based on a given condition.
Syntax
SELECT COUNT(column_name) FROM table_name WHERE condition;
1. Counting All Rows in a Table
SELECT COUNT(*) FROM employees;
✅ Counts all rows in the employees
table, including NULL
values.
2. Counting Non-NULL Values in a Column
SELECT COUNT(salary) FROM employees;
✅ Counts rows where salary
is not NULL.
3. Counting Rows with a Condition
SELECT COUNT(*) FROM employees WHERE department = 'IT';
✅ Counts employees only in the IT department.
4. Counting Unique Values (Using DISTINCT
)
SELECT COUNT(DISTINCT department) FROM employees;
✅ Counts unique departments in the employees
table.
5. Using GROUP BY
with COUNT()
SELECT department, COUNT(*) FROM employees GROUP BY department;
✅ Counts employees in each department.
6. Using HAVING
to Filter Groups
SELECT department, COUNT(*) FROM employees GROUP BY departmentHAVING COUNT(*) > 10;
✅ Retrieves only departments with more than 10 employees.