← Lessons

quiz vs the machine

Gold1340

Databases

Database Triggers

Code the database runs automatically when rows change.

4 min read · core · beat Gold to climb

Automatic Reactions

A trigger is a piece of logic the database runs by itself when a defined event happens on a table, such as an INSERT, UPDATE, or DELETE. You never call it directly. The database fires it as part of the statement.

Timing and Scope

  • A BEFORE trigger runs before the change and can adjust or reject the row.
  • An AFTER trigger runs once the change is committed to the table.
  • A row level trigger fires once per affected row, while a statement level trigger fires once per statement.

Good Uses

  • Maintaining an audit log of who changed what.
  • Keeping a denormalized count or timestamp in sync.
  • Enforcing a rule too complex for a simple constraint.

The Risk

Triggers run hidden logic. Heavy work inside a trigger slows every write, and chains of triggers firing other triggers are hard to debug. Use them sparingly and document them clearly.

Key idea

A trigger runs database logic automatically on insert update or delete, which is powerful for auditing but hides work that can slow and complicate writes.

Check yourself

Answer to earn rating on the learn ladder.

1. When does a BEFORE trigger run?

2. What is a common drawback of triggers?