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.

Kindfunction
Example LanguageSQL

📝 Syntax

string_agg(value anyelement, delimiter text) → text
string_agg(value anyelement, delimiter text ORDER BY sort_expression) → text

⚙️ Parameters

value anyelementThe value to join; text or anything castable to it. NULL values are ignored.
delimiter textThe separator placed between values. Type text.
sort_expressionOptional: 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

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.
Web-Tutorial.com

Web-Tutorial Tech Team

A team of developers maintaining programming tutorials. Each tutorial is written and reviewed by developers with expertise in that field. We work to keep our content accurate and reliable — if you spot an issue, please let us know.

Content reviewed by MOTO · Found an error? Report it

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏