Database.Middle.What is a trigger? How and when would you use it?

A trigger in SQL is a database object that automatically executes (or “fires”) a specified block of code in response to certain events (like INSERT, UPDATE, or DELETE) on a table or view.


🔧 What Is a Trigger?

A trigger is like a hidden “watchdog” that runs custom logic automatically when data changes in a table.


🧠 When Would You Use a Trigger?

✅ Common Use Cases:

Use CaseDescription
Audit loggingLog who changed what and when
Enforcing business rulesBlock or transform certain changes
Auto-updating fieldsE.g., update updated_at on row change
Cascading actionsAutomatically affect related records
Preventing invalid changesValidate complex conditions before changes

🧾 Basic Trigger Syntax (PostgreSQL)

-- 1. Create a trigger function
CREATE OR REPLACE FUNCTION update_timestamp()
RETURNS TRIGGER AS $$
BEGIN
  NEW.updated_at := NOW();
  RETURN NEW;
END;
$$ LANGUAGE plpgsql;

-- 2. Attach trigger to a table
CREATE TRIGGER set_updated_at
BEFORE UPDATE ON users
FOR EACH ROW
EXECUTE FUNCTION update_timestamp();

✅ Now every time a users row is updated, updated_at is set to NOW() automatically.

🚦 Trigger Timing Options

KeywordFires When?
BEFORE INSERTBefore inserting a row
AFTER INSERTAfter inserting a row
BEFORE UPDATEBefore an update
AFTER UPDATEAfter an update
BEFORE DELETEBefore deleting a row
AFTER DELETEAfter deleting a row

🧮 FOR EACH ROW vs FOR EACH STATEMENT

OptionDescription
FOR EACH ROWFires once per affected row
FOR EACH STATEMENTFires once per SQL statement

🐬 Example: MySQL Trigger

CREATE TRIGGER log_deletes
AFTER DELETE ON users
FOR EACH ROW
INSERT INTO deleted_users_log(user_id, deleted_at)
VALUES (OLD.id, NOW());

⚠️ Trigger Considerations

AdvantageDisadvantage
✅ Automates integrity logic❌ Hidden logic → harder to debug
✅ Keeps schema DRY❌ Can affect performance
✅ Useful for audits or sync❌ Not portable across DB engines

🧠 Summary

ConceptTrigger
What is it?Code that runs automatically on events
When?INSERT, UPDATE, DELETE
Why?Automate logic, enforce rules, audit
How?CREATE TRIGGER ... with custom logic
This entry was posted in Без рубрики. Bookmark the permalink.

Leave a Reply

Your email address will not be published.