STRING_AGG Ordered Group Concatenation
Concatenate group members into one delimited string with STRING_AGG, ordering inside the aggregate and narrowing inputs with FILTER.
Code
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
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 relations are involved here?
- The references are `team_members`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.