1

I know how to do this using PHP, but I was wondering if MySQL provides for a simpler solution.

UPDATE users SET fname = 'badooka', lname = '' WHERE user_id='322';

If a value is empty (lname, in this particular case), how do I ignore it instead of overwriting the original with an empty string?

1
  • 1
    I would agree with Myles response 'UPDATE users SET fname = 'badooka', lname = '' WHERE user_id='322' AND lname != '';' by doing so you are just ignoring empty value(lname, in this case) instead of overwriting the original with an empty string. Commented Nov 9, 2009 at 0:36

3 Answers 3

2

Do you mean UPDATE users SET fname = 'badooka', lname = '' WHERE user_id='322' AND lname != ''; Or do you mean have the database just not update that field that is empty? If the latter then no, there's not a simpler way, but the performance hit is negligible to update an additional field in a row that you are already updating.

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

Comments

1

Try this:

UPDATE users 
SET fname = IF(CHAR_LENGTH('badooka'),'badooka',fname), lname = IF(CHAR_LENGTH(''),'',lname) 
WHERE user_id='322';

That's the basic idea. If CHAR_LENGTH() returns 0, it'll use the original values.

Comments

1

The COALESCE operator will select the first non-null value of its arguments

so if you want to only update lname when lname is not empty, I might do something like this

UPDATE users SET fname = 'badooka', COALESCE( lname, SELECT lname FROM users where user_id='322' ) where user_id='322'

is that what you meant? this might be a bit of a performance hit if you're doing a lot, someone else know a better way?

2 Comments

Ok now that an answer has been accepted, I can see that obviously I misinterpreted the question as not overwriting a non-null with a null, where the asker meant not overwriting a null with a non-null...ah well if people come looking I still think this would be the answer if the case was reversed...
I would agree, sorry about the confusion

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.