2

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 :)

3 Answers 3

6
SELECT IFNULL(username, 'Unknown') FROM users_table

OR

SELECT COALESCE(username, 'Unknown') FROM users_table
Sign up to request clarification or add additional context in comments.

4 Comments

nice one :) thnx m8 question, using this method instead of the php version which one do you think is faster?... its just a stupid question but worth knowing :)
Both should be identical, IFNULL are mysql specifically, while COALESCE is a common string function for other sql as well. (COALESCE might slightly slower as it accept multiple arguments), but I think the difference is too small to mention
@Val If you use PHP you are able to handle blank users differently (e.g., assign a CSS class to display them in italics).
you can do it by adding username value on the class and just do the same class="<?php echo $username=='unknown'?'italic':'normal'; ?>"
2

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

1 Comment

Did you mean IF(ISNULL(...? I can't seem to find a NULL() function in the reference...
1

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.)

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.