Aggregate ordered row values into one string
A string aggregate turns several row values into one display value. Specify the order inside the aggregate when the sequence matters. An ORDER BY applied to the final result sorts result rows, not the pieces already concatenated within one result.
The examples below describe the same operation in three dialects. They retain repeated names, skip a NULL name and place a comma followed by a space between the remaining values. The expected result is Aster, Basil, Aster.
Define the output contract
Each alternative contains its own read-only fixture. Sequence numbers 1 through 4 define the required order. The rows are deliberately written out of sequence so that incidental input order cannot explain the correct result.
Run just the example for your database. SQL Server needs a version that supports STRING_AGG, introduced in SQL Server 2017. Its ordered form also requires database compatibility level 110 or later. PostgreSQL and MySQL use different aggregate syntax, even though the desired text is identical.
Aggregate with SQL Server
WITH Names AS (
SELECT 2 AS Seq, CAST(N'Basil' AS nvarchar(20)) AS Name
UNION ALL SELECT 1, N'Aster'
UNION ALL SELECT 3, NULL
UNION ALL SELECT 4, N'Aster'
)
SELECT STRING_AGG(CAST(Name AS nvarchar(max)), N', ')
WITHIN GROUP (ORDER BY Seq) AS NamesText
FROM Names;
The conversion to nvarchar(max) occurs inside the aggregate. Casting a completed, limited-length aggregate afterward cannot repair an overflow that already occurred. Keep the separator and input in compatible string types.
STRING_AGG
documents its result-type rules.
Aggregate with PostgreSQL
WITH Names(Seq, Name) AS (
VALUES (2, 'Basil'), (1, 'Aster'),
(3, NULL), (4, 'Aster')
)
SELECT string_agg(Name, ', ' ORDER BY Seq) AS NamesText
FROM Names;
PostgreSQL places ordering inside the function call. Keep it there when joins or other processing could reorder a source subquery. The text result still consumes memory and must fit the database and application's practical limits.
Aggregate with MySQL
WITH Names AS (
SELECT 2 AS Seq, 'Basil' AS Name
UNION ALL SELECT 1, 'Aster'
UNION ALL SELECT 3, NULL
UNION ALL SELECT 4, 'Aster'
)
SELECT GROUP_CONCAT(Name ORDER BY Seq SEPARATOR ', ') AS NamesText
FROM Names;
MySQL limits the result with group_concat_max_len, whose documented default is 1024 bytes, and other server limits also apply. Inspect the session setting and warnings for larger results. An unexpectedly short string can be truncation, not missing source rows. Change only a deliberate session limit when needed, rather than raising a global setting for this small example.
Handle NULLs and duplicates deliberately
These aggregates omit NULL inputs rather than emitting an empty placeholder with its separator. An empty string is a real value and can produce adjacent separators. If a missing name must be visible, replace NULL with a chosen display label before aggregating. If every input is NULL or no rows qualify, the aggregate produces NULL. Apply a final COALESCE only if your output contract wants an empty string instead.
A repeated name is retained by these examples. To aggregate distinct names with a meaningful order, first produce one row per name and choose its ordering value, such as the earliest sequence number. Do not remove duplicates by accident when two distinct people can share a name. SQL Server does not accept DISTINCT directly in its STRING_AGG argument list, while other engines offer their own forms.
Keep display text separate from interchange data
Joining values with commas is not automatically CSV. A value containing a comma, quote or newline needs proper CSV escaping when a consumer will parse it. JSON or a dedicated CSV export can be a better boundary format. Preserve relational rows when downstream operations need filtering or joins.
Add a grouping key and GROUP BY when each parent needs a separate string. In that case, aggregate ordering determines the children within each string, and an outer ordering independently determines the order of the parent rows.
Source and further reading
This article addresses the problem raised by JohnnyM in “Concatenate text from multiple rows into a single text string” on Stack Overflow, licensed under CC BY-SA 4.0 . The question is the topic source. The explanations and examples here are newly authored from the database documentation, rather than reproduced from a community answer.


Author: Herman Schoenfeld