2

I have two fields, but I want to return only the non-empty one.

select firstname, lastname, (if firstname != empty, then firstname else lastname) as name from users;

How do I go about doing something like above. Am not sure what should be inside the round brackets. I don't want to use PHP post-processing.

2 Answers 2

6

There are several ways you can do this in MySQL.

You can use the coalesce() function which returns the first non-null value among its arguments.

select coalesce(firstname, lastname) as name from users;

Alternatively, you could use a case statement:

select case when firstname is not null then firstname else lastname end as name from users;

Or you could use the if() function:

select if(firstname is not null, firstname, lastname) as name from users;

Or you could use the ifnull() function:

select ifnull(firstname, lastname) as name from users;
Sign up to request clarification or add additional context in comments.

1 Comment

@Alec Smart: That's ok. The important thing is that you got a correct answer to your question.
3

This works for both null values as well as empty strings ('')

SELECT IF(LENGTH(firstname), firstname, lastname) as name from users;

Comments

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.