Join child rows into a comma-separated list in SQL
Show each customer with their order references in a single cell instead of one row per order.
The task
A customer overview reads better with all order references in one cell. STRING_AGG concatenates the child rows in a defined order.
The snippet
Written for PostgreSQL. Versions for SQL Server, MySQL and Oracle are under Variations.
SELECT c.customer_id,
STRING_AGG(o.order_ref, ', ' ORDER BY o.order_ref) AS order_list
FROM customers c
JOIN orders o ON o.customer_id = c.customer_id
GROUP BY c.customer_id;
Как это работает
The JOIN produces one row per order, and STRING_AGG with an ORDER BY inside the call folds them back to one row per customer, comma-separated in a stable order. Without the ORDER BY the order of values is not guaranteed. Use LEFT JOIN plus COALESCE if customers without orders must still appear.
Variations
SQL Server
SQL ServerSELECT c.customer_id,
STRING_AGG(o.order_ref, ', ') WITHIN GROUP (ORDER BY o.order_ref) AS order_list
FROM customers c
JOIN orders o ON o.customer_id = c.customer_id
GROUP BY c.customer_id;
MySQL
MySQLSELECT c.customer_id,
GROUP_CONCAT(o.order_ref ORDER BY o.order_ref SEPARATOR ', ') AS order_list
FROM customers c
JOIN orders o ON o.customer_id = c.customer_id
GROUP BY c.customer_id;
Oracle
OracleSELECT c.customer_id,
LISTAGG(o.order_ref, ', ') WITHIN GROUP (ORDER BY o.order_ref) AS order_list
FROM customers c
JOIN orders o ON o.customer_id = c.customer_id
GROUP BY c.customer_id;
Questions that come up
What if the list can exceed the string limit?
MySQL's GROUP_CONCAT stops at group_concat_max_len (default 1024 bytes) and silently truncates; SQL Server's STRING_AGG raises an error past 8000 bytes unless you CAST the value to VARCHAR(MAX) or NVARCHAR(MAX). Oracle's LISTAGG errors past its VARCHAR2 limit (4000 bytes by default) unless you add ON OVERFLOW TRUNCATE (12.2+). Test against your worst-case parent.
Keep reading
Run these with autocomplete that knows your tables
SQLly is a native SQL workbench for macOS, Windows and Linux. Paste a snippet into a live connection and you get schema-aware IntelliSense, a plan viewer and guards against unsafe edits.