How to Use STRING_AGG in SQL Server

Last updated July 25, 2026 · By the SaturnSQL team

STRING_AGG(expression, separator) collapses grouped rows into one delimited string; add WITHIN GROUP (ORDER BY ...) to control ordering. It requires SQL Server 2017+; older versions use the FOR XML PATH trick.

SELECT customer_id,
       STRING_AGG(product_name, ', ') WITHIN GROUP (ORDER BY product_name) AS products
FROM order_items
GROUP BY customer_id;

Pre-2017 fallback with FOR XML PATH

SELECT c.id,
       STUFF((
         SELECT ', ' + oi.product_name
         FROM order_items oi
         WHERE oi.customer_id = c.id
         ORDER BY oi.product_name
         FOR XML PATH(''), TYPE
       ).value('.', 'nvarchar(max)'), 1, 2, '') AS products
FROM customers c;

STRING_AGG inherits the input's size limit and errors past 8000 bytes; cast the input to avoid that: STRING_AGG(CAST(product_name AS nvarchar(max)), ', ').

Run this in SaturnSQL

SaturnSQL is a browser-based SQL editor for teams: shared query library, schema-aware autocomplete, and scheduled exports to Google Sheets and Slack.

Try it free

Related SQL Server guides

© 2026 Panda Capital Oy Ab. All rights reserved.