Junior — Middle
Can you explain what the term 'trigger' means in the context of databases and how it is used?
sobes.tech AI
Answer from AI
In databases, a trigger is a special object that automatically performs a specified set of actions (such as SQL queries or procedures) in response to certain events, such as inserting (INSERT), updating (UPDATE), or deleting (DELETE) data in a table.
Triggers are used for:
- Automatic validation or modification of data upon changes.
- Maintaining change logs.
- Ensuring data integrity.
- Implementing business logic at the database level.
An example of a simple SQL trigger that records the change date when a new record is inserted into the "orders" table:
CREATE TRIGGER trg_set_order_date
BEFORE INSERT ON orders
FOR EACH ROW
BEGIN
SET NEW.order_date = NOW();
END;