0
0
SQLquery~30 mins

Why triggers are needed in SQL - See It in Action

Choose your learning style9 modes available
Understanding Why Triggers Are Needed in SQL
📖 Scenario: You are managing a small online bookstore database. You want to keep track of every time a book's price changes so you can analyze pricing trends later.
🎯 Goal: Build a simple SQL trigger that automatically records price changes in a separate table whenever the price of a book is updated.
📋 What You'll Learn
Create a table called books with columns book_id, title, and price
Create a table called price_changes with columns change_id, book_id, old_price, new_price, and change_date
Create a trigger called log_price_change that fires after an update on books
The trigger should insert a record into price_changes only if the price has changed
💡 Why This Matters
🌍 Real World
In real businesses, triggers help keep audit logs, enforce rules, and automate updates without extra application code.
💼 Career
Database administrators and developers use triggers to maintain data integrity and automate workflows in many industries.
Progress0 / 4 steps
1
Create the books table
Create a table called books with columns book_id as an integer primary key, title as text, and price as a decimal number.
SQL
Need a hint?

Use CREATE TABLE with the specified columns and types.

2
Create the price_changes table
Create a table called price_changes with columns change_id as an auto-increment integer primary key, book_id as integer, old_price and new_price as decimal numbers, and change_date as a timestamp.
SQL
Need a hint?

Use SERIAL for auto-incrementing change_id and set default for change_date.

3
Create the trigger function to log price changes
Create a trigger function called log_price_change_func that inserts a record into price_changes with the book_id, old_price, new_price, and current timestamp, but only if the price has changed.
SQL
Need a hint?

Use a trigger function with IF to check price change and insert accordingly.

4
Create the trigger to call the function after update
Create a trigger called log_price_change that fires AFTER UPDATE on the books table and calls the log_price_change_func function.
SQL
Need a hint?

Use CREATE TRIGGER with AFTER UPDATE and FOR EACH ROW.