SQL STRING_AGG Function

The SQL STRING_AGG String Function concatenates the string expressions, and places a specified separator in-between them. Remember, this function will not place a separator at the end of the string. The basic syntax of the SQL Server STRING_AGG function is

SELECT STRING_AGG (String_Expression, Separator)
FROM [Source]
GROUP BY Columns

The list of arguments available for STRING_AGG is

  • String_Expression: Please specify a valid String Expression
  • Separator: Use VARCHAR or NVARCHAR type. This function will use this separator in-between string concatenation
  • Group By: This is an optional argument. Use this to perform Grouping.

For this SQL Server demonstration, we are going to use the below-shown data

SQL STRING_AGG Function 1

SQL STRING_AGG Function Example 1

In this String Function example, we will concatenate the Last name columns data using STRING_AGG function.

-- SQL Server STRING_AGG Function Example
USE [SQL Tutorial]
GO
SELECT STRING_AGG([LastName], ' , ') AS TextFile
  FROM [Employee]
SQL STRING_AGG Function 2

STRING_AGG Function Example 2

In this example, we are going to implement the Grouping along with the String_Agg function.

-- SQL Server STRING_AGG Function Example
USE [SQL Tutorial]
GO
SELECT STRING_AGG([LastName], ' , ') AS TextFile
  FROM [Employee]
  GROUP BY Occupation
SQL STRING_AGG Function 3