Function or operator · Text, numbers and dates

STRING_AGG and GROUP_CONCAT: concatenating rows in SQL

STRING_AGG and GROUP_CONCAT join text from several rows into one string per group. The syntax for ordering depends on the engine.

Example

We want one row per category with a readable list of products. To make the example reproducible in SQLite 3.46.1, we sort the input set first and then apply group_concat.

Verified SQL
SELECT category,
       group_concat(name, ' · ') AS products
FROM (
  SELECT category, name
  FROM products
  ORDER BY category, name
)
GROUP BY category
ORDER BY category;

What changes from case to case

The syntax depends on the engine

Common ways to concatenate the values in a group
EngineExample with ordering
PostgreSQLstring_agg(name, ' · ' ORDER BY name)
SQL ServerSTRING_AGG(name, ' · ') WITHIN GROUP (ORDER BY name)
MySQLGROUP_CONCAT(name ORDER BY name SEPARATOR ' · ')
SQLitegroup_concat(name, ' · '); specify the order whenever it matters

Do not memorise one form as if it were universal SQL. The intent is shared, but the function name, the position of ORDER BY and options such as the separator vary.

The order is part of the result

For a sum, changing the input order does not change the total. For an aggregated string, it can change the final text. PostgreSQL and SQLite document that input order matters for this kind of aggregate; SQL Server and MySQL each have their own syntax for ordering it.

Relying on the physical order of the rows

Without an ordering rule, do not promise the list will come out alphabetically or in id order. Define the order with the syntax your engine documents.

What happens with NULL

The documented implementations of STRING_AGG/GROUP_CONCAT usually skip null inputs. That is different from inserting the literal text «NULL». If you need a placeholder, transform the value explicitly with a function such as COALESCE or your engine's equivalent.

Key differences between engines

PostgreSQL and SQL Server call the main function STRING_AGG. MySQL documents GROUP_CONCAT. SQLite documents group_concat and, in its current documentation, string_agg as an alias compatible with PostgreSQL and SQL Server. Even so, the ordering and separator options are not identical.