✏️ Explanatory Question

What is the difference between the CONCAT() and CONCAT_WS() functions?

👁 6 Views
📘 Detailed Answer
🟢 Easy
💡

Answer with Explanation

32

What is the difference between CONCAT() and CONCAT_WS()?

Level: Intermediate — Tests your knowledge of string joining and, crucially, NULL handling.

Both functions join two or more strings into one, but they differ in how they handle separators and NULL values.

  • CONCAT(): Joins strings directly with no separator. If any argument is NULL, the entire result becomes NULL.
  • CONCAT_WS(): "Concatenate With Separator" — the first argument is the separator, placed between the remaining values. It skips NULL values instead of returning NULL.
The key advantage: CONCAT_WS() is NULL-safe. A single NULL won't wipe out the whole result — it simply gets skipped, and the separator is not duplicated around it.

Side-by-Side Comparison

Feature CONCAT() CONCAT_WS()
Separator None (manual) First argument
NULL handling Returns NULL if any arg is NULL Skips NULL values
Best for Simple joins CSV, full names, addresses

NULL Behaviour Demonstrated

CONCAT() with NULL

  • CONCAT('A', NULL, 'B')
  • Result: NULL (whole thing lost)

CONCAT_WS() with NULL

  • CONCAT_WS('-', 'A', NULL, 'B')
  • Result: 'A-B' (NULL skipped)

Quick Example

-- CONCAT: manual separator, NULL breaks it
SELECT CONCAT('My', 'SQL');                 -- MySQL
SELECT CONCAT(first_name, ' ', last_name)   -- needs manual space
FROM employees;
SELECT CONCAT('A', NULL, 'B');              -- NULL

-- CONCAT_WS: separator handled once, NULL-safe
SELECT CONCAT_WS(' ', first_name, middle_name, last_name) AS full_name
FROM employees;   -- skips NULL middle_name cleanly

-- Build a comma-separated address
SELECT CONCAT_WS(', ', street, city, state, pincode) AS address
FROM customers;
Interviewer tip: The one-liner they want — "CONCAT joins strings with no separator and returns NULL if any argument is NULL, while CONCAT_WS uses the first argument as a separator and safely skips NULL values."