SQL Server's new STRING_AGG function

Posted: (EET/GMT+2)

 

SQL Server 2017 finally added a feature that developers have wanted for years: the STRING_AGG function. It lets you concatenate values from multiple rows into a single string, without having to use XML tricks or complex subqueries.

In older versions of SQL Server, if you wanted to combine multiple values into a comma-separated list, you usually had to write something like this:

SELECT Name + ',' 
FROM Employees 
FOR XML PATH('');

This worked, but it was clunky and hard to read. With STRING_AGG, it becomes much cleaner:

SELECT STRING_AGG(Name, ',') AS EmployeeList
FROM Employees;

You can also add an ORDER BY clause inside the function to control the output order:

SELECT STRING_AGG(Name, ',') 
       WITHIN GROUP (ORDER BY Name)
FROM Employees;

The result is a single row with all employee names combined into one string. It's simple, efficient, and long overdue.

STRING_AGG works on both text and numeric columns (after conversion) and is a great addition to SQL Server's T-SQL language. If you've ever needed to flatten rows into a single value, this is the new go-to solution.