COUNT variants
Overview
An aggregate summarizes a set of input rows into one value. COUNT(*) counts rows, COUNT(column) counts known values, and COUNT(DISTINCT column) counts different non-NULL values. Without GROUP BY, these aggregate queries produce one summary row.
First example
SELECT COUNT(*), COUNT(score) FROM sort_scores;Observed SQLite result (rows in JSON):
[ [ 4, 2 ]]How it works
In sort_scores, four students have records, but only two have known scores (10 and 0). Zero is known, so COUNT(score) includes it. In orders, three orders belong to two distinct customers. COUNT returns an integer count (bigint in PostgreSQL). WHERE restricts the rows before aggregation.
Practical example
SELECT COUNT(*), COUNT(DISTINCT customer_id) FROM orders;Observed SQLite result (rows in JSON):
[ [ 3, 2 ]]Practice and mistakes
Do not use COUNT(1) expecting a count of the first column: 1 is a non-NULL constant. Practice: count only orders for customer 1 using WHERE; expect 2.