What is a trigger, and how do you create one in MySQL?

A trigger is a block of SQL code that MySQL automatically executes in response to a specific data-changing event -- an INSERT, UPDATE, or DELETE -- on a given table. Triggers let you enforce rules or automate side effects without requiring every application to remember to implement that logic itself.

Key Points: • Triggers fire automatically, so they help maintain data integrity and enforce business rules consistently. • You choose the event (INSERT/UPDATE/DELETE), the timing (BEFORE or AFTER), and the table the trigger is attached to. • The FOR EACH ROW clause means the trigger body runs once per affected row. • Inside the trigger, NEW refers to the incoming row's values (for INSERT/UPDATE) and OLD refers to the previous values (for UPDATE/DELETE). • Overusing triggers can make application behavior harder to trace, since the logic runs outside the application code path.

Example: An e-commerce system wants every new order automatically logged for auditing; instead of remembering to write a log entry in every place orders get created, a trigger on the orders table handles it automatically after each insert.

Code Example:

CREATE TRIGGER log_order_insert
AFTER INSERT ON orders
FOR EACH ROW
BEGIN
    INSERT INTO order_logs (Order_ID, Action, Timestamp)
    VALUES (NEW.Order_ID, 'Order Placed', NOW());
END;

Interview Tip: A concise interview answer is:

"A trigger is code that MySQL runs automatically when a specified INSERT, UPDATE, or DELETE happens on a table, defined with an event, a timing of BEFORE or AFTER, and FOR EACH ROW to run once per affected row. I'd use one, for example, to automatically log every new order into an audit table without relying on every code path to remember to do it manually."