Val
Val

Reputation: 17522

mysql replace an empty value

I was wondering if this is possible from mysql.

SELECT username FROM users_table

If username is NULL I would like to display something like "Unknown" I can do it on php comfortable with it just wondering if this something worth looking into :)

Upvotes: 2

Views: 4795

Answers (3)

Silver Light
Silver Light

Reputation: 45932

You can use IF function.

IF(condition, if_true, if_false)

So, your query is:

SELECT IF(NULL(username), "Unknown", username) FROM users_table

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

Upvotes: 2

Álvaro González
Álvaro González

Reputation: 146460

Last but not least, CASE:

SELECT
    CASE
        WHEN username IS NULL THEN '(Unknown)'
        ELSE username 
    END AS username
FROM users_table

I like it because it's easy to generalise when you have complex expressions (you can add as many WHEN as you want) and it works in many DBMS.

(In this case I'd use COALESCE from @ajreal's answer.)

Upvotes: 1

ajreal
ajreal

Reputation: 47321

SELECT IFNULL(username, 'Unknown') FROM users_table

OR

SELECT COALESCE(username, 'Unknown') FROM users_table

Upvotes: 6

Related Questions