Using BEFORE INSERT Triggers in MySQL
📖 Scenario: You are managing a small online bookstore database. You want to ensure that every new book added has a valid price and automatically set the date when the book was added.
🎯 Goal: Create a books table and a BEFORE INSERT trigger that checks if the price is positive and sets the added_date to the current date if not provided.
📋 What You'll Learn
Create a
books table with columns id, title, author, price, and added_dateCreate a
BEFORE INSERT trigger named check_price_and_set_dateThe trigger must prevent inserting a book with a non-positive price by setting it to 1.00
The trigger must set
added_date to the current date if it is NULL during insert💡 Why This Matters
🌍 Real World
BEFORE INSERT triggers help maintain data quality by automatically checking and adjusting data before it enters the database, useful in many business applications.
💼 Career
Database developers and administrators often write triggers to enforce business rules and data integrity without relying on application code.
Progress0 / 4 steps