0

I have a contacts table:

id   first_name   last_name   full_name
1    John         Doe         -null-
2    -null-       -null-      Mike Willson
3    Dany         Jean        -null-
4    Peter        -null-      -null-

How can i merge first_name and last_name columns to fill full_name column where full_name is NULL?

I would like to get results as this:

id   first_name   last_name   full_name
1    John         Doe         John Doe 
2    -null-      -null-       Mike Willson
3    Dany         Jean        Dany Jean
4    Peter        -null-      Peter
1
  • where does mike come from..? Commented Nov 25, 2019 at 20:08

3 Answers 3

2
UPDATE your_table
SET full_name = CONCAT_WS(' ', first_name, last_name)
WHERE full_name IS NULL
  AND COALESCE(first_name, last_name) IS NOT NULL

Will update the full_name if it's NULL and either first_name or last_name is not NULL.

Note that CONCAT_WS() will ignore NULL parameters. So if first_name or last_name is NULL, you will only get the other value without the ' ' space.

See demo on db-fiddle.com

Sign up to request clarification or add additional context in comments.

Comments

1

One option would be using CONCAT(), COALESCE() and TRIM() functions together :

UPDATE contacts_table
   SET full_name = TRIM(CONCAT( COALESCE(first_name,''), ' ', COALESCE(last_name,'') )) 

without a WHERE condition.

Demo

Comments

1

I'm doing it this way - and it wors fine:

UPDATE `conacts_table`
SET `full_name` = CONCAT(IFNULL(first_name, ''), ' ', IFNULL(last_name, ''))
WHERE `full_name` IS NULL

Just wonder if it's the optimal way to do it?

1 Comment

That and a couple of TRIMs, and a NULLIF if the concatenated result is an empty string.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.