Counting Distinct Values or Returning Groups

A distinct count gives a number of different present values. Grouping can show each observed key and its own row count.

Source
Anbloq
Language
English
Created
Updated
Chapters
4
Reading time
1 min
In this article4 chapters
  1. Trace a three-row sample
  2. Decide how missing labels appear
  3. Decide whether to return one count or a breakdown
  4. Keep normalization and scope visible

Trace a three-row sample

Labels A, A, and B have two distinct non-null labels. Grouping by label can show A with two and B with one. See group aggregation.

Decide how missing labels appear

Count of distinct label excludes null. Grouping may produce a null-key group. Counting rows and values helps produce the summary the reader expects.[1]

Decide whether to return one count or a breakdown

For labels A, A, B and null, a distinct count on the expression finds two non-null labels. Grouping by label can return groups A, B and a group for null. The reports serve different questions. See counting rows and present values.

Input labels: A,A,B,null
COUNT(DISTINCT label) → 2
GROUP BY label with COUNT(*) → A:2, B:1, null:1

Keep normalization and scope visible

Distinctness applies under the selected comparison rules and within the current filter. A model storing several spellings may require a normalized key. Test empty and duplicate-heavy inputs.

References

  1. PostgreSQL Global Development Group, Aggregate Functions ↩