Compare nulll value with non null value SQL

Viewed 69

I have two columns as below:

Column A Column B
A1 NULL
A1 A1
B1 C1.

When i query these columns as below :

SELECT Column A, Column B from table where Column A != Column B

i am expecting the following result:

Column A Column B
A1 NULL
B1. C1

But my query is only giving me the second line as result.

5 Answers

null in SQL equals unknown

It could also have A1 as value, therefore it will not show up if you check if A1 is not null

Null values do not participate in equality operations as there is no value to compare with.

You will need to include a check for null into your comparisoon statement.

SELECT Column A, Column B from table where  ISNULL(Column A,0) <> ISNULL(Column B,0)
SELECT * from Your_table where IFNULL(`Column A`, 'NULL') != IFNULL(`Column B`, 'NULL')

IFNULL(expression, alt_value) function returns the value of the expression if it's not NULL and returns alt_value when expression is NULL. So, from the above query, Column A and Column B will have the string value of 'NULL' when the column has the NULL value so they can still be comparable.

You can use below workaround

select * from your_table
except distinct
select * from your_table
where columnA = columnB    

with output

enter image description here

Consider below

select *
from your_table
where columnA is distinct from columnB    

with output

enter image description here

Related