Count Distinct Composite Key Pairs

count(DISTINCT (user_id, day)) treats the row constructor as one key, separating unique pairs from plain row and column counts.

SqlData Fetching

Code

snippet
CREATE TABLE visits (
    id      bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
    user_id integer NOT NULL,
    day     date NOT NULL
);

INSERT INTO visits (user_id, day) VALUES
    (1, DATE '2026-06-01'),
    (1, DATE '2026-06-01'),
    (1, DATE '2026-06-02'),
    (2, DATE '2026-06-01'),
    (2, DATE '2026-06-03');

SELECT
    count(*)                       AS total_rows,
    count(DISTINCT user_id)        AS distinct_users,
    count(DISTINCT day)            AS distinct_days,
    count(DISTINCT (user_id, day)) AS distinct_user_day_pairs
FROM visits;

The shape of this snippet — Count Distinct Composite Key Pairs

SELECT / INSERT / CREATE statements share the script, touching visits.

Mechanically, the statements are built from: COUNT aggregation; a DISTINCT qualifier that collapses duplicate rows; NOT NULL qualifiers on the required columns; a PRIMARY KEY that enforces row identity; a GENERATED ALWAYS/GENERATED BY clause that computes the column value.

Using it

Point it at the visits table.

Key statements

SELECT
    count(*)                       AS total_rows,
    count(DISTINCT user_id)        AS distinct_users,
    count(DISTINCT day)            AS distinct_days,
    count(DISTINCT (user_id, day)) AS distinct_user_day_pairs
FROM visits;
INSERT INTO visits (user_id, day) VALUES
    (1, DATE '2026-06-01'),
    (1, DATE '2026-06-01'),
    (1, DATE '2026-06-02'),
    (2, DATE '2026-06-01'),
    (2, DATE '2026-06-03');
CREATE TABLE visits (
    id      bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
    user_id integer NOT NULL,
    day     date NOT NULL
);

Interactive Tools for This Topic

FAQ

Which objects does the SQL touch?
`visits` — referenced directly, no join needed.