The CONCAT_WS() function in MySQL is used to concatenate (combine) strings with a specified separator. It is a more flexible version of the CONCAT() function, as it allows you to specify a delimiter (separator) to insert between each string.
Syntax:
CONCAT_WS(separator, string1, string2, ..., stringN)
- separator: The string to use as a separator between the values being concatenated.
- string1, string2, ..., stringN: The strings to concatenate.
Key Features:
- Separator Insertion: The separator is added between each of the strings provided as arguments.
- Automatic Null Handling: If any of the strings are
NULL, they are skipped. The separator is not added for skipped values.
Examples:
1. Basic Usage
SELECT CONCAT_WS('-', '2024', '12', '20');
-- Output: '2024-12-20'
2. Skipping NULL Values
SELECT CONCAT_WS('-', '2024', NULL, '20');
-- Output: '2024-20'
3. Combining Table Columns
Suppose you have a table employees:
| first_name | last_name |
|---|---|
| John | Doe |
| Jane | Smith |
You can combine the names with a space as a separator:
SELECT CONCAT_WS(' ', first_name, last_name) AS full_name
FROM employees;
-- Output:
-- full_name
-- John Doe
-- Jane Smith
Notes:
- The
CONCAT_WS()function is particularly useful when formatting output that requires separators, such as creating CSV lines, constructing file paths, or formatting dates and times. - If you pass only the separator and no other arguments, the function will return an empty string.
No comments:
Post a Comment