So here is my issue I am comparing new and old values when a table row is being updated. But the new or old value will sometimes be null. So the code below doesn't work. Can can I remedy this issue?
Thank You
BEFORE UPDATE ON mytable
FOR EACH ROW
BEGIN
IF OLD.assignedto != NEW.assignedto
THEN
INSERT INTO history
(
asset ,
changedfield ,
oldvalue ,
newvalue
)
VALUES
(
NEW.asset,
'assignedto',
OLD.assignedto,
NEW.assignedto
);
END IF;
END$$
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.
In SQL null is not equal ( = ) to anything—not even to another null . According to the three-valued logic of SQL, the result of null = null is not true but unknown. SQL has the is [not] null predicate to test if a particular value is null .
The IS NULL operator is used to test for empty values (NULL values).
To look for NULL values, you must use the IS NULL test. The following statements show how to find the NULL phone number and the empty phone number: mysql> SELECT * FROM my_table WHERE phone IS NULL; mysql> SELECT * FROM my_table WHERE phone = ''; See Section 3.3.
MySql has a special null-safe equality check operator:
<=>
NULL-safe equal. This operator performs an equality comparison like the = operator, but returns 1 rather than NULL if both operands are NULL, and 0 rather than NULL if one operand is NULL.
mysql> SELECT 1 <=> 1, NULL <=> NULL, 1 <=> NULL;
-> 1, 1, 0
mysql> SELECT 1 = 1, NULL = NULL, 1 = NULL;
-> 1, NULL, NULL
You can use this operator with the NOT operator:
mysql> SELECT NOT (1 <=> 1), NOT (NULL <=> NULL), NOT (1 <=> NULL);
-> 0, 0, 1
So, in your case you should write:
IF NOT (OLD.assignedto <=> NEW.assignedto)
Try:
IF ( (OLD.assignedto IS NOT NULL AND NEW.assignedto IS NOT NULL
AND OLD.assignedto != NEW.assignedto)
OR (OLD.assignedto IS NULL AND NEW.assignedto IS NOT NULL)
OR (OLD.assignedto IS NOT NULL AND NEW.assignedto IS NULL)
)
The comment is very much correct.
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