AI Hints
PostgreSQL · Lesson 78 of 120

Practice: Stock Trigger

Orders reduce stock.

⏱ 2 min read▶ Video at 1:10:10🎓 Free
Watch this lesson in the PostgreSQL courseWatch on YouTube ↗Full PostgreSQL course

When an order item is added, that book's stock should drop. If there isn't enough stock, the order should be refused. A trigger can enforce both.

  • Item added
  • Stock drops
  • Not enough? Refuse

Stock goes down, or refuses

The function takes the quantity from stock, but only if there's enough. If no row was updated, raise exception stops the insert with a clear message. Run it. One item works, and one big order is refused.

query.sqlsql
CREATE FUNCTION take_stock() RETURNS trigger LANGUAGE plpgsql AS $$
BEGIN
  UPDATE books SET stock = stock - NEW.quantity
  WHERE book_id = NEW.book_id AND stock >= NEW.quantity;
  IF NOT FOUND THEN
    RAISE EXCEPTION 'Not enough stock for book %', NEW.book_id;
  END IF;
  RETURN NEW;
END $$;

CREATE TRIGGER items_stock AFTER INSERT ON order_items
FOR EACH ROW EXECUTE FUNCTION take_stock();

INSERT INTO order_items VALUES (1001, 5, 2);
SELECT stock FROM books WHERE book_id = 5;
INSERT INTO order_items VALUES (1002, 5, 500);
Output
CREATE FUNCTION
CREATE TRIGGER
INSERT 0 1
 stock
-------
    15
(1 row)

ERROR:  Not enough stock for book 5
CONTEXT:  PL/pgSQL function take_stock() line 6 at RAISE

Triggers, carefully

Triggers are powerful, but hidden. Keep them short and documented. Avoid triggers that call other triggers in long chains. And for business logic that changes often, application code may be clearer.

keyvalue
Shortand documented
Chainsavoid
Hiddentell your team
Complex rulesmaybe app code

Summary

Triggers can keep related tables in sync, like stock and orders. Next, roles and privileges.

Key takeaways
  • AFTER INSERT
  • Stock sync
  • CHECK refuses
Next up: Roles and Privileges — who can do what