ARRAY_AGG FILTER With Empty-Group COALESCE

Partition rows into multiple arrays in one GROUP BY via ARRAY_AGG FILTER (WHERE ...), wrapping outputs with COALESCE so empty matches stay {}.

SqlData Integrity

Code

snippet
CREATE TEMP TABLE sprint_tasks (
    team   text NOT NULL,
    task   text NOT NULL,
    status text NOT NULL CHECK (status IN ('done', 'blocked'))
);

INSERT INTO sprint_tasks VALUES
    ('core', 'schema-v2',  'done'),
    ('core', 'auth-audit', 'blocked'),
    ('core', 'cache-key',  'done'),
    ('edge', 'tls-reload', 'done');

-- FILTER with zero matching rows returns NULL, so COALESCE turns it into '{}'
SELECT
    team,
    COALESCE(ARRAY_AGG(task ORDER BY task) FILTER (WHERE status = 'done'), '{}')    AS done_tasks,
    COALESCE(ARRAY_AGG(task ORDER BY task) FILTER (WHERE status = 'blocked'), '{}') AS blocked_tasks,
    COUNT(*) FILTER (WHERE status = 'blocked') AS blocked_count
FROM sprint_tasks
GROUP BY team
ORDER BY team;

Execution breakdown — ARRAY_AGG FILTER With Empty-Group COALESCE

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

sprint_tasks starts cleanly inside this script using ephemeral temporary session tables so no schema setup is needed beforehand and cleanup runs on disconnect.

Concretely, the SQL combines: a WHERE clause that keeps only the rows a statement is meant to touch; COUNT aggregation; a GROUP BY that collapses matching rows into one output row per group; an ORDER BY that fixes the output order; a CHECK constraint that rejects out-of-domain values at write time; NOT NULL qualifiers on the required columns.

Using it

Nothing outside the file is needed: the session-local tables it touches (sprint_tasks) are created by the file itself — point it at a scratch database and run the whole thing.

Key statements

INSERT INTO sprint_tasks VALUES
    ('core', 'schema-v2',  'done'),
    ('core', 'auth-audit', 'blocked'),
    ('core', 'cache-key',  'done'),
    ('edge', 'tls-reload', 'done');
CREATE TEMP TABLE sprint_tasks (
    team   text NOT NULL,
    task   text NOT NULL,
    status text NOT NULL CHECK (status IN ('done', 'blocked'))
);

Interactive Tools for This Topic

FAQ

Which tables does this file reference?
`sprint_tasks`.