STRING_AGG DISTINCT With ORDER BY Alignment

Deduplicate grouped strings with STRING_AGG(DISTINCT ... ORDER BY ...), and pre-dedup in a subquery when sorting by a non-aggregated column.

SqlData Integrity

Code

snippet
CREATE TEMP TABLE incident_labels (
    incident_id integer NOT NULL,
    seen_order  integer NOT NULL,
    label       text
);

INSERT INTO incident_labels VALUES
    (10, 1, 'db'),
    (10, 2, 'timeout'),
    (10, 3, 'db'),
    (10, 4, NULL),
    (20, 1, 'auth');

-- DISTINCT + ORDER BY works when ORDER BY references the DISTINCT expression itself
SELECT
    incident_id,
    STRING_AGG(DISTINCT label, ', ' ORDER BY label DESC) AS unique_desc
FROM incident_labels
GROUP BY incident_id
ORDER BY incident_id;

-- To order unique labels by earliest seen_order, deduplicate first in a subquery
SELECT
    incident_id,
    STRING_AGG(label, ', ' ORDER BY first_seen) AS unique_by_first_seen
FROM (
    SELECT incident_id, label, MIN(seen_order) AS first_seen
    FROM incident_labels
    WHERE label IS NOT NULL
    GROUP BY incident_id, label
) AS deduped
GROUP BY incident_id
ORDER BY incident_id;

Stepwise trace — STRING_AGG DISTINCT With ORDER BY Alignment

The file runs SELECT / INSERT / CREATE statements, touching incident_labels.

incident_labels builds fresh session-local temporary tables inline right inside the script so zero persistent tables exist beforehand or stay behind after closing.

Mechanically, the statements are built from: a WHERE clause constraining which rows the statement operates on; MIN aggregation; a GROUP BY that collapses matching rows into one output row per group; an ORDER BY that fixes the output order; a DISTINCT qualifier that collapses duplicate rows; NOT NULL qualifiers on the required columns.

Using it

The file brings its own tables (incident_labels) — session-local, created on the fly — so execute it whole against a database you can throw away.

Key statements

SELECT
    incident_id,
    STRING_AGG(label, ', ' ORDER BY first_seen) AS unique_by_first_seen
FROM (
    SELECT incident_id, label, MIN(seen_order) AS first_seen
    FROM incident_labels
    WHERE label IS NOT NULL
    GROUP BY incident_id, label
) AS deduped
GROUP BY incident_id
ORDER BY incident_id;
SELECT
    incident_id,
    STRING_AGG(DISTINCT label, ', ' ORDER BY label DESC) AS unique_desc
FROM incident_labels
GROUP BY incident_id
ORDER BY incident_id;
INSERT INTO incident_labels VALUES
    (10, 1, 'db'),
    (10, 2, 'timeout'),
    (10, 3, 'db'),
    (10, 4, NULL),
    (20, 1, 'auth');

Interactive Tools for This Topic

FAQ

What objects does the SQL involve?
`incident_labels`.