2

In my db there is a varchar(255) column and for some records it contains null values, when i fired this

SELECT * FORM my_table where some_column <> NULL;

nothing is returned

but when is fired

SELECT * FORM my_table where some_column IS NOT NULL;

I got desired records

can you explain what's the main difference between them and when to use <> and != operators.

5
  • 6
    The second is the correct, documented, and standard way to compare a value to NULL in SQL. For all practical purposes, the first is a typo. Commented Jan 25, 2019 at 12:46
  • 1
    NULL <> NULL is NULL, not true. Comparing NULL to any other value including NULL is always NULL and therefore not true, regardless of the comparison operator, unless it is IS NULL or IS NOT NULL. Commented Jan 25, 2019 at 12:47
  • Additional detail: some_column = NULL always returns false. Also some_column <> NULL always returns false. Commented Jan 25, 2019 at 12:49
  • 1
    @RobertKock - no it doesn't - it returns UNKNOWN/NULL. If your assertion was correct NOT (some_column = NULL) would be true. Commented Jan 25, 2019 at 12:50
  • @Damien_The_Unbeliever I didn't know that. Forget my comment. Commented Jan 25, 2019 at 12:52

2 Answers 2

6

From the Mysql 8 Reference:

You cannot use arithmetic comparison operators such as =, <, or <> to test for NULL. Because the result of any arithmetic comparison with NULL is also NULL, you cannot obtain any meaningful results from such comparisons.

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

Comments

2

In mysql a string column can be empty = '' or NUL (not values assigned )

so you should use for not empty

  SELECT * FORM my_table where some_column <> '';

or

  SELECT * FORM my_table where some_column  != '';

or not equal to a value

  SELECT * FORM my_table where some_column <> 'my_value';
  SELECT * FORM my_table where some_column != 'my_value';

for not null you must use the special operator IS NOT NULL

SELECT * FORM my_table where some_column IS NOT NULL;

2 Comments

so when to use <> and != operators ?
You need <> or != when you want check if the string is different from a string value see .. updated ..answer

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.