MySQL CONCAT_WS() Function

The CONCAT_WS() function in MySQL concatenates (joins together) two or more strings, with a separator that you specify. This is a very useful function for creating combined text strings from individual parts.



CONCAT_WS(): Definition and Usage

CONCAT_WS() is designed to make string concatenation simpler and more readable, particularly when you need to insert a separator between multiple strings. The first argument is always the separator, followed by the strings you wish to join. If the separator is NULL, the function returns NULL. Any arguments that are NULL are skipped.

Syntax

Syntax

CONCAT_WS(separator, expression1, expression2, expression3, ...)
      

Parameter Values

Parameter Description
separator The string used as a separator between the expressions. This is required. If NULL, the result is NULL.
expression1, expression2, expression3, ... The strings to concatenate. At least one expression is required. NULL expressions are skipped.

Related Function

For basic string concatenation without a separator, see the CONCAT() function.

Examples

Concatenating Strings with a Separator

This example concatenates strings with a "-" separator.

Syntax

SELECT CONCAT_WS("-", "SQL", "Tutorial", "is", "fun!") AS ConcatenatedString;
      
Output

SQL-Tutorial-is-fun!
      

Concatenating Columns into an Address

This example combines 'Address', 'PostalCode', and 'City' columns from a 'Customers' table into a single 'Address' column using spaces as separators. (Assumes a 'Customers' table exists with these columns.)

Syntax

SELECT CONCAT_WS(" ", Address, PostalCode, City) AS Address
FROM Customers;
      
Output

Address
------------------------------------
(Combined address for each customer will be displayed here)
      

**Note:** The second example's output will vary depending on the data in your `Customers` table. Each row will show the combined address string, with spaces as separators between the address components. If any of the `Address`, `PostalCode`, or `City` values are `NULL`, that part will be skipped in the output string.