Alex Rivera | Logout

Setting Up MySQL Triggers

Asked 2008-09-06T11:24:53.000
10

I've been hearing about triggers, and I have a few questions.
What are triggers?
How do I set them up?
Are there any precautions, aside from typical SQL stuff, that should be taken?

Edit
Report

1 Answer

15

Triggers allow you to perform a function in the database as certain events happen (eg, an insert into a table).

I can't comment on mysql specifically.

Precaution: Triggers can be very alluring, when you first start using them they seem like a magic bullet to all kinds of problems. But, they make "magic" stuff happen, if you don't know the database inside out, it can seem like really strange things happen (such as inserts into other tables, input data changing, etc). Before implementing things as a trigger I'd seriously consider instead enforcing the use of an API around the schema (preferably in the database, but outside if you can't).

Some things I'd still use triggers for

  • Keeping track of "date_created" and "date_last_edited" fields
  • Inserting "ID"'s (in oracle, where there is no auto id field)
  • Keeping change history

Things you wouldn't want to use triggers for

  • business rules/logic
  • anything which connects outside of the database (eg a webservice call)
  • Access control
  • Anything which isn't transactional ( anything you do in the trigger MUST be able to rollback with the transaction )
answered 2008-09-06T11:35:21.883

Your Answer