SQL Server STRING_AGG: GROUP BY, Order, DISTINCT and Errors

Quick answer: SQL Server STRING_AGG joins values from many rows into one string with a separator. Add GROUP BY to get one list per group:

SET NOCOUNT ON;
SELECT t.TeamName,
       STRING_AGG(e.FullName, ', ') AS Members
FROM dbo.Teams AS t
JOIN dbo.Employees AS e ON e.TeamID = t.TeamID
GROUP BY t.TeamName;

Result:

TeamName   Members                                                     
---------- ------------------------------------------------------------
Finance    Chloe Turner                                                
Sales      Hannah Brooks, Tyler Reed, Grace Miller                     
Support    Marcus Bennett, Olivia Hayes, Ethan Carter, Ryan Foster

Three teams, one row each. Legal has nobody, so the inner join leaves it out, and you’ll see how to keep it below.

SQL Server STRING_AGG with GROUP BY and JOIN in VS Code: one comma-separated member list per team
One row per team, members joined with a comma

Sample Tables for the STRING_AGG Examples

Tested on SQL Server 2025 Developer (17.0.1000.7), sqlcmd in VS Code. STRING_AGG needs SQL Server 2017 or later; Azure SQL Database has it too.

CREATE TABLE dbo.Teams (
    TeamID   int          PRIMARY KEY,
    TeamName nvarchar(10) NOT NULL
);
CREATE TABLE dbo.Employees (
    EmpID    int          PRIMARY KEY,
    FullName nvarchar(15) NOT NULL,
    TeamID   int          NOT NULL,
    City     nvarchar(10) NOT NULL,
    Email    varchar(30)  NULL
);
INSERT INTO dbo.Teams VALUES
(1, N'Sales'), (2, N'Support'), (3, N'Finance'), (4, N'Legal');
INSERT INTO dbo.Employees VALUES
(1, N'Hannah Brooks',  1, N'Columbus', 'hannah.brooks@example.com'),
(2, N'Tyler Reed',     1, N'Dayton',   'tyler.reed@example.com'),
(3, N'Grace Miller',   1, N'Columbus', 'grace.miller@example.com'),
(4, N'Marcus Bennett', 2, N'Austin',   'marcus.bennett@example.com'),
(5, N'Olivia Hayes',   2, N'Austin',   NULL),
(6, N'Ethan Carter',   2, N'Dallas',   'ethan.carter@example.com'),
(7, N'Ryan Foster',    2, N'Austin',   'ryan.foster@example.com'),
(8, N'Chloe Turner',   3, N'Denver',   'chloe.turner@example.com');

Why -Y 60 in my sqlcmd calls? STRING_AGG over nvarchar(15) returns nvarchar(4000), and sqlcmd pads it that wide.

Group By and Concatenate Strings Across a JOIN

The query above is the whole “group by join strings” pattern: join the parent, aggregate the child column, group by the parent. Leave out GROUP BY while selecting TeamName and you get Msg 8120.

Want empty teams too? Use a LEFT JOIN, just like an ordinary LEFT JOIN in SQL Server. The next section shows what comes back.

How Does STRING_AGG Handle NULL Values?

It skips them, separator included. Support has one NULL email; Legal has no rows at all:

SET NOCOUNT ON;
SELECT t.TeamName,
       COUNT(e.EmpID) AS People,
       ISNULL(STRING_AGG(e.Email, ';'), '(none)') AS Emails
FROM dbo.Teams AS t
LEFT JOIN dbo.Employees AS e ON e.TeamID = t.TeamID
WHERE t.TeamID IN (2, 4)
GROUP BY t.TeamName;

Two groups, two kinds of NULL:

TeamName   People      Emails                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          
---------- ----------- --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
Legal                0 (none)                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          
Support              4 marcus.bennett@example.com;ethan.carter@example.com;ryan.foster@example.com

Support has 4 people but 3 emails; Olivia’s NULL just vanished. Legal’s whole list is NULL, so ISNULL outside the call swaps in a placeholder.

Filter on an employee column in WHERE and Legal vanishes; the reason is in LEFT OUTER JOIN with a WHERE clause.

Want a marker per missing value? Put ISNULL(e.Email, 'n/a') inside the call.

Pick a STRING_AGG Separator: Comma, Pipe or New Line

Any varchar or nvarchar expression works, including CHAR(13) + CHAR(10):

SET NOCOUNT ON;
SELECT STRING_AGG(FullName, ' | ') AS Piped
FROM dbo.Employees WHERE TeamID = 1;
SELECT STRING_AGG(FullName, CHAR(13) + CHAR(10)) AS OnePerLine
FROM dbo.Employees WHERE TeamID = 1;

sqlcmd prints:

Piped                                                       
------------------------------------------------------------
Hannah Brooks | Tyler Reed | Grace Miller                   
OnePerLine                                                  
------------------------------------------------------------
Hannah Brooks
Tyler Reed
Grace Miller

The line-break version only shows up in text output. SSMS Results to Grid flattens it, so switch to Results to Text (Ctrl+T).

One rule from the docs: when your input is varchar, the separator can’t be nvarchar. Easy fix.

STRING_AGG WITHIN GROUP (ORDER BY): Sort the List

Without WITHIN GROUP, the order inside the list isn’t guaranteed. This is where the old “ORDER BY not working” complaints came from:

SET NOCOUNT ON;
-- ORDER BY on the query sorts the rows, not the list
SELECT TeamID, STRING_AGG(FullName, ', ') AS NoOrder
FROM dbo.Employees WHERE TeamID = 2
GROUP BY TeamID ORDER BY TeamID;
-- WITHIN GROUP sorts inside the list
SELECT TeamID, STRING_AGG(FullName, ', ')
       WITHIN GROUP (ORDER BY FullName) AS Sorted
FROM dbo.Employees WHERE TeamID = 2
GROUP BY TeamID;
BEGIN TRY
    EXEC (N'SELECT STRING_AGG(FullName, '', '' ORDER BY FullName)
            FROM dbo.Employees;');
END TRY BEGIN CATCH PRINT CONCAT(N'Msg ', ERROR_NUMBER(), N': ', ERROR_MESSAGE()); END CATCH;

Output:

TeamID      NoOrder                                                     
----------- ------------------------------------------------------------
          2 Marcus Bennett, Olivia Hayes, Ethan Carter, Ryan Foster     
TeamID      Sorted                                                      
----------- ------------------------------------------------------------
          2 Ethan Carter, Marcus Bennett, Olivia Hayes, Ryan Foster     
Msg 102: Incorrect syntax near 'STRING_AGG'.
SQL Server STRING_AGG WITHIN GROUP ORDER BY sorts the names; ORDER BY inside the parentheses fails with Msg 102
The outer ORDER BY doesn’t touch the list; WITHIN GROUP does

The first list follows EmpID, since that’s the order the rows happened to arrive in, and the outer ORDER BY TeamID sorts result rows only.

WITHIN GROUP fixes it. Same rule as ORDER BY in a SQL Server view: no explicit order, no promise.

PostgreSQL-style ORDER BY inside the parentheses? Msg 102.

One more catch I hit while testing: two STRING_AGG calls with different WITHIN GROUP orders in one SELECT fail with Msg 8711, “mutually incompatible orderings”. Move the second list into a subquery.

STRING_AGG DISTINCT: Remove Duplicates First

Support has three people in Austin. You want each city once, but DISTINCT doesn’t parse inside STRING_AGG:

SET NOCOUNT ON;
BEGIN TRY
    EXEC (N'SELECT STRING_AGG(DISTINCT City, '', '') FROM dbo.Employees;');
END TRY BEGIN CATCH PRINT CONCAT(N'Msg ', ERROR_NUMBER(), N': ', ERROR_MESSAGE()); END CATCH;
-- dedupe first, then aggregate
SELECT t.TeamName, STRING_AGG(d.City, ', ') AS Cities
FROM (SELECT DISTINCT TeamID, City FROM dbo.Employees) AS d
JOIN dbo.Teams AS t ON t.TeamID = d.TeamID
GROUP BY t.TeamName;

First the error, then the fix:

Msg 102: Incorrect syntax near ','.
TeamName   Cities                                                      
---------- ------------------------------------------------------------
Finance    Denver                                                      
Sales      Columbus, Dayton                                            
Support    Austin, Dallas
SQL Server STRING_AGG DISTINCT fails with Msg 102; deduplicating in a subquery returns unique cities per team
DISTINCT inside STRING_AGG fails; a DISTINCT subquery fixes it

Dedupe in a derived table, then aggregate. Each team now lists every city once, so Support shows Austin and Dallas instead of Austin three times. More on that pattern in DISTINCT with a JOIN.

STRING_AGG With Multiple Columns

STRING_AGG takes one expression, so build it with CONCAT. You can also put several STRING_AGG calls in one SELECT:

SET NOCOUNT ON;
SELECT TeamID,
       STRING_AGG(CONCAT(FullName, N' (', City, N')'), '; ') AS WhoWhere
FROM dbo.Employees
WHERE TeamID = 1
GROUP BY TeamID;

Result:

TeamID      WhoWhere                                                                
----------- ------------------------------------------------------------------------
          1 Hannah Brooks (Columbus); Tyler Reed (Dayton); Grace Miller (Columbus)

Non-string inputs such as int or date are converted to nvarchar for you. For a fixed format, convert first; see converting an int to a string.

Filter STRING_AGG Groups With WHERE, HAVING and LIKE

WHERE removes rows before they’re concatenated. HAVING removes whole groups after, and it can test the aggregated string itself:

SET NOCOUNT ON;
SELECT t.TeamName, STRING_AGG(e.FullName, ', ') AS Members
FROM dbo.Teams AS t
JOIN dbo.Employees AS e ON e.TeamID = t.TeamID
WHERE e.FullName LIKE N'%er%'          -- filters rows
GROUP BY t.TeamName
HAVING COUNT(*) >= 2;                  -- filters groups
SELECT TeamID, STRING_AGG(City, ', ') AS Cities
FROM dbo.Employees
GROUP BY TeamID
HAVING STRING_AGG(City, ', ') LIKE N'%Dallas%';

Both result sets:

TeamName   Members                                                     
---------- ------------------------------------------------------------
Sales      Tyler Reed, Grace Miller                                    
Support    Ethan Carter, Ryan Foster                                   
TeamID      Cities                                                      
----------- ------------------------------------------------------------
          2 Austin, Austin, Dallas, Austin

Only names containing “er” made it into the lists, and Finance dropped out with one match. The second query keeps just the team whose city list mentions Dallas.

The row-level filter works the same way as in an INNER JOIN with WHERE.

Error 9829: STRING_AGG Exceeded the 8000-Byte Limit

A varchar(30) input returns varchar(8000). Go past that and the query fails; it doesn’t truncate. I multiplied the 7 emails by 100 rows to hit it:

SET NOCOUNT ON;
BEGIN TRY
    SELECT LEN(STRING_AGG(e.Email, ';')) AS Chars
    FROM dbo.Employees AS e CROSS JOIN GENERATE_SERIES(1, 100) AS g;
END TRY BEGIN CATCH PRINT CONCAT(N'Msg ', ERROR_NUMBER(), N': ', ERROR_MESSAGE()); END CATCH;
-- fix: make the input a max type
SELECT LEN(STRING_AGG(CAST(e.Email AS varchar(max)), ';')) AS Chars
FROM dbo.Employees AS e CROSS JOIN GENERATE_SERIES(1, 100) AS g;

Output:

Chars      
-----------
Msg 9829: STRING_AGG aggregation result exceeded the limit of 8000 bytes. Use LOB types to avoid result truncation.
Chars               
--------------------
               17499
SQL Server STRING_AGG Msg 9829 exceeded the limit of 8000 bytes, fixed with CAST to varchar(max)
Msg 9829, then 17,499 characters after the CAST

Cast the input, not the result. If you wrap the finished STRING_AGG in a CAST, it has already failed by then, so the CAST has to go on the column you pass in.

Use varchar(max) or nvarchar(max). For nvarchar(n) input the cap is nvarchar(4000), same 8,000 bytes.

Don’t confuse it with Msg 2628 on INSERT: string or binary data would be truncated.

Before SQL Server 2017: FOR XML PATH and STUFF

On SQL Server 2016 and older there’s no STRING_AGG. The standard workaround builds the list with a correlated FOR XML subquery and strips the leading comma with STUFF:

SET NOCOUNT ON;
SET QUOTED_IDENTIFIER ON;  -- sqlcmd starts with it OFF
SELECT t.TeamName,
       STUFF((SELECT N', ' + e.FullName
              FROM dbo.Employees AS e
              WHERE e.TeamID = t.TeamID
              ORDER BY e.FullName
              FOR XML PATH(''), TYPE).value('.', 'nvarchar(max)'),
             1, 2, N'') AS Members
FROM dbo.Teams AS t
WHERE t.TeamID = 1;

Same list, built the old way:

TeamName   Members                                                     
---------- ------------------------------------------------------------
Sales      Grace Miller, Hannah Brooks, Tyler Reed

The first run failed with Msg 1934 because sqlcmd starts with QUOTED_IDENTIFIER OFF, and XML methods need it ON. SSMS sets it ON already.

Keep , TYPE).value(...). Without it, names with & or < come back XML-escaped.

Common STRING_AGG Errors and How to Fix Them

What you seeCauseFix
Msg 102 near ‘,’STRING_AGG(DISTINCT …)SELECT DISTINCT in a subquery first
Msg 102 near ‘STRING_AGG’ORDER BY inside the parenthesesWITHIN GROUP (ORDER BY …)
Msg 8711Two different WITHIN GROUP ordersSplit into a subquery
Msg 9829Result over 8,000 bytesCAST input to varchar(max)
Msg 4113 (not a valid windowing function)STRING_AGG(…) OVER (…)Grouped subquery, then join

Next step: if you need counts next to the lists, COUNT with JOIN and GROUP BY uses the same grouping. On PostgreSQL the function has the same name and accepts DISTINCT; see group concatenation in PostgreSQL.

Frequently Asked Questions

Does STRING_AGG need a specific compatibility level?

No. STRING_AGG works at any compatibility level; only the WITHIN GROUP clause needs level 110 or higher (STRING_AGG on Microsoft Learn).

How do I split a STRING_AGG list back into rows?

Use STRING_SPLIT(list, ‘,’). On SQL Server 2022 and later, pass 1 as the third argument to get an ordinal column so you keep the order.

Can STRI