What is the purpose of the STRING_AGG function in SQL?

Learn SQL with Udemy

For an instructor lead, in-depth look at learning SQL click below.


The STRING_AGG is a built-in function in SQL Server (starting with 2017) that concatenates the values of string expressions and places a separator between them. This function simplifies the concatenation of strings. Prior to SQL Server 2017, you had to use various workarounds to concatenate string values with a certain separator. Now with STRING_AGG, it’s just a piece of cake.

The Syntax

Where, ‘expression’ is the column that receives data for concatenating, ‘separator’ is the symbol or string that separates string values, and the optional ‘order_by_clause’ determines the sequence of concatenated values.

Examples

Basic Example:

Assume we have a table called ‘Orders’ like this:

And we want to aggregate the ‘Product’ values for each ‘OrderID’. We can use the STRING_AGG function like follows:

This will return:

With ORDER BY clause:

If we want to control the order of the aggregated strings, we can add the WITHIN GROUP clause like this:

This will return:

Note that STRING_AGG returns a single string result, and it’s very helpful in many scenarios where you need to concatenate string values in a single row, eliminating the need for additional looping or variables handling inside your SQL scripts.

Leave a Comment