SQL SERVER

CONCAT_WS SQL Server Function: Ultimate Guide With Examples

intro

Let's explore what the CONCAT_WS function has to offer when it comes to string concatenation in SQL Server!

Tools used in the tutorial
Tool Description Link
Dbvisualizer DBVISUALIZER
TOP RATED DATABASE MANAGEMENT TOOL AND SQL CLIENT

String concatenation is a common operation when dealing with text data in a database. Here is why SQL Server provides some functions and operators to make that easier. This is where the CONCAT_WS SQL Server function comes in!

In this article, you will learn what CONCAT_WS is, how this string concatenation function works, and how to use it in real-world Transact-SQL examples!

Time to dive in!

What Is the CONCAT_WS SQL Server Function?

CONCAT_WS is a SQL Server function that accepts a separator and a list of strings. Given those arguments, it returns a string resulting from the concatenation of the string in the list using the specified separator. In other words, the CONCAT_WS SQL Server function takes a variable number of strings and concatenates them into a single string according to a separator.

“CONCAT_WS” stands for “concatenate with separator” and is one of the most common database functions to deal with string concatenation. Other popular approaches involve the CONCAT function and the + operator applied on strings.

SQL Server CONCAT_WS(): Syntax and How to Use It

In Transact-SQL, the SQL CONCAT_WS function has the following syntax:

Copy
        
1 CONCAT_WS(separator, argument1, argument2 [, ..., argumentN])

The arguments accepted by the function are:

  • separator: The separator to apply to the resulting string when concatenating the other arguments
  • argumentX: The string-like arguments to be concatenated according to the specified separator.

Keep in mind that CONCAT_WS requires a separator and a minimum of two other string arguments. Otherwise, SQL Server will raise the following error (the contents of the error will differ in other database management systems):

Copy
        
1 [Code: 189, SQL State: S1000]  The concat_ws function requires 3 to 254 arguments.

To better understand how the function works, consider the CONCAT_WS SQL example query below:

Copy
        
1 SELECT CONCAT_WS('-', 'Aa', 'Bb', 'Cc', 'Dd');
Executing a CONCAT_WS query in DbVisualizer
Executing a CONCAT_WS query in DbVisualizer

This returns the string 'Aa-Bb-Cc-Dd'.

The CONCAT_WS SQL Server function implicitly converts all arguments to strings before concatenation. The implicit conversion to strings follows the Transact-SQL rules for data type conversions. Thus, you can also use it with non-explicit string formats as below:

Copy
        
1 SELECT CONCAT_WS('-', 1, 'A', 2, 'B');
Numbers have been converted to strings
Numbers have been converted to strings

The resulting string is 1-A-2-B as if 1 and 2 were strings.

Note that CONCAT_WS ignores NULL values during concatenation, avoiding adding separators between them:

NULLs are skipped in the concatenation
NULLs are skipped in the concatenation

If the function receives arguments with all NULL values, it returns an empty string.

Use Cases of the SQL CONCAT_WS Function in Transact-SQL

Let's learn how to use CONCAT_WS in SQL Server by showing some of its most common use cases through real-world examples.

The following CONCAT_WS SQL Server queries will be executed in DbVisualizer, the database client with the highest user satisfaction in the market!

This is the table the statements will be run on:

The data in the Employee table as presented by DbVisualizer
The data in the Employee table as presented by DbVisualizer

As you can see, it is called Employee and stores information about the employees in a company.

Data Aggregation

The basic use case of the SQL CONCAT_WS function is to concatenate two or more columns to produce useful aggregate data. For example, you can use it to get complete names out of individual names and surnames:

Copy
        
1 SELECT Id, CONCAT_WS(' ', Name, Surname) as CompleteName 2 FROM Employee;
Note the name aggregation
Note the name aggregation

Great, the name strings have been aggregated as desired!

Address Concatenation

Since CONCAT_WS does not add the separator between NULL values, it is a great tool for concatenating strings that might have “blank” values. A common example is the concatenation of addresses.

Assume your target table has a column for the first address and a column for the second address. You can concatenate them consistently with the following query:

Copy
        
1 SELECT Id, Name, Surname, CONCAT_WS(' - ', FirstAddress, SecondAddress) as CompleteAddress 2 FROM Employee;
Note how the query ignores second addresses that are NULL
Note how the query ignores second addresses that are NULL

Awesome! When SecondAddress is NULL, the SQL Server CONCAT_WS function returns only FirstAddress as expected.

Generate Data in CSV Format

Suppose your goal is to get CSV-formatted data from a table. The first approach you might come up with is the following query:

Copy
        
1 SELECT STRING_AGG(CONCAT_WS(',', Id, Name, Surname, FirstAddress, SecondAddress, Role), CHAR(13)) AS CsvData 2 FROM Employee;
This is invalid CSV
This is invalid CSV

In this example, STRING_AGG concatenated the values of string expressions by placing a CHAR(13) (carriage return) between them. Simply put, it populated each line of the resulting CSV-formatted text.

Unfortunately, that query does not achieve the goal. The first line has fewer commas than the second, meaning the resulting string is not in CSV format. That occurs because CONCAT_WS ignores NULL values. To fix that, you need to use ISNULL or COALESCE to replace NULL with '' as follows:

Finally achieving valid CSV
Finally achieving valid CSV

Perfect, this time the query works like a charm!

Congratulations, you are now a SQL Server CONCAT_WS expert!

Conclusion

In this guide, you understood what the CONCAT_WS function is and how it works. This powerful string concatenation function helps you aggregate strings in multiple database management systems including SQL Server, MySQL, and PostgreSQL even when they have NULL values. Thanks to the real-world use cases shown above, you also learned how to use it.

As proven by the CSV generation example, string concatenation can be tricky, so to better understand how to use the SQL CONCAT_WS function, you need a powerful database client like DbVisualizer! In addition to presenting data visually, it supports several DBMS technologies, offers advanced query optimization capabilities, and can generate ERD-like schemas. Try DbVisualizer for free today!

FAQ

How does the CONCAT_WS SQL Server function differ from CONCAT?

The CONCAT_WS function in SQL Server is specifically designed for concatenating values with a specified separator. It allows you to concatenate multiple values, handling NULL values gracefully. In contrast, the CONCAT function simply concatenates values without any separator.

Is it possible to use NULL or an empty string as a separator with CONCAT_WS?

Yes, you can use NULL or an empty string as a separator with CONCAT_WS. In both cases, the function concatenates the string arguments with an empty string. So, for instance, CONCAT_WS('', 'A', 'B', 'C') would produce the string 'ABC'.

When is CONCAT_WS better than other string concatenation methods in SQL Server?

CONCAT_WS is particularly useful when concatenating values with a specific separator, as it allows for cleaner and more readable SQL code. It also excels in scenarios where you need to handle NULL values consistently.

What is the CONCAT_WS equivalent in MySQL?

In MySQL, the equivalent function to SQL Server’s CONCAT_WS is also called CONCAT_WS. The syntax and functionality are the same between the two databases, so they are direct equivalent functions.

How does the SQL Server CONCAT_WS function handle NULL values?

The SQL Server CONCAT_WS function simply skips NULLs as they were not arguments. In detail, it inserts the separator only between non-NULL values.

Dbvis download link img
About the author
Antonello Zanini

Antonello is a software engineer, and often refers to himself as a technology bishop. His mission is to spread knowledge through writing.

The Table Icon
Sign up to receive The Table's roundup
More from the table
Title Author Tags Length Published
title

Clustered vs Non-Clustered Index: Complete SQL Guide

author Antonello Zanini tags MySQL ORACLE POSTGRESQL SQL SQL SERVER 8 min 2025-02-13
title

Queries and Subqueries in SQL: The Definitive Guide

author Lukas Vileikis tags DbVisualizer MySQL POSTGRESQL SQL SQL SERVER 7 min 2025-02-12
title

How to Optimize a Clustered Index Scan in SQL

author Antonello Zanini tags MySQL SQL SQL SERVER 7 min 2025-02-11
title

SQL Derived Table: Everything You Need to Know

author Antonello Zanini tags MySQL POSTGRESQL SQL SQL SERVER 9 min 2025-02-06
title

A Complete Guide to the ALTER TABLE DROP COLUMN Statement

author Antonello Zanini tags MySQL ORACLE POSTGRESQL SQL SQL SERVER 8 min 2025-01-27
title

How to Use a Recursive CTE in SQL

author Antonello Zanini tags MySQL POSTGRESQL SQL SQL SERVER 5 min 2025-01-22
title

How to Use MERGE in SQL Query Statements: Complete Guide

author Antonello Zanini tags ORACLE POSTGRESQL SQL SQL SERVER 8 min 2025-01-20
title

A Guide to SQL Server Indexes on Partitioned Tables

author Antonello Zanini tags SQL SERVER 7 min 2025-01-13
title

How to Drop an Index By Partition Number in SQL Server

author Antonello Zanini tags SQL SERVER 7 min 2025-01-06
title

SQL CHECK Constraint: Definitive Guide With Examples

author Antonello Zanini tags MySQL ORACLE POSTGRESQL SQL SQL SERVER 8 min 2024-12-16

The content provided on dbvis.com/thetable, including but not limited to code and examples, is intended for educational and informational purposes only. We do not make any warranties or representations of any kind. Read more here.