I have the following trigger on my table of customers so I can track whether the customer name has been changed over time and what the previous versions of the name were.
CREATE OR REPLACE FUNCTION fn_customer_changes_log_history() RETURNS trigger as
$BODY$
BEGIN
IF (NEW.name <> OLD.name)
THEN
INSERT INTO tbl_customers_history(customer_id, name, action)
VALUES(OLD.id, OLD.name, 'UPDATE');
END IF;
RETURN NEW;
END;
$BODY$
LANGUAGE plpgsql;
CREATE TRIGGER tr_customer_changes_log_history
BEFORE UPDATE ON tbl_customers
FOR EACH ROW
EXECUTE PROCEDURE fn_customer_changes_log_history();
But when I do an UPDATE when the NEW.name = NULL and and the OLD.name = "Customer 1" this trigger is not triggered? It only triggers when NEW.name has a actual string value here.
Why is that? NULL and "Customer 1" are not equal so it should trigger?
Use
IF (NEW.name IS DISTINCT FROM OLD.name)
instead of
IF (NEW.name <> OLD.name)
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