Reference

COUNT / SUM / AVG

Core aggregates. COUNT() counts rows, COUNT(col) counts non-null values, COUNT(DISTINCT col) counts unique non-null values. SUM and AVG ignore NULL: AVG divides the non-null sum by the non-null count, which is not the same as SUM(col) / COUNT().

Syntax #

sql
SELECT
  COUNT(*),
  COUNT(col),
  COUNT(DISTINCT col),
  SUM(metric),
  AVG(metric)
FROM table_name;

Example #

Loading SQL editor...
Warning

Aggregates silently skip NULL. AVG(col) is SUM(col) / COUNT(col), not SUM(col) / COUNT() — so rows where the column is NULL are excluded from the denominator. Usually what you want, but not always: if you need "average revenue per order including NULLs as zero", write SUM(COALESCE(total, 0)) / COUNT() explicitly. And COUNT(*) vs COUNT(col) differ as soon as the column has any NULL — choose based on whether you are counting rows or counting non-null values.