Concatenating row values in Transact-SQL

Many a time, SQL programmers are faced with a requirement to generate report-like resultsets right off of a Transact SQL
query. In most cases, the requirement arises from the fact that there are no sufficient tools or in-house expertise to develop
tools that can extract the data as a resultset and massage the data in the desired display format. Quite often folks are
confused about the potential of breaking relational fundamentals say like First Normal Form or the scalar nature of typed
values. (Talking about 1NF violations in a language like SQL which lacks sufficient domain support, allows NULLs and supports
duplicates is somewhat ironic to begin with, but that is a topic which requires detailed explanations.)

Concatenating column values or expressions from multiple rows are usually best done in a client side application language,
since the string manipulation capabilities of Transact SQL and SQL based DBMSs are somewhat limited. However, you can do these
using different approaches in Transact SQL, but avoiding such methods for long term solutions is your best bet.

A core issue

Even though SQL in general deviates considerably from the relational
model, its reliance on certain core aspects of relational
foundations makes SQL functional and powerful. One such core aspect is
the set based nature of SQL expressions (well, multi-sets
to be exact, but for the given context let us ignore the issue of
duplication). The primary idea is that tables are unordered
and hence the resultsets of any query that does not have an explicit
ORDER BY clause is unordered as well. In other words, the rows
in a resultset of a query do not have a prescribed position, unless it
is explicitly specified in the query expression.

On the other hand, a concatenated list is an ordered structure. Each
element in the list has a specific position. In fact,
concatenation itself is an order-utilizing operation in the sense that
values can be prefixed or post fixed to an existing list. So
approaches that are loosely called “concatenating row values”,
“aggregate concatenation” etc. would have to make sure that some kind
of an order, either explicit or implicit, should be specified prior to
concatenating the row values. If such an ordering criteria
is not provided, the concatenated string would be arbitrary in nature.

Considerations

Generally, requests for row value concatenations often comes in two
basic flavors, when the number of rows is known and small (typically
less than 10) and when the number of rows is unknown and potentially
large. It may be better to look at each of them separately.

In some cases, all the programmer wants is just the list of values from a
set of rows. There is no grouping or logical partitioning
of values like the list of email addresses separated by a semicolon or
some such. In such situations, the approaches can be the same
except the join conditions may vary. Minor variations of the examples
list on this page illustrate such solutions as well.

For the purpose of this article the Products table from Northwind
database is used to illustrate column value concatenations with a
grouping column. Northwind is a sample database in SQL Server 2000
default installations. You can download a copy from from theMicrosoft Downloads
Consider the resultset produced by the following query:

The goal is to return a resultset with two columns one with the Category
Identifier and the other with a concatenated list of all
the Product Names separated by a delimiting character, say a comma for
instance.

Concatenating values when the number of items is small and known upfront

When the number of rows are small and almost known upfront, it is easier
to generate the code. One common approach with a small set
of finite rows it the pivoting method. Here is an example where only
first four alphabetically sorted product names per categoryid is
retrieved:

The idea above is to create a expression inside the correlated subquery
that produces a rank (seq) based on the product names and
then use it in the outer query. Using common table expressions and the
ROW_NUMBER() function, you can re-write this as:

Note that ROW_NUMBER() is a newly introduced feature in SQL 2005. If you
are using any previous versions, you will have to use the
subquery approach (You can also use a self-join, to write it a bit
differently). Using the recently introduced PIVOT operator, you
can write the above as following :

Not only the syntax appears a bit confusing, it does not appear to offer
anything functionally beyond the CASE approach above. However,
in rare situations, it could come in handy.

Concatenating values when the number of items is not known

When the number of items that are to be concatenated is not known
upfront, the code can become a bit more demanding. The new features
in SQL 2005 make some of the approaches a bit easy. For instance, the
recursive common table expressions (CTEs) and the FOR XML PATH(”)
syntax makes the server do the hard work behind the concatenation
leaving the programmer to deal with the presentation issues. The
examples below make this point obvious.

Recursive CTE methods

The idea behind this method is from a newsgroup posting by Vadim
Tropashko similar to the ideas behind generating a materialized path
for hierarchies.

The CASE in the recursive part of the CTE is used to eliminate the
initial comma and you can use RIGHT or the SUBSTRING functions
to substitute it. Also, this may not be the best performing option,
however certain additional tuning could be done to make them
suitable for medium sized datasets.

Another approach using recursive common table expressions was sent in by
Anub Philip, an Engineer from Sathyam Computers that uses
separate common table expressions for the anchor and recursive parts.

You may notice a comma at the end of the concatenated string, which you
can remove using a STUFF, SUBSTRING or LEFT function. While the
above methods are deemed reliable by many at the time of writing, there
is no guarantee that it will stay that way given the internal
workings and evaluation rules of FOR XML PATH() expression in correlated
subqueries are not well documented.

Using Common Language Runtime

Though this article is about approaches using Transact SQL, this section
is included due to the popularity of CLR aggregates in SQL 2005. Not
only it
empowers the CLR programmer with new options for database development,
in some cases, they work at least as well as native Transact
SQL approaches.

If you are familiar with .NET languages, SQL 2005 offers a convenient
way to create user defined aggregate functions using C#, VB.NET or
similar languages that is supported by the Common Language Runtime
(CLR). Here is an example of a string concatenate aggregate function
written using C#.

Recursive functions in t-SQL have a drawback that the maximum nesting
level is 32. So this approach is applicable only for smaller
datasets, especially when the number of items within a group, that needs
to be concatenated, is less than 32.

This approach is based on the idea by Linda Wierzbecki where a table
variable with three columns is used within a table valued UDF.
The first column represents the group, second represents the currently
processing value within a group and the third represents the
concatenated list of values.

This approach is a variation of the kludge often known using the nickname as dynamic cross tabulation.

This approach is a variation of the kludge often known using the
nickname as dynamic cross tabulation. There is enough literature out
there which demonstrates the drawbacks and implications of using Dynamic
SQL. A popular one, at least from Transact SQL programmer’s
perspective, is Erland’s Curse and Blessings of Dynamic SQL.
The Dynamic SQL
approaches can be developed based on creating a Transact SQL query
string based on the number of groups and then use a series of CASE
expressions or ROW_NUMBER() function to pivot the data for
concatenation.

The drawbacks of rampant usage of cursors are well-known among the
Transact SQL community. Given the fact that they are generally
resource intensive, procedural and inefficient, one should strive to
avoid cursors or loop based solutions in general Transact SQL
programming.

This section details a couple of notorious methods often publicized by
some in public forums. The problem with these methods is that
they rely on the physical implementation model; changes in indexes,
statistics etc or even a change of a simple expression in the
SELECT list or ORDER BY clause can change the output. Also these are
undocumented, unsupported and unreliable to the point where one
can consistently demonstrate failures. Therefore these methods are not
at all recommended for production mode systems.

Scalar UDF with t-SQL update extension

The usage of an expression that involves a column, a variable and an
expression in the SET clause in an UPDATE statement rarely appear
intuitive. However, in general, the optimizer often seems to process
these values in the order of materialization, either in the internal
work tables or any other storage structures.

Regardless of how it is used, "aggregate concatenation" of row values in
Transact SQL, especially when there is a grouping, is not
a simple routine. Various programming considerations are to be carefully
considered to choose one method over another depending on
the situations. The most logical choice would be the availability of a
built-in operator with optional configurable parameters that
can do the concatenation of the values depending on the type. Till then,
reporting requirements and external data export routines
will have to rely on such Transact SQL programming hacks.