What if your database could fix itself automatically every time data changes?
Why Trigger function creation in PostgreSQL? - Purpose & Use Cases
Imagine you have a busy online store database. Every time a new order is placed, you want to update the stock automatically. Doing this by hand means checking each order and changing stock numbers yourself.
Manually updating stock is slow and easy to forget. If you miss one update, your stock numbers become wrong. This causes unhappy customers and lost sales. Doing it by hand every time wastes time and causes mistakes.
Trigger functions automatically run code when something happens in the database, like adding an order. This means stock updates happen instantly and correctly without you lifting a finger. It keeps data accurate and saves you time.
UPDATE stock SET quantity = quantity - 1 WHERE product_id = 123; -- run this after each order manually
CREATE FUNCTION update_stock() RETURNS trigger AS $$ BEGIN UPDATE stock SET quantity = quantity - 1 WHERE product_id = NEW.product_id; RETURN NEW; END; $$ LANGUAGE plpgsql; CREATE TRIGGER stock_update AFTER INSERT ON orders FOR EACH ROW EXECUTE FUNCTION update_stock();Trigger functions let your database react instantly and correctly to changes, automating tasks that would be slow and error-prone if done by hand.
An online store automatically reduces product stock when a customer places an order, ensuring the website always shows the right stock without manual updates.
Manual updates are slow and risky.
Trigger functions automate reactions to data changes.
This keeps data accurate and saves time.