Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

<> operator in SQL

I have a table like this

ID   Name    IsDeleted
1    Yogesh  Null
2    Goldy   1

Now when I run this query

select  * 
from tableName 
where IsDeleted <> 1

I should get ID 1 record, But I am not getting it,

But when I run this

select  * 
from tableName 
where IsDeleted is null

I get ID 1 record,

Why am I facing this behavior ?? Isn't NULL <> 1 is a true statement in SQL ??

IsDeleted is a bit type field with Allow Null true

like image 814
yogi Avatar asked Jan 17 '23 04:01

yogi


2 Answers

select * from table 
where COALESCE(IsDeleted, 0) <> 1 
-- or ISNULL instead of COALESCE. 
--ISNULL seems to be better in subqueries, but it's not ANSI SQL.

or

select * from table 
where IsDeleted <> 1 or IsDeleted IS NULL
like image 169
Raphaël Althaus Avatar answered Jan 18 '23 19:01

Raphaël Althaus


Comparing something with null will always result in unknown. That is why you need to use the is operator to compare null or use functions like COALESCE or isnull to replace null

like image 37
juergen d Avatar answered Jan 18 '23 19:01

juergen d