Lesson

MySQL CONCAT_WS() Function

10 min reading
Free Course

MySQL CONCAT_WS() Function

The CONCAT_WS() function stands for Concatenate With Separator. It inserts a chosen delimiter between string arguments while automatically skipping any NULL values in the list.

Syntax

CONCAT_WS(separator, str1, str2, ...)
  • separator: The delimiter inserted between non-NULL values.
  • str1, str2, ...: Expressions to join using separator.
  • Return value: Joined string, or NULL only when separator itself is NULL.

Unlike CONCAT(), which collapses to NULL whenever a single input is NULL, CONCAT_WS() keeps the remaining valid values and avoids trailing delimiters.

Practical Example

Suppose you generate shipping labels from demo_customers using city, postal_code, and country. Several international records lack a postal_code.

SELECT
    customer_id,
    CONCAT_WS(', ', city, postal_code, country) AS location_line,
    CONCAT(city, ', ', postal_code, ', ', country) AS concat_comparison
FROM demo_customers;
customer_id location_line concat_comparison
1 Austin, 78701, USA Austin, 78701, USA
2 Dublin, Ireland NULL
3 10115, Germany NULL

In row 2, postal_code is NULL. CONCAT_WS() omits the missing value and extra comma, while CONCAT() collapses the whole string to NULL. Row 3 shows the same skip behavior when city is NULL.

Common Mistakes & NULL Behavior

  • Passing a NULL separator: CONCAT_WS() skips NULL values, never a NULL separator. Calling CONCAT_WS(NULL, 'a', 'b') returns NULL.
  • Empty strings are NOT skipped: CONCAT_WS('-', 'A', '', 'C') produces 'A--C'. Convert blank strings to NULL with NULLIF(col, '') if you want them skipped too.
  • Forgetting the first argument is the separator: Placing data in the first slot turns that column into the delimiter between the remaining columns.

Frequently Asked Questions

What happens if every argument after the separator is NULL?

CONCAT_WS(', ', NULL, NULL) returns an empty string '', not NULL, provided the separator itself is not NULL.

How do I skip both NULL and empty strings in CONCAT_WS()?

Wrap each optional column in NULLIF(col, ''), such as CONCAT_WS(', ', NULLIF(city, ''), country).

Is CONCAT_WS() faster than multiple COALESCE calls inside CONCAT()?

Readability is the biggest win. Both perform similarly, though CONCAT_WS() avoids repeated separators when middle fields are NULL.

Save Your Progress

Unlock Your
Full Potential.

Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.

Quick Access With

Enterprise-Grade Security Protocol

Try it Yourself

Experiment with the code from this lesson in our interactive playground.

Open Playground
MySQL Topic Hub

Stuck on this lesson?

Join our community of senior developers.

Ask in Forum