STRING_AGG Ordered Group Concatenation

Concatenate group members into one delimited string with STRING_AGG, ordering inside the aggregate and narrowing inputs with FILTER.

SqlData Fetching

Code

snippet
WITH team_members(team, name) AS (
    VALUES
        ('core',  'ada'),
        ('core',  'miles'),
        ('core',  'zoe'),
        ('infra', 'raj'),
        ('infra', 'mei')
)
SELECT
    team,
    -- ORDER BY 写在聚合内部:拼接顺序稳定,不依赖行的物理顺序
    string_agg(name, ', ' ORDER BY name) AS roster_sorted,
    -- FILTER 收窄参与聚合的行,再按倒序拼接
    string_agg(name, ' & ' ORDER BY name DESC)
               FILTER (WHERE name <> 'zoe') AS roster_desc_no_zoe,
    array_agg(name ORDER BY name) AS roster_array
FROM team_members
GROUP BY team
ORDER BY team;

What the code does

What runs is SELECT, with team_members as the object involved.

Mechanically, the statements are built from: a CTE (WITH … AS) that names an intermediate result before the main query; a WHERE clause constraining which rows the statement operates on; a GROUP BY that collapses matching rows into one output row per group; an ORDER BY that fixes the output order.

Applying it

The team_members table is the working surface here.

Interactive Tools for This Topic

FAQ

Which relations are involved here?
The references are `team_members`.