SQL Basics

Chapter 22 - Using Triggers

  • Triggers are SQL operations executed automatically in response to a particular event
  • These events are:
    • DELETE
    • INSERT
    • UPDATE
  • Trigger syntax varies by SQL dialect. In MySQL, BEGIN ... END is needed for a trigger containing several statements; it is optional for a single statement.
  • Supported trigger targets vary by dialect. MySQL triggers belong to permanent tables and cannot be attached to a view.

Examples of useful triggers include:

  • When a customer is added, check that a phone number is provided and the postal code meets the requirements
  • When a product is ordered, reduce stock by the quantity ordered
  • Before a row is deleted, copy it into an archive table