To combine text values from multiple SQL rows into a single delimited string (such as comma-separated values), use an aggregate string-concatenation function paired with GROUP BY (or window OVER (...) when supported). Each SQL dialect has its own function name and syntax: STRING_AGG() in PostgreSQL and SQL Server, GROUP_CONCAT() in MySQL, and GROUP_CONCAT() in SQLite.
1. PostgreSQL & SQL Server: STRING_AGG()
STRING_AGG(expression, separator) takes the value expression and delimiter, and supports ordering inside the function or via ORDER BY.
PostgreSQL Syntax
SELECT
department_id,
STRING_AGG(employee_name, ', ' ORDER BY employee_name ASC) AS team_members
FROM employees
GROUP BY department_id;
SQL Server (T-SQL) Syntax (SQL Server 2017+)
SELECT
department_id,
STRING_AGG(CAST(employee_name AS NVARCHAR(MAX)), ', ')
WITHIN GROUP (ORDER BY employee_name ASC) AS team_members
FROM employees
GROUP BY department_id;
- Casting to
NVARCHAR(MAX)orVARCHAR(MAX)in SQL Server avoids truncation when concatenated strings exceed 8,000 bytes.
2. MySQL: GROUP_CONCAT()
MySQL uses GROUP_CONCAT(), which supports DISTINCT, ORDER BY, and custom SEPARATOR clauses.
SELECT
department_id,
GROUP_CONCAT(DISTINCT employee_name ORDER BY employee_name ASC SEPARATOR ', ') AS team_members
FROM employees
GROUP BY department_id;
- Default separator in MySQL is
,(no space), so specifySEPARATOR ', 'when you want spaces after commas. - Watch
group_concat_max_lenin MySQL if results approach length limits.
3. SQLite: GROUP_CONCAT()
SQLite provides GROUP_CONCAT(X) (default ,) and GROUP_CONCAT(X, Y) with a custom separator.
SELECT
department_id,
GROUP_CONCAT(employee_name, ', ') AS team_members
FROM employees
GROUP BY department_id;
4. Handling NULL Values and Empty Groups
- Most string-aggregation functions ignore
NULLvalues automatically rather than turning the whole result intoNULL. - To replace
NULLvalues with a placeholder before concatenating, wrap the column inCOALESCE(col, 'Unknown'). - If you want one string across the entire table rather than per group, omit the
GROUP BYclause (or group by a constant expression).
Quick Checklist
- Pick the right function for your SQL dialect:
STRING_AGG()for PostgreSQL and SQL Server;GROUP_CONCAT()for MySQL and SQLite. - Add
ORDER BYinside the aggregate when deterministic item order matters. - Use
DISTINCTorCOALESCEwhen duplicate labels orNULLvalues should be cleaned up first.
You must log in or register to comment.
