Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CONCAT multiple fields to a single field, single spaced

Tags:

concat

mysql

I'm trying to concatenate a first middle maiden and last name fields and use that to update a single field which is named fullname

For each user any combination of these 4 fields can be filled. From 0 to all 4. However I also need a single space between each name (not multiple spaces).

UPDATE nameTable SET fullname = CONCAT(first, middle, maiden, last); 
like image 422
kylex Avatar asked Dec 04 '12 21:12

kylex


People also ask

How do I concatenate multiple columns in SQL?

To concatenate more than 2 fields with SQL, you can use CONCAT() or CONCAT_WS() function.

How do I concatenate two columns in SQL with a hyphen?

Do it with two concats: select concat(concat(amt, '-'), endamt) as amount from mstcatrule; concat(amt,'-') concatenates the amt with the dash and the resulting string is concatenated with endamt .


2 Answers

MySQL has CONCAT_WS - concatenate with separator

CONCAT_WS(' ', first, middle, maiden, last); 

http://dev.mysql.com/doc/refman/5.0/en/string-functions.html#function_concat-ws

As pointed out by andr below, make sure any concatenated fields contain NULL and not an empty string ('') otherwise you will get a double space in the output.

Fiddle: http://sqlfiddle.com/#!2/1fe83/1

Further Application

Be careful therefore if in the future you use this function to make a small CSV list, because you won't get the comma for a NULL field. You'd have to do a COALESCE(column, '') wrapper around each nullable column.

like image 133
akatakritos Avatar answered Oct 06 '22 21:10

akatakritos


empty string solution TRIM(BOTH ' ' FROM CONCAT_WS(' ', first, middle, maiden, last))

http://dev.mysql.com/doc/refman/5.0/en/string-functions.html#function_trim

like image 43
jasz24 Avatar answered Oct 06 '22 20:10

jasz24