What is the purpose of the CONCAT_WS function in SQL?

Learn SQL with Udemy

For an instructor lead, in-depth look at learning SQL click below.


The CONCAT_WS function in SQL is designed to consolidate several expressions or strings into a single value, with each one separated by a specified separator. CONCAT_WS is an abbreviation for ‘Concatenate With Separator’. This function is highly useful in SQL and is often employed in domains like data manipulation and data cleaning.

Definition

The CONCAT_WS function works by concatenating the inputs after transforming them into strings. However, it also includes a separator between each concatenated item. The general syntax of this function is:

It’s important to highlight that the separator can be any SQL expression. If the separator is NULL, the function will treat it as an empty string.

Practical Example of CONCAT_WS

As an example, let’s consider a database that holds a table named “Employees” with the following data:

First Name Last Name Email
John Doe jdoe@example.com
Jane Smith jsmith@example.com

If we want to merge the first name, last name and email of each employee into a single string with comma as a separator, we can use the CONCAT_WS function. The SQL code would look like this:

The output of this request will be:

This is a simple yet very practical example of how to use the CONCAT_WS function in SQL to combine a series of variable length strings into a standard format. The CONCAT_WS function is thus a powerful tool in a SQL programmer’s toolbox!

Leave a Comment