STRING_AGG Function in SQL Server

This function is introduced in SQL Server 2017 (14x) concatenates the values of string expressions and places separator values between them. The separator is not added at the end of the string.


For practice, use the dataset below. Each student is assigned three subjects. One input per student is required, with all of his chosen subjects listed in a single row separated by a comma.

StudentName Subject
Scott Mathematics
Scott Physics
Scott Chemistry
Williams Mathematics
Williams Physics
Williams Chemistry
Mary Mathematics
Mary Physics
Mary Chemistry
Mike Mathematics
Mike Physics
Mike Chemistry
John Mathematics
John Physics
John Chemistry
George Mathematics
George Physics
George Chemistry


SELECT  StudentName,
              STRING_AGG(Subjects,’,’) Subjects
FROM tbStudentInfo


StudentName Subjects
Scott Mathematics, Physics, Chemistry
Williams Mathematics, Physics, Chemistry
Mary Mathematics, Physics, Chemistry
Mike Mathematics, Physics, Chemistry
John Mathematics, Physics, Chemistry
George Mathematics, Physics, Chemistry

Hope you find this article helpful.

Please subscribe for more interesting updates.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s