MySQL CONCAT_WS()

The CONCAT_WS() function concatenates strings with a specified separator. It is useful for combining strings with a consistent delimiter.

Examples

1. Concatenating Strings with a Separator

SELECT CONCAT_WS(', ', 'Raja Raja', 'Chola', 'The Great') AS full_name;

Code Explanation: This query concatenates the strings 'Raja Raja', 'Chola', and 'The Great' with a comma and space as the separator, resulting in 'Raja Raja, Chola, The Great'.

2. Using CONCAT_WS with Column Data

SELECT CONCAT_WS(' - ', king_name, kingdom) AS king_description FROM tamil_kings_auto_increment;

Code Explanation: This query concatenates king_name and kingdom with ' - ' as the separator for all records.

Best Practices

  • Use CONCAT_WS() when you need to join strings with a consistent separator.
  • Ensure that the separator is meaningful and does not cause confusion in the output.

Key Takeaways

  • The CONCAT_WS() function concatenates strings with a specified separator.
  • It is useful for generating formatted text and combining strings.