aggregate

STRING_AGG / GROUP_CONCAT

Concatenates non-NULL string values across a group into a single delimited string. Postgres and SQL Server spell it STRING_AGG; MySQL and SQLite use GROUP_CONCAT with a SEPARATOR clause.

STRING_AGG(expr, delim [ORDER BY ...])  |  GROUP_CONCAT(expr SEPARATOR ',')

Parameters / Modifiers

Parameter Purpose
ORDER BY Postgres: control the order of concatenated pieces
DISTINCT Concatenate unique values only (supported by MySQL GROUP_CONCAT)
SEPARATOR 'x' MySQL/SQLite syntax for the delimiter
group_concat_max_len MySQL session variable that truncates long results (default 1024)

Examples

SELECT STRING_AGG(name, ', ' ORDER BY name) FROM users;

Postgres: comma-separated alphabetized name list

SELECT GROUP_CONCAT(name SEPARATOR ', ') FROM users;

MySQL/SQLite equivalent of the previous query

SELECT dept, STRING_AGG(DISTINCT skill, '|') FROM emp GROUP BY dept;

Postgres: pipe-separated unique skills per department

SELECT GROUP_CONCAT(DISTINCT tag ORDER BY tag) FROM posts;

MySQL: sorted unique tags in one string

Dialect notes / Gotcha

MySQL silently truncates at group_concat_max_len (default 1024) — bump the session var for large lists. Postgres requires an explicit delimiter argument; passing '' concatenates without one.

Related functions

← All SQL functions · SQL cheat sheet · Window functions · PostgreSQL cheat sheet