Clement
Clement

Reputation: 35

How do I run if statement

I have one table in my MySQL database, having phones and names like:

etc...

and I'm listing names, but I want to replace a name which is null with a phone in my results

like IF(name IS NULL){SELECT phone AS name}else{SELECT name} FROM users

and get:

Is there any way to do this?

Upvotes: 1

Views: 63

Answers (4)

user1773603
user1773603

Reputation:

Try this:

IF (SELECT name FROM tbl_your WHERE name IS NULL) SELECT phone AS name
ELSE SELECT name;

Upvotes: 1

solamente
solamente

Reputation: 266

You can do this:

SELECT id, 
   IF(name IS NULL, phone, name) as name
FROM report

Here you can find more info

http://dev.mysql.com/doc/refman/5.0/en/control-flow-functions.html.

Upvotes: 3

Blue
Blue

Reputation: 22921

In addition to the COALESE function, or for more complex IF statements, you can use CASE statements:

SELECT CASE WHEN name IS NULL THEN phone ELSE name END AS name_or_phone

If you're involving multiple tables, join them, and reference them in the CASE:

SELECT CASE WHEN users.name IS NULL THEN phones.phone ELSE users.name END AS name_or_phone
FROM users
LEFT JOIN phones on phones.user_id = users.user_id

See Case statements on MySQL Docs.

Upvotes: 1

Mureinik
Mureinik

Reputation: 312219

The coalesce function seems like an easy way to achieve this:

SELECT COALESCE(name, phone) FROM users

Upvotes: 3

Related Questions