Create a BEFORE Trigger to Validate Data
📖 Scenario: You are managing a small online store database. You want to make sure that no product can be added with a negative price. To do this, you will create a BEFORE trigger that checks the price before inserting a new product.
🎯 Goal: Build a BEFORE trigger on the products table that prevents inserting a product with a negative price by raising an error.
📋 What You'll Learn
Create a
products table with columns id (integer), name (text), and price (numeric).Create a BEFORE INSERT trigger named
check_price_before_insert on the products table.The trigger should check if the new
price is less than 0.If the price is negative, the trigger should raise an error to prevent the insert.
💡 Why This Matters
🌍 Real World
Triggers help enforce business rules automatically in databases, such as preventing invalid data entry.
💼 Career
Database developers and administrators use triggers to maintain data integrity and automate checks.
Progress0 / 4 steps