85

I am having trouble with a mysql query. I want to exclude values of 2. So I thought I would do following:

table products

id | name     | backorder
-------------------
1  | product1 | NULL
2  | product2 | NULL
3  | product3 | 2

SELECT name from `products` p
WHERE backorder <> '2'

However, This is not giving the desired result of product1, product 2 It is giving an empty results table.

On the other hand if I use

SELECT name from `products` p
WHERE backorder = '2'

Then it produces: product3. But I want to get those records where it is not equal to 2.

Something is not working with the <> '2'. Could it be that the NULL values are throwing it off? Can anyone suggest a fix.

Thanks in advance!

simhumileco
  • 31,877
  • 16
  • 137
  • 115
user1904273
  • 4,562
  • 11
  • 45
  • 96

4 Answers4

118

use IS NULL or IS NOT NULL to compare NULL values because they are simply unknown.

SELECT name 
from   products p
WHERE  backorder IS NULL OR backorder <> 2
John Woo
  • 258,903
  • 69
  • 498
  • 492
  • That worked. Will mark correct when SO allows me. One question...some records have the value 1 in them. To allow for case where value is NULL or 1 should I be able to do something like (backorder IS NULL OR backorder ='1') . This is not working for me at the moment. – user1904273 Apr 24 '13 at 08:16
  • just to clarify, do you want to get both `NULL` and with value of `1`? – John Woo Apr 24 '13 at 08:17
  • Yes, I want everything but value=2 – user1904273 Apr 24 '13 at 08:18
  • so do you want to get all records except for `backorder = 2` right? then use this condition `backorder IS NULL OR backorder <> '2'` demonstrated here: http://www.sqlfiddle.com/#!2/e0e57/2 – John Woo Apr 24 '13 at 08:19
  • Is the reason for having to do a separate NULL check because "Unknown value" could mean, "Well, it MIGHT be the value you're looking for, but I just don't know"? – TMH Apr 08 '16 at 12:25
  • it works but `IS NULL` is very slow for large data. is there any way to make it faster – Elyor Dec 15 '18 at 14:03
57

Use the <=> operator.

You can use:

SELECT `name` FROM `products` `p`
WHERE NOT `backorder` <=> '2'

or

SELECT `name` FROM `products` `p`
WHERE !(`backorder` <=> '2')

See this answer for more information about the <=> operator:

What is this operator <=> in MySQL?

Joshua Pinter
  • 45,245
  • 23
  • 243
  • 245
simhumileco
  • 31,877
  • 16
  • 137
  • 115
8

We can use this also:

SELECT p.name 
FROM   products p
WHERE  COALESCE(backorder,1) <> 2
jbkhere
  • 101
  • 1
  • 6
-10

Try this and see.

SELECT name from `products` p
WHERE backorder != '2'
sentil kumar
  • 97
  • 2
  • 7