MySQL has the CONCAT()
function, which allows you to concatenate two or more strings. The function actually allows for one or more arguments, but its main use is to concatenate two or more strings.
In MySQL (and in any computer programming environment), string concatenation is the operation of joining character strings end-to-end.
Here’s an example:
SELECT CONCAT('Homer', ' ', 'Simpson') AS 'Full Name';
Result:
+---------------+ | Full Name | +---------------+ | Homer Simpson | +---------------+
Note that I actually concatenated 3 strings here. I concatenated the first name, the last name, plus a space.
If I didn’t add the space it would’ve looked like this:
SELECT CONCAT('Homer', 'Simpson') AS 'Full Name';
Result:
+--------------+ | Full Name | +--------------+ | HomerSimpson | +--------------+
Which may or may not be the result you’re looking for.
So if we apply this to a database, then the query might look something like this:
SELECT CONCAT(FirstName, ' ', LastName) AS 'Full Name' FROM Individuals WHERE IndividualId = '1';
Result:
+---------------+ | Full Name | +---------------+ | Homer Simpson | +---------------+
If you’re concatenating more than two strings, and you need a space (or other separator), consider using the CONCAT_WS()
function. This allows you to specify a separator to be used in between each string. You only need to specify the separator once, and it’s used on every string that’s concatenated, therefore saving you from having to re-type it between each string.
NULL Arguments
The CONCAT()
function returns NULL
if any argument is NULL
.
Example:
SELECT CONCAT('Homer', NULL, 'Simpson') AS 'Full Name';
Result:
+-----------+ | Full Name | +-----------+ | NULL | +-----------+
Binary Strings vs Nonbinary Strings
The MySQL documentation states:
If all arguments are nonbinary strings, the result is a nonbinary string. If the arguments include any binary strings, the result is a binary string. A numeric argument is converted to its equivalent nonbinary string form.