PostgreSQL COUNT

The COUNT() function returns the number of rows that match a specified criterion. It’s one of the most commonly used aggregate functions for summarizing data.

Key Topics

1. COUNT(*)

SELECT COUNT(*) AS total_rows
FROM employees;

This counts all rows in the employees table.

2. COUNT(column)

Counts only rows where the column is not NULL:

SELECT COUNT(email) AS total_emails
FROM employees;

3. Using GROUP BY

SELECT department, COUNT(*) AS dept_count
FROM employees
GROUP BY department;

Each department is listed alongside the number of employees within it.

Best Practices

  • Use COUNT(*) for a straightforward total row count.
  • Combine COUNT() with GROUP BY to get counts per category or group.

Key Takeaways

  • COUNT() is an essential function for basic data analysis.
  • COUNT(column) ignores NULL values, while COUNT(*) does not.