Junior — Middle
Explain what a trigger is in SQL and how it is used to automate operations in a database.
sobes.tech AI
Answer from AI
A trigger in SQL is a special database object that automatically executes a specified set of actions (such as SQL queries) when certain events (INSERT, UPDATE, DELETE) occur on a table.
Triggers are used to automate tasks such as:
- Data integrity checks and maintenance
- Logging changes
- Automatic updating of related tables
An example of a trigger that automatically updates the order count in the customers table when a record is inserted into the orders table:
CREATE TRIGGER UpdateOrderCount
AFTER INSERT ON orders
FOR EACH ROW
BEGIN
UPDATE customers SET order_count = order_count + 1 WHERE id = NEW.customer_id;
END;
Thus, triggers help automate business logic at the database level.