Unlike stored procedures (which are simply stored SQL statements), triggers are tied to individual tables. A trigger associated with INSERT operations on the Orders table will be executed only when a row is inserted into the Orders table. Similarly, a trigger on INSERT and UPDATE operations on the Customers table will be executed only when those specific operations occur on that table.
Within triggers, your code has access to the following:
-
All new data in INSERT operations
-
All new data and old data in UPDATE operations
-
Deleted data in DELETE operations
Depending on the DBMS being used, triggers can be executed before or after a specified operation is performed.
The following are some common uses for triggers:
-
Ensuring data consistency— for example, converting all state names to uppercase during an INSERT or UPDATE operation
-
Performing actions on other tables based on changes to a table— for example, writing an audit trail record to a log table each time a row is updated or deleted
-
Performing additional validation and rolling back data if needed— for example, making sure a customer's available credit has not been exceeded and blocking the insertion if it has
-
Calculating computed column values or updating timestamps
As you probably expect by now, trigger creation syntax varies dramatically from one DBMS to another. Check your documentation for more details.