Triggers: The Hidden Side of Databases

January 27, 2025 | by dbsnoop

Just like the advanced sensors of the Death Star can automatically track targets and record fired shots, triggers in databases are automatic guardians that monitor events and take actions without manual intervention. They are like imperial officers documenting every shot for future reference—useful, precise, and, of course, a bit dangerous in the wrong hands.

Let’s learn how to use triggers to record all the shots fired by the Death Star.


What Are Triggers?

Triggers are pieces of code that execute automatically in response to certain events (like the Death Star firing at rebel planets). These events can be:

  • INSERT: When a new shot is recorded.
  • UPDATE: When a shot is adjusted (e.g., someone adjusts the aim because the first attempt was poor).
  • DELETE: When old shot records are removed.

They are essential for automation, validation, and auditing.


The Scenario: Recording Death Star Shots

For this example, we have two tables:

  1. laser_shots: Contains the records of the fired shots.
  2. shot_audit: Maintains an audit log of all fired shots (because Palpatine likes to know who’s doing what).

Table Structures

CREATE TABLE laser_shots (
    shot_id INT PRIMARY KEY,
    target VARCHAR(100),
    fired_by VARCHAR(100),
    timestamp DATETIME DEFAULT CURRENT_TIMESTAMP
);

CREATE TABLE shot_audit (
    audit_id INT AUTO_INCREMENT PRIMARY KEY,
    shot_id INT,
    action VARCHAR(50),
    details VARCHAR(255),
    log_time DATETIME DEFAULT CURRENT_TIMESTAMP
);

Creating Triggers in MySQL

In MySQL, triggers can be created to automatically record fired shots:

DELIMITER //

CREATE TRIGGER after_shot_insert
AFTER INSERT ON laser_shots
FOR EACH ROW
BEGIN
    INSERT INTO shot_audit (shot_id, action, details) 
    VALUES (NEW.shot_id, 'INSERT', CONCAT('Shot fired by ', NEW.fired_by, ' at ', NEW.target));
END //

DELIMITER ;

Explanation:

  • AFTER INSERT: This trigger fires after each new shot is recorded.
  • NEW: Refers to the data of the new row inserted into the laser_shots table.
  • CONCAT: Creates a detailed message about the event.

Creating Triggers in PostgreSQL

In PostgreSQL, triggers are configured with a function:

CREATE OR REPLACE FUNCTION log_laser_shot()
RETURNS TRIGGER AS $$
BEGIN
    INSERT INTO shot_audit (shot_id, action, details) 
    VALUES (NEW.shot_id, 'INSERT', CONCAT('Shot fired by ', NEW.fired_by, ' at ', NEW.target));
    RETURN NEW;
END;
$$ LANGUAGE plpgsql;

CREATE TRIGGER after_shot_insert
AFTER INSERT ON laser_shots
FOR EACH ROW
EXECUTE FUNCTION log_laser_shot();

Explanation:

  • The function log_laser_shot logs the shots into the audit table.
  • NEW and CONCAT are used to generate the details of the record.

Creating Triggers in SQL Server

In SQL Server, triggers are directly configured:

CREATE TRIGGER after_shot_insert
ON laser_shots
AFTER INSERT
AS
BEGIN
    INSERT INTO shot_audit (shot_id, action, details, log_time) 
    SELECT shot_id, 'INSERT', CONCAT('Shot fired by ', fired_by, ' at ', target), GETDATE()
    FROM INSERTED;
END;

Explanation:

  • INSERTED: A pseudo-table containing the data of the new row inserted.
  • CONCAT and GETDATE(): Generate the message and record the event’s date/time.

Example of Inserting Shots

Let’s simulate recording fired shots:

INSERT INTO laser_shots (shot_id, target, fired_by)
VALUES (1, 'Alderaan', 'Darth Vader');

Result in the Audit Table:

audit_idshot_idactiondetailslog_time
11INSERTShot fired by Darth Vader at Alderaan2024-12-04 10:00:00

Cautions When Using Triggers

  1. Performance: Just like the Death Star requires extensive resources to operate, triggers can impact database performance if overused.
  2. Debugging: Since triggers are “invisible,” errors can be hard to trace. Document them thoroughly!
  3. Avoid Overuse: Don’t use triggers for complex business logic—leave that to the application.

Tips from Data Vader

Triggers are like the Death Star’s control panel: they monitor events automatically without direct action from you. They are perfect for tasks like auditing and automation, but they require wisdom in their use.

Remember: “With great triggers come great responsibilities for maintenance.” May the Force (and the integrity of your data) be with you!


A Final Word for Padawans

A trigger doesn’t need a button to be activated. It automatically comes into play whenever a write event—whether an insertion, update, or deletion—occurs on a table. Over the years, I’ve seen robust applications turn into space junk because people “forgot” about hidden triggers deep within the database. Therefore, document them carefully, Jedi! Ensure triggers are included in both the application and database documentation, or you might face the dark side of maintenance.

Don’t forget to check out our database monitoring and observability SaaS, Flightdeck:

  • Schedule a demo here.
  • Learn more about Flightdeck here.
dbsnOOp trial
Share

Read more