0

I have such type of query:

SELECT table1.field1, table1.field2, table2.field3
FROM table1
LEFT JOIN table2 ON (...)

because of left join i sometimes have table2.field3 NULL

After that in my php script in cycle i redefine it manually

...
$row['field3'] = ($row['field3'] === null) ? 'undefined' : $row['field3']; 
...

But how can i get this 'undefined' in my result-set?

I ve searched for answer, COALESCE seems to work, but it have some strange logic with many-many arguments. Seems like it do what i want, but somehow strange..

Im interested if there another simple way to replace my NULL with 'undefined'?

3
  • COALESCE in mysql Commented Aug 17, 2015 at 4:39
  • have you looked at IFNULL ? Commented Aug 17, 2015 at 4:41
  • tim Mickey, nope. thanks Commented Aug 17, 2015 at 4:44

2 Answers 2

3

You should not be afraid of COALESCE... its ok.

But, there are other ways:

  1. Just use IF & IS NULL

    SELECT table1.field1, table1.field2, IF(table2.field3 IS NULL, 'undefined', table2.field3) AS field3

  2. Or simpler, use IFNULL (i believe you will like it)

    SELECT table1.field1, table1.field2, IFNULL(table2.field3, 'undefined') AS field3

https://dev.mysql.com/doc/refman/5.0/en/control-flow-functions.html#function_ifnull

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

Comments

1

You can also use case when,

Select 
    case when table1.field1 is null then 
        case when table1.field2 is null then 'undefined'
        else table1.field2 end 
    else table1.field1 end as field1
from tablename

you can use nested case when in case you want to check further level conditions.

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.