Skip to content
SQLSimplified
aggregate

STRING_AGG()

Concatenates values from a group into a single string, separated by a delimiter.

Description

STRING_AGG is an aggregate function that gathers values from a group and joins them into one string, with a separator between each value. It's the group-aware cousin of CONCAT — perfect for turning a list of names into a comma-separated string per department.

Syntax

STRING_AGG(expression, separator)
STRING_AGG(DISTINCT expression, separator)

Parameters

NameDescriptionOptional
expressionThe value to concatenate (usually a column).No
separatorThe delimiter inserted between values.No

Return Type

Returns a VARCHAR containing all grouped values joined by the separator. If the group is empty it returns NULL.

Examples

Employees & Departments

Loading database engine...

Employees & Departments

Loading database engine...

Order the values

To control the order of items in the result, use the ORDER BY clause inside the function: STRING_AGG(first_name ORDER BY first_name, ', ').

Common Mistakes

  • Forgetting GROUP BY. Without a grouping, STRING_AGG collapses every row into a single string.
  • Assuming a fixed order. The order of concatenated values isn't guaranteed unless you use ORDER BY inside the call.
  • Mixing with NULLs. NULL values in the group are skipped, not rendered as empty slots.

See also: CONCAT, ARRAY_AGG.

Search

Search lessons, functions, examples, and practice problems