Collecting multiple rows into one comma-separated string used to require cursors. STRING_AGG does it in one line.
Basic Usage:
-- Get all tags for each post
SELECT
PostId,
STRING_AGG(TagName, ', ') AS Tags
FROM PostTags
GROUP BY PostId;
-- Result:
-- PostId Tags
-- 1 CSS, HTML, JavaScript
-- 2 SQL, Database, Performance
With Ordering:
SELECT
DepartmentId,
STRING_AGG(EmployeeName, ', ' ORDER BY EmployeeName) AS Employees
FROM Employees
GROUP BY DepartmentId;
With Distinct:
-- Remove duplicates first
SELECT
PostId,
STRING_AGG(DISTINCT TagName, ', ') AS UniqueTags
FROM PostTags
GROUP BY PostId;
Available in: SQL Server 2017+, PostgreSQL 9.0+, MySQL 8.0+
No more ugly cursor loops!
