Roshan
Roshan

Reputation: 2762

String concatenation in MySQL

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

Upvotes: 256

Views: 330693

Answers (5)

Eugene Yarmash
Eugene Yarmash

Reputation: 149823

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.

Upvotes: 440

gil.fernandes
gil.fernandes

Reputation: 14611

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

Upvotes: 6

Vithun
Vithun

Reputation: 360

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

Upvotes: 3

Harry Joy
Harry Joy

Reputation: 59660

Use concat() function instead of + like this:

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

Upvotes: 14

ADW
ADW

Reputation: 4080

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

Upvotes: 36

Related Questions