Search code examples
sqldatabasepostgresqltriggerssql-insert

Trigger to update current date in another table with Postgres 9


I have two tables called sale and customer. I want to create a trigger that updates the column last_purchase on customer table on each new insert in the sale table.

Table customer: customer_id, name, last_sale, ...
Table sale: sale_id, customer_id, date, ...

CREATE TRIGGER update_last_sale BEFORE INSERT ON sale FOR EACH ROW EXECUTE...

I have started writing, but I don't know how to do it.
Could someone help me?


Solution

  • CREATE FUNCTION update_customer_last_sale() RETURNS TRIGGER AS $$
    BEGIN
        UPDATE customer SET last_sale=now() WHERE cutomer_id=NEW.customer_id;
        RETURN NEW;
    END; $$
    LANGUAGE plpgsql;
    

    then

    CREATE TRIGGER update_last_sale
    BEFORE INSERT ON sale
    FOR EACH ROW EXECUTE update_customer_last_sale;
    

    NEW is the row which is about to be inserted in the sale table. (For an update row, it would be NEW for how the row will look after the update, and OLD for how the row looks before the update).