Knowledge base / SQL

SQL STRING_AGG: combine rows with an explicit order

Combining labels into a list needs decisions about order and missing values. I show the same result in PostgreSQL and SQL Server with distinct syntax for each engine.

Kajo RudzińskiPublished Updated 5 min read

Separate rectangular tiles combined into ordered ribbons with separators, in yellow and navy pixel art.

When a recipient needs labels listed in one report cell, I would consider text aggregation. STRING_AGG combines values from multiple rows into one string with a chosen separator. Before using it, I would settle three questions: what defines a group, how its items should be ordered, and whether repetitions carry meaning.

This article compares PostgreSQL 18 with SQL Server 2017 and later. Microsoft confirms availability from SQL Server 2017; its ordered form requires database compatibility level 110 or higher. I keep the ordering syntax separate for the two engines instead of offering one apparently portable fragment.

Shared synthetic data, separate queries

Assume a table called task_labels, with integer project_id, unique integer item_id and a text label. The label can use nvarchar in SQL Server and text in PostgreSQL. Here, NULL represents a missing value rather than an empty string.

project_id item_id label
10 1 Beta
10 2 Alpha
10 3 Alpha
10 4 NULL
20 5 Gamma
30 6 NULL

In PostgreSQL, I put item ordering inside the aggregate:

SELECT project_id,
       string_agg(label, ', ' ORDER BY item_id) AS labels
FROM task_labels
GROUP BY project_id
ORDER BY project_id;

The PostgreSQL aggregate-expression documentation shows ORDER BY following the arguments. In SQL Server, the corresponding example uses WITHIN GROUP:

SELECT project_id,
       STRING_AGG(CAST(label AS nvarchar(max)), N', ')
           WITHIN GROUP (ORDER BY item_id) AS labels
FROM task_labels
GROUP BY project_id
ORDER BY project_id;

Both examples produce this result:

project_id labels
10 Beta, Alpha, Alpha
20 Gamma
30 NULL

For project 10, we read items 1, 2 and 3 in that order. Item 4 contributes neither a value nor an additional comma. Project 20 has one label. Project 30 has an input row but no non-null value to concatenate, so its result is NULL.

There are two independent orderings

The aggregate’s ordering controls labels inside a cell. The final ORDER BY project_id controls the rows of the completed result. One cannot replace the other. Without an ordering inside the aggregate, I would not promise a particular list order, even if several reads happened to display the same sequence.

PostgreSQL explicitly describes string_agg as order-sensitive. Our item_id is unique, resolving item order. When sorting by name or date, consider ties and an additional key where needed. Text ordering also depends on collation, so a report’s intended sequence deserves a deliberate choice rather than an assumption.

I would choose that order according to the use. A list of labels might be alphabetical. A process history is more likely to need an event time and identifier. Both can be rendered in one field, but recipients read them differently. An unexplained ordering can make a technically correct list harder to interpret.

Tiles arranged into a single ordered ribbon, with missing positions set aside and repetitions retained in a separate stack.

Duplicates and missing values need decisions

Both Alpha labels remain in ordinary aggregation. They could represent two legitimate assignments or a copy created by a join. I would establish the cause first. Removing repetition only from the final string can conceal a preparation error without explaining its effect on other measures produced from the same joined dataset.

When the requirement really is unique names, PostgreSQL allows:

SELECT project_id,
       string_agg(DISTINCT label, ', ' ORDER BY label) AS labels
FROM task_labels
GROUP BY project_id
ORDER BY project_id;

With the ordinary ordering of these sample names, project 10 produces Alpha, Beta. We have changed the list’s meaning too: unique names sorted by label replace the order of assignments. In SQL Server, I would first prepare SELECT DISTINCT project_id, label in a subquery, then aggregate its result. SQL Server’s function syntax does not accept DISTINCT as an argument here.

If each missing label should be visible, replace it before aggregating. For these PostgreSQL data:

SELECT project_id,
       string_agg(COALESCE(label, '(missing)'), ', ' ORDER BY item_id) AS labels
FROM task_labels
GROUP BY project_id
ORDER BY project_id;

Project 10 produces Beta, Alpha, Alpha, (missing), and project 30 produces (missing). Replacing NULL after aggregation would change only an empty result for the whole group. That serves a different purpose from exposing a missing label at a particular position. An empty string, '', is different again and can leave adjacent separators in a list.

SQL Server result type and length

The SQL Server example casts the input to nvarchar(max) before concatenation. The first argument influences the result type: bounded nvarchar produces nvarchar(4000), while bounded varchar produces varchar(8000). Casting the completed aggregate afterwards does not change the type in which the aggregation was built.

This does not mean every list should grow without a practical limit. I would still agree how many items the recipient can use and inspect the displaying client’s limits. A cell containing a thousand labels can be valid text and an awkward interface. I also make no universal performance claim against every older concatenation technique.

Counterparts in other databases

Engine Name I would check in its documentation
MySQL 8.4 GROUP_CONCAT
Oracle Database 19c LISTAGG
SQLite since 3.44.0 string_agg as a group_concat alias

SQLite 3.44.0 added string_agg; its aggregate documentation explains the alias and ordering syntax. In MySQL, I would also inspect group_concat_max_len. For Oracle LISTAGG, I would check overflow handling. A corresponding name does not guarantee identical limits or syntax.

Exercise and boundaries

Remove the row with item_id = 2 mentally: project 10 now has Beta, Alpha. Then decide whether an empty-string label should remain visible, be omitted or be replaced by a description. That decision should follow the list definition rather than a desire to remove an inconvenient comma.

I would use aggregation for presentation and retain the separate rows for subsequent calculations. Labels containing commas do not automatically become valid CSV or JSON when concatenated. For data exchange, choose the relevant format and its encoding rules. For combining fragments already in a single row, continue with CONCAT.

Key takeaways

Is STRING_AGG ordering syntax identical in SQL Server and PostgreSQL?

No. SQL Server uses WITHIN GROUP (ORDER BY ...) after the function call. PostgreSQL places ORDER BY inside the function parentheses, after the delimiter.

Does STRING_AGG remove duplicates?

An ordinary call retains repeated values. PostgreSQL supports DISTINCT inside the aggregate; in SQL Server, you can first prepare distinct rows in a subquery.

What happens to NULL?

These calls skip NULL values and their separators. A group containing only NULL produces NULL. An empty string is different and can leave visible separators in a list.

AI was used in an automated way while working on this article. If you want to learn how to do it too, check out this project.

Kajo Rudziński

Newsletter KajoData

Let’s keep in touch.

I write about data analysis, learning and changing careers. My newsletter and the sign-up form are in Polish. If that works for you, I’d be glad to see you there.