Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PostgreSQL not triggering when NEW.field is NULL

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?

like image 409
koala Avatar asked Nov 30 '25 02:11

koala


1 Answers

Use

IF (NEW.name IS DISTINCT FROM OLD.name)

instead of

IF (NEW.name <> OLD.name)
like image 182
Laurenz Albe Avatar answered Dec 01 '25 21:12

Laurenz Albe