Trigger for Data Validation in PostgreSQL
📖 Scenario: You are managing a customer database for an online store. To keep data clean, you want to make sure that no customer can be added with an invalid email address.
🎯 Goal: Create a PostgreSQL trigger that validates the email format before inserting a new customer record. If the email is invalid, the insertion should be stopped.
📋 What You'll Learn
Create a table called
customers with columns id (integer, primary key), name (text), and email (text).Create a trigger function called
validate_email that checks if the email contains an '@' character.Create a trigger called
email_check_trigger that calls validate_email before inserting a new row into customers.If the email is invalid, the trigger function should raise an exception to prevent the insert.
💡 Why This Matters
🌍 Real World
Triggers help keep data clean automatically by validating data before it enters the database, reducing errors and bad data.
💼 Career
Database developers and administrators use triggers to enforce business rules and data integrity without relying on application code.
Progress0 / 4 steps