Creating Delete Triggers in PostgreSQL

One of the common data integrity issues that can happen in a database is the unintended deletion of a row. Here is how to create a DELETE trigger in PostgreSQL.

The example code below assumes you have a “customer_cus” table and a “customer_archive_cua” table with at least two fields. It is a good idea to add a timestamp field to the archive table with DEFAULT now(), so that the date of deletion is captured.

CREATE FUNCTION archive_customer() RETURNS TRIGGER AS '
BEGIN
INSERT INTO customer_archive_cua (name_cua, address_cua)
VALUES (OLD.name_cus,OLD.address_cus);
RETURN NULL;
END;
' LANGUAGE 'plpgsql';
CREATE TRIGGER customer_archive_on_delete AFTER DELETE ON customer_cus
FOR EACH ROW EXECUTE PROCEDURE archive_customer();

References

This entry was posted in DB2 and tagged , , , . Bookmark the permalink.

NewPush has solutions to fit your business needs.  For more than a decade, our focus has been to take on the technical challenges that are the hardest and most time-consumming.  Our goal is to free up your resources to focus on the core activities of your business and to drive your business performance.  Please visit our main site at newpush.com for more information or call us at +1-303-423-4500.