string_agg(anyelement, text) — Concatenate many rows into one string
Last updated: 2026-11-04
string_agg(anyelement, text) — Concatenate many rows into one string
string_agg() is an aggregate that joins the values of a group into a single string using a separator. It is the usual way to produce tag lists or participant rosters. Without ORDER BY the concatenation order is unspecified, so add one whenever the output must be stable and reproducible.
| Kind | function |
|---|---|
| Example Language | SQL |
📝 Syntax
string_agg(value anyelement, delimiter text) → text
string_agg(value anyelement, delimiter text ORDER BY sort_expression) → text
⚙️ Parameters
| value anyelement | The value to join; text or anything castable to it. NULL values are ignored. |
|---|---|
| delimiter text | The separator placed between values. Type text. |
| sort_expression | Optional: the sort expression that fixes the concatenation order, used with ORDER BY. |
Returns:text — the joined string. It returns NULL when the group contains no non-NULL values.
▶ Example
Runs real PostgreSQL 18 right in your browser (PGlite WASM, nothing to install). Press ▶ Run and the result appears in the panel below.
Output:
order_id | items | item_count
----------+---------------------------+------------
100 | CBL-002, HUB-001, MSE-003 | 3
200 | HUB-001 | 1
(2 rows)
📌 Key Points
- It is an aggregate rather than a scalar function, so it has to be used with GROUP BY.
- Without ORDER BY the order is unspecified and may differ between versions or concurrent executions.
- It returns NULL, not an empty string, when every value in the group is NULL; coalesce() can guard that.
💡 Related Cases
More case studies coming soon.
📚 Related Reference
❓ FAQ
QHow does string_agg() differ from array_agg()?
Aarray_agg() returns an array, which is handy when you want to keep working with array operators, while string_agg() gives you text straight away for display or export. Both accept an ORDER BY clause.