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?
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.
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 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.
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.
SET @Name = NULL;
UPDATE emp
SET name="gaurav"
WHERE (@Name IS NULL AND name IS NULL)
OR (@Name IS NOT NULL AND name = @Name)
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;
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)**
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With