How TRIGGER works in SQL? Best TRIGGER examples

How TRIGGER works in SQL? Best TRIGGER examples

SQL TRIGGERs are one of the most powerful yet often misunderstood features in relational databases. They allow us to automate actions, enforce business rules, and maintain data integrity without writing extra application code.

What is an SQL TRIGGER?

A TRIGGER in SQL is a special kind of stored procedure that is automatically executed when a specific database event occurs. Unlike regular stored procedures, TRIGGERs are event-driven, meaning that they fire in response to changes in a table.

Triggers can be activated by operations such as:

  • INSERT – fires when a new record is added
  • UPDATE – fires when an existing record is modified
  • DELETE – fires when a record is removed

They can execute before or after the triggering event, depending on how they are defined.

Types of Triggers

SQL TRIGGERs generally fall into two main categories:

1. BEFORE Triggers

Executed before the event occurs. Useful for validating or modifying data before it gets inserted, updated, or deleted.

CREATE TRIGGER before_insert_example
BEFORE INSERT ON users
FOR EACH ROW
BEGIN
    SET NEW.created_at = NOW();
END;

2. AFTER Triggers

Executed after the event has occurred. Commonly used for logging changes, updating related tables, or enforcing referential integrity.

CREATE TRIGGER after_insert_example
AFTER INSERT ON users
FOR EACH ROW
BEGIN
    INSERT INTO audit_log (user_id, action, timestamp)
    VALUES (NEW.id, 'INSERT', NOW());
END;

How TRIGGER Works in SQL?

When creating a TRIGGER, it must be associated with a specific table and an event type. Here’s a step-by-step breakdown of how an SQL TRIGGER works:

  1. Define the TRIGGER name and the table it applies to.
  2. Specify whether it fires BEFORE or AFTER the event.
  3. Define the operation that activates the trigger (INSERT, UPDATE, DELETE).
  4. Write the SQL statements to execute when the trigger fires.
  5. Apply constraints using OLD and NEW references, available in row-level triggers.

Best TRIGGER Examples

1. Automatically Set a Timestamp

Often, we want to set creation and update timestamps automatically for each row. A TRIGGER can handle this efficiently:

CREATE TRIGGER before_insert_users
BEFORE INSERT ON users
FOR EACH ROW
BEGIN
    SET NEW.created_at = NOW();
    SET NEW.updated_at = NOW();
END;

2. Prevent Deleting Vital Records

If we have critical records that shouldn’t be deleted, a TRIGGER can enforce this restriction:

CREATE TRIGGER prevent_admin_deletion
BEFORE DELETE ON users
FOR EACH ROW
BEGIN
    IF OLD.role = 'admin' THEN
        SIGNAL SQLSTATE '45000'
        SET MESSAGE_TEXT = 'Admins cannot be deleted';
    END IF;
END;

3. Log Changes Made to a Table

Maintaining an audit log of data changes improves traceability and security. A simple TRIGGER can store changes in a separate table:

CREATE TRIGGER log_user_updates
AFTER UPDATE ON users
FOR EACH ROW
BEGIN
    INSERT INTO user_audit_log (user_id, old_email, new_email, change_date)
    VALUES (OLD.id, OLD.email, NEW.email, NOW());
END;

Advantages and Disadvantages of Using TRIGGERs

Advantages Disadvantages
Automates database operations and ensures consistency. Can make debugging difficult due to hidden executions.
Reduces the need for application-side logic. May impact database performance if overused.
Improves security by enforcing business rules. Not all databases support TRIGGERs in the same way.

Conclusion

SQL TRIGGERs are a valuable tool for maintaining data integrity, enforcing rules, and automating processes within a database. However, they should be used strategically to avoid performance overhead and debugging challenges. By understanding how TRIGGERs work and implementing best practices, you can enhance your database’s efficiency and security.

 

Other interesting article:

How STORED PROCEDURE works in SQL? Best STORED PROCEDURE examples