1

I was trying to compare values of some fields while using case when in mysql. I found strange behavior. So I tried following query. It's returning me false in mysql. I can't get reason behind it. Any Help?
select if(null=null,'true','false');

0

4 Answers 4

2

you should do with IS

 SELECT IF(NULL IS NULL,'true','false');

or if you are comparing other field name then for example

 SELECT * FROM `table_name` WHERE `field_name` IS NULL

or to negate it

 SELECT * FROM `table_name` WHERE `field_name` IS NOT NULL
Sign up to request clarification or add additional context in comments.

Comments

1

From the MySQL documentation at the Working with null values page:

The NULL value can be surprising until you get used to it. Conceptually, NULL means “a missing unknown value” and it is treated somewhat differently from other values.

since NULL is "unknown", the comparison NULL = NULL will be unknown as well and will return NULL, and since NULL is not TRUE your function will return 'false'.

You could use IS NULL operator:

SELECT IF(NULL IS NULL, 'true', 'false')

or you can also use then NULL-safe equal to operator:

SELECT IF(NULL <=> NULL, 'true', 'false')

Comments

1

You can compare NULL in below way also:

SELECT IF (NULL<=>NULL,'True','False');

Comments

0

NULL isn't a value; it's the lack of a value. So, logically, it cannot compare equally with itself.

This is not unique to MySQL; it is a phenomenon found across the field of computer programming (though there are some notable exceptions such as C).

The operator IS performs a more intelligent, null-aware "comparison", whereby NULL IS NULL evaluates to TRUE.

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.