The CONCAT() function in MySQL is used to concatenate two or more strings into a single string. It combines the values of the strings and returns the result.
Syntax:
CONCAT(string1, string2, ..., stringN)
- string1, string2, ..., stringN: The strings to concatenate. You can pass column names, literals, or expressions.
If any of the arguments is NULL, the CONCAT() function returns NULL. To avoid this, use CONCAT_WS() or handle NULL values explicitly.
Example Usages:
1. Concatenating String Literals:
SELECT CONCAT('Hello', ' ', 'World') AS Result;
-- Output: "Hello World"
2. Concatenating Columns:
SELECT CONCAT(first_name, ' ', last_name) AS FullName
FROM employees;
-- Output: "John Doe", "Jane Smith", etc.
3. Handling NULL Values:
SELECT CONCAT('Hello', NULL, 'World') AS Result;
-- Output: NULL
4. Using IFNULL() to Avoid NULL Result:
SELECT CONCAT(IFNULL(first_name, ''), ' ', IFNULL(last_name, '')) AS FullName
FROM employees;
Notes:
-
To use a delimiter between concatenated strings, consider using
CONCAT_WS(), which includes a separator:SELECT CONCAT_WS('-', '2024', '12', '20') AS Date; -- Output: "2024-12-20" -
CONCAT()can be useful in constructing dynamic SQL queries or formatting output for reports.
Would you like more examples or further assistance with this function?
No comments:
Post a Comment