Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to compare Null values from the database column [duplicate]

I have record in my table where Name column has Null value.. and I want to update that record using below query.. My sql query is:

set @Name=NUll;

update emp set name="gaurav" where name=@Name

When I run this query.. It will not update the record.. It does not compare the value Null to column value

How can this be done?

like image 883
Gaurav Gupta Avatar asked Nov 13 '13 10:11

Gaurav Gupta


People also ask

How do I compare two columns with NULL values in SQL?

Use <=> (null-safe equality operator) negated comparison which returns FALSE in case one of the operands is null but TRUE when both are null and both operands have equal non-null values.

Can we compare NULL values with comparison?

Because the NULL value cannot be equal or unequal to any value, you cannot perform any comparison on this value by using operators such as '=' or '<>'.

How do I compare NULL values in SQL?

How to Test for NULL Values? It is not possible to test for NULL values with comparison operators, such as =, <, or <>. We will have to use the IS NULL and IS NOT NULL operators instead.

Can we compare two NULL values in SQL?

To handle NULLs correctly, SQL provides two special comparison operators: IS NULL and IS NOT NULL. They return only true or false and are the best practice for incorporating NULL values into your queries. Now the query will return every row, as we expected.


3 Answers

SET @Name = NULL;

UPDATE emp
SET name="gaurav"
WHERE    (@Name IS NULL     AND name IS NULL)
      OR (@Name IS NOT NULL AND name = @Name)
like image 131
ta.speot.is Avatar answered Oct 14 '22 21:10

ta.speot.is


Also you can use following condition with ISNULL()

SET @Name = NULL;

UPDATE emp SET name='gaurav' WHERE ISNULL(@Name,'XXXXXXX')=ISNULL(Name,'XXXXXXX'); 

Where 'XXXXXXX' is a unique string constant which can't exist in EMP table;

like image 22
valex Avatar answered Oct 14 '22 20:10

valex


Tests with null values are always false in SQL, except IS NULL or IS NOT NULL. you should add a IS NULL clause to your WHERE:

WHERE name = @name
**OR (name IS NULL and @name IS NULL)**
like image 23
ARA Avatar answered Oct 14 '22 20:10

ARA