String concatenation in MySQL

MysqlMysql WorkbenchConcat

Mysql Problem Overview


I am using MySQL and MySQL Workbench 5.2 CE. When I try to concatenate 2 columns, last_name and first_name, it doesn't work :

select first_name + last_name as "Name" from test.student

Mysql Solutions


Solution 1 - Mysql

MySQL is different from most DBMSs' use of + or || for concatenation. It uses the CONCAT function:

SELECT CONCAT(first_name, ' ', last_name) AS Name FROM test.student

There's also the CONCAT_WS (Concatenate With Separator) function, which is a special form of CONCAT():

SELECT CONCAT_WS(' ', first_name, last_name) from test.student

That said, if you want to treat || as a string concatenation operator (same as CONCAT()) rather than as a synonym for OR in MySQL, you can set the PIPES_AS_CONCAT SQL mode.

Solution 2 - Mysql

Try:

select concat(first_name,last_name) as "Name" from test.student

or, better:

select concat(first_name," ",last_name) as "Name" from test.student

Solution 3 - Mysql

Use concat() function instead of + like this:

select concat(firstname, lastname) as "Name" from test.student

Solution 4 - Mysql

That's not the way to concat in MYSQL. Use the CONCAT function Have a look here: http://dev.mysql.com/doc/refman/4.1/en/string-functions.html#function_concat

Solution 5 - Mysql

Apart from concat you can also use concat_ws (concatenate with separator):

SELECT CONCAT_WS(' ', first_name, last_name) from test.student

This function has the added benefit of skipping null values.

See https://dev.mysql.com/doc/refman/8.0/en/string-functions.html#function_concat-ws

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionRoshanView Question on Stackoverflow
Solution 1 - MysqlEugene YarmashView Answer on Stackoverflow
Solution 2 - MysqlADWView Answer on Stackoverflow
Solution 3 - MysqlHarry JoyView Answer on Stackoverflow
Solution 4 - MysqlVithunView Answer on Stackoverflow
Solution 5 - Mysqlgil.fernandesView Answer on Stackoverflow