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.
Code
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
SQL DDL to TypeScript ConverterConvert SQL CREATE TABLE DDL statements into strict TypeScript interfaces with nullable, array, enum, JSONB, and Date or ISO string column mappings.PostgreSQL EXPLAIN AnalyzerAnalyze PostgreSQL EXPLAIN ANALYZE text or FORMAT JSON plans locally to flag Seq Scans, slow nodes, row misestimates, disk sorts, and index hints.Multi-Mode Escape & Unescape CodecEscape and unescape strings safely across JSON, JavaScript, SQL single-quoted literals, POSIX shell single quotes, and RFC 4180 CSV cells in your browser.SQL FormatterReformat SQL by uppercasing reserved words and breaking lines before SELECT, FROM, WHERE, and other clauses.
FAQ
- Which objects does the SQL touch?
- `visits` — referenced directly, no join needed.
Report a problem with this exampleOpens a pre-filled issue on GitHub.