sqlstreak

SQL compared

COUNT(*) vs COUNT(column) vs COUNT(DISTINCT)

Updated · Tested on PostgreSQL 18.6 and SQLite 3.54.1 (results generated , re-checked on every release)

Short answer

COUNT(*) counts rows. COUNT(column) counts the rows where that column is not NULL. COUNT(DISTINCT column) counts the different non-NULL values. COUNT(1) is the same as COUNT(*).

Side by side

COUNT(*)COUNT(column)COUNT(DISTINCT column)
CountsRowsNon-NULL valuesDifferent non-NULL values
NULLsCounted (it's a row)SkippedSkipped
After a LEFT JOIN, for a row with no match10 (count a right-hand column)0
Typical useHow many rowsHow many have a value filled inHow many different ones

The same data, each way

Every query below was run on PostgreSQL and SQLite when this page was built; the tables are what came back.

Three answers from one table

20 pets, of which some have no recorded breed (NULL), and fewer different breeds than pets.

SELECT COUNT(*) AS pets,
       COUNT(breed) AS with_breed,
       COUNT(DISTINCT breed) AS breeds,
       COUNT(DISTINCT species) AS species
FROM pets;

Result (PostgreSQL and SQLite, identical): 1 row

petswith_breedbreedsspecies
2014134

Try it: PostgreSQL playground · SQLite playground

The LEFT JOIN trap

Counting orders per customer. Customers with no orders still produce one row with NULLs, so COUNT(*) says 1. Count a column from the right-hand table instead.

SELECT c.name,
       COUNT(*) AS count_star,
       COUNT(o.id) AS orders
FROM customers c
LEFT JOIN orders o ON o.customer_id = c.id
GROUP BY c.id, c.name
ORDER BY orders, c.name;

Result (PostgreSQL and SQLite, identical): 10 rows

namecount_starorders
Diego Santos10
Nora Lindqvist10
Lena Fischer11
Priya Nair11
Ellie Park22
Marcus Bell22
Sam Okafor22
Tomás Herrera22
Jonah Reed33
Maya Ortiz44

Try it: PostgreSQL playground · SQLite playground

When to use which

COUNT(*)

To count rows: how many orders, how many pets per species.

COUNT(column)

To count rows that have a value in a column, or matches after a LEFT JOIN (count the right table's id).

COUNT(DISTINCT column)

To count different values: how many cities, how many customers ordered.

Common mistakes

  • COUNT(*) after a LEFT JOIN: unmatched rows count as 1, not 0. Count a column of the joined table.

  • Expecting COUNT(column) to count NULLs: it skips them. Use COUNT(*) or SUM(CASE WHEN column IS NULL THEN 1 ELSE 0 END).

  • COUNT(DISTINCT a, b) with two columns: PostgreSQL and SQLite don't accept it. Count distinct pairs in a subquery.

PostgreSQL and SQLite

Everything on this page works the same in PostgreSQL and SQLite: each example above was run on both, and the results match.

Official documentation

Go deeper

Make it stick in five minutes a day

“Count, sum, average” teaches this step by step on a real database, with instant feedback. Part of sqlstreak Pro; the first lessons are free.

Start free