Trigger functions in SQL
A stock floor enforced by the table itself: the trigger runs on every update.
-- A trigger function sees NEW and OLD; the trigger wires it to a table.
CREATE FUNCTION guard_stock()
RETURNS trigger
LANGUAGE plpgsql
AS $$
BEGIN
IF NEW.stock < 0 THEN
RAISE EXCEPTION 'stock for % cannot go below zero', NEW.sku;
END IF;
RETURN NEW;
END;
$$;
CREATE TRIGGER stock_floor
BEFORE UPDATE ON products
FOR EACH ROW
EXECUTE FUNCTION guard_stock();
-- A legal update sails through the guard.
UPDATE products
SET stock = 3
WHERE sku = 'PFD-M';
SELECT sku, stock
FROM products
WHERE sku = 'PFD-M';
How it works
RETURNS triggerfunctions seeNEWandOLDrow values.RAISE EXCEPTIONvetoes the write; returningNEWlets it through.CREATE TRIGGER ... BEFORE UPDATE ... FOR EACH ROWwires it to products.
Keywords and builtins used here
ASBEFOREBEGINCREATEEACHENDEXCEPTIONEXECUTEFORFROMFUNCTIONIFLANGUAGENEWONRETURNRETURNSROWSELECTSETTHENTRIGGERUPDATEWHEREtrigger
The run, in numbers
- Lines
- 26
- Characters to type
- 507
- Tokens
- 79
- Three-star pace
- 65 tpm
At the three-star pace of 65 tokens a minute, this run takes about 73 seconds.
Step 4 of 4 in Errors & triggers, step 20 of 23 in PostgreSQL Stored Procedures.