Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MYSQL syntax not evaluating not equal to in presence of NULL

Tags:

sql

mysql

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!

like image 971
user1904273 Avatar asked Apr 24 '13 08:04

user1904273


People also ask

Is is not NULL and != The same in SQL?

<> is Standard SQL-92; != is its equivalent. Both evaluate for values, which NULL is not -- NULL is a placeholder to say there is the absence of a value.

IS NOT NULL syntax in MySQL?

By default, a column can hold NULL values. The NOT NULL constraint enforces a column to NOT accept NULL values. This enforces a field to always contain a value, which means that you cannot insert a new record, or update a record without adding a value to this field.

What does <> mean in MySQL?

MySQLi For Beginners The symbol <> in MySQL is same as not equal to operator (!=). Both gives the result in boolean or tinyint(1). If the condition becomes true, then the result will be 1 otherwise 0.


1 Answers

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 
  • SQLFiddle Demo
  • SQLFiddle Demo (added some records)

  • Working with NULL Values

like image 185
John Woo Avatar answered Oct 08 '22 20:10

John Woo