SQL GROUP_CONCAT function
Aggregates a column into one delimited string per group. MySQL's version is configurable but quietly truncates at 1024 bytes by default.
- Categoria
- Aggregates
- Returns
string- In this category
- 12 of 52
Sintaxe
GROUP_CONCAT([DISTINCT] column [ORDER BY ...] [SEPARATOR 'sep'])
Suporte a mecanismos
| Motor | Support | Notas |
|---|---|---|
| SQL Server | Different name or syntax | STRING_AGG (2017+) |
| PostgreSQL | Different name or syntax | STRING_AGG |
| MySQL | Sim | Supported under this name. |
| SQLite | Sim | Supported under this name. |
| Oracle | Different name or syntax | LISTAGG |
Exemplos
MySQL
SELECT department, GROUP_CONCAT(last_name ORDER BY last_name SEPARATOR ' | ') AS team FROM employees GROUP BY department;
SQLite
SELECT department, group_concat(last_name, ', ') AS team FROM employees GROUP BY department;
Bom saber
- MySQL truncates the result at group_concat_max_len, default 1024 bytes. The only signal is warning 1260 (Row n was cut by GROUP_CONCAT()), which most clients never show. Raise it per session: SET SESSION group_concat_max_len = 1000000.
- Default separator is ','; change it with SEPARATOR ' | '. ORDER BY inside the call orders the joined values.
- SQLite accepts ORDER BY inside group_concat() from 3.44 (string_agg is an alias from the same release); older versions join in whatever order rows arrive. DISTINCT only works in the one-argument, comma-separated form.
- A group whose values are all NULL aggregates to NULL, not an empty string.
Questions about GROUP_CONCAT
Why is my GROUP_CONCAT result cut off?
group_concat_max_len, which defaults to 1024 bytes, truncated it. Set it higher in the session; the server-level value caps what a session can raise.
How do I get STRING_AGG behaviour in MySQL?
GROUP_CONCAT(column ORDER BY x SEPARATOR ', ') is the direct match for STRING_AGG(column, ', ' ORDER BY x).
Does SQLite have GROUP_CONCAT?
Yes: group_concat(X) or group_concat(X, separator), with ORDER BY inside the call from 3.44. DISTINCT cannot be combined with a custom separator.
Browse every function in the SQL function reference, or see what the SQLly desktop app does for your database.
Related on SQLly
- Join child rows into a comma-separated list in SQL Snippet
- Find duplicate emails ignoring case Snippet
- SQL aggregation & HAVING interview questions Interview questions
Cheat sheets for the engines that have it: MySQL, SQLite, SQL Server, PostgreSQL, Oracle.
Functions your engine actually has
SQLly's completion lists the built-in functions of the engine you're connected to, whether that's SQL Server, PostgreSQL, MySQL, SQLite or Oracle. Hover a function for help, and signature hints show each argument as you type.