count
PG 8.0+→ bigintCounts the number of input rows (with *) or the number of input rows where the expression is not NULL.
Signatures
count ( * ) → bigintcount ( expression ) → bigintParameters
| Parameter | Type | Description |
|---|---|---|
| expression | any | Value to count; NULLs are excluded. Use * to count all rows. |
Examples
SELECT count(*) FROM orders;1042SELECT count(email) FROM users;Counts only rows where email is not NULLSELECT count(DISTINCT status) FROM orders;Number of unique statusesSELECT department, count(*) AS headcount FROM employees GROUP BY department ORDER BY headcount DESC;Row count per departmentA common mistake is using `count(col)` expecting it to count all rows, then being surprised that NULL values are silently skipped. Equally, using `count(*)` to count non-null values in a specific column is incorrect.
✓ Instead: Use `count(*)` for total row count and `count(col)` explicitly when NULL-exclusion is desired. To count NULLs: `count(*) - count(col)`.
`count(*)` counts all rows including NULLs. `count(col)` skips NULLs. Use `count(*) - count(col)` to count NULLs in a column without a CASE expression.
SELECT count(*) AS total, count(email) AS with_email, count(*) - count(email) AS missing_email FROM users;Total rows, non-null emails, and missing email count