EN
MS SQL Server - STRING_AGG function example
0 points
In this article, we would like to show you how to use STRING_AGG
function in MS SQL Server.
This function is used for concatenating multiple rows into one field with a specified separator.
Quick solution:
xxxxxxxxxx
1
SELECT [column1],
2
STRING_AGG([column2], 'separator')
3
FROM [table_name];
In this example, we want to display all the colors and a list of people who like each color in one field.

Note:
At the end of this article you can find database preparation SQL queries.
Query:
xxxxxxxxxx
1
SELECT [favorite_color],
2
STRING_AGG([name], ', ') AS 'people'
3
FROM [users]
4
GROUP BY [favorite_color];
Output:

create_tables.sql
file:
xxxxxxxxxx
1
CREATE TABLE [users] (
2
[id] INT IDENTITY(1,1),
3
[name] VARCHAR(50) NOT NULL,
4
[favorite_color] VARCHAR(100) NOT NULL,
5
PRIMARY KEY ([id])
6
);
insert_data.sql
file:
xxxxxxxxxx
1
INSERT INTO [users]
2
( [name], [favorite_color])
3
VALUES
4
('Tom', 'red'),
5
('Chris', 'green'),
6
('Kate', 'blue'),
7
('Jack', 'green'),
8
('Mark', 'green'),
9
('Ann', 'orange'),
10
('Natalie', 'pink');