How to Use CONCAT Function in MySQL: Syntax and Examples
In MySQL, use the
CONCAT() function to join two or more strings into one. Pass the strings as arguments inside the parentheses, separated by commas, like CONCAT('Hello', ' ', 'World') which returns 'Hello World'.Syntax
The CONCAT() function joins multiple strings into one continuous string. You list the strings or columns you want to join inside the parentheses, separated by commas.
- CONCAT(str1, str2, ...): Joins all strings
str1,str2, etc. - If any argument is
NULL, the result isNULL.
sql
CONCAT(string1, string2, ...)Example
This example shows how to join first and last names from a table into a full name with a space in between.
sql
SELECT CONCAT(first_name, ' ', last_name) AS full_name FROM users;
Output
full_name
John Doe
Jane Smith
Alice Johnson
Common Pitfalls
One common mistake is that if any argument to CONCAT() is NULL, the entire result becomes NULL. To avoid this, use CONCAT_WS() or handle NULL values explicitly.
Also, remember to add spaces or separators manually if needed, as CONCAT() just joins strings directly.
sql
/* Wrong: returns NULL if last_name is NULL */ SELECT CONCAT(first_name, ' ', last_name) FROM users; /* Right: use CONCAT_WS to skip NULLs and add separator */ SELECT CONCAT_WS(' ', first_name, last_name) FROM users;
Quick Reference
- CONCAT(str1, str2, ...): Joins strings, returns NULL if any argument is NULL.
- CONCAT_WS(separator, str1, str2, ...): Joins strings with separator, skips NULLs.
- Use single quotes
' 'for string literals. - Add spaces or punctuation manually inside
CONCAT().
Key Takeaways
Use CONCAT() to join multiple strings into one in MySQL.
If any argument is NULL, CONCAT() returns NULL; use CONCAT_WS() to avoid this.
Manually add spaces or separators inside CONCAT() as it does not add them automatically.
Use single quotes for string literals inside CONCAT().
CONCAT_WS() is useful for joining strings with a separator and ignoring NULL values.