Given a trigger that logs inserts into employees table, what will be the content of audit_log after inserting a new employee?
CREATE TABLE employees (id INT PRIMARY KEY, name VARCHAR(50)); CREATE TABLE audit_log (action VARCHAR(10), emp_id INT, emp_name VARCHAR(50)); CREATE TRIGGER log_employee_insert AFTER INSERT ON employees FOR EACH ROW INSERT INTO audit_log VALUES ('INSERT', NEW.id, NEW.name); INSERT INTO employees VALUES (1, 'Alice'); SELECT * FROM audit_log;
Remember that NEW keyword in triggers refers to the inserted row.
The trigger fires after an insert on employees. It inserts a row into audit_log with the action 'INSERT' and the new employee's id and name. So the audit_log table will have one row showing the inserted employee.
Choose the correct SQL trigger that logs deletions from employees into audit_log with action 'DELETE'.
For DELETE triggers, OLD holds the row being deleted.
After DELETE triggers run after the row is deleted, and OLD contains the deleted row's data. Using NEW in DELETE triggers is invalid. The correct syntax uses AFTER DELETE and OLD.
Given this trigger, why does it fail to log the updated data in audit_log after updating employees?
CREATE TRIGGER log_employee_update AFTER UPDATE ON employees FOR EACH ROW INSERT INTO audit_log VALUES ('UPDATE', OLD.id, OLD.name);
Consider which values reflect the updated data after an update.
After an update, OLD holds the old data before update, NEW holds the new data. To log the updated values, the trigger should insert NEW values, not OLD. Using OLD logs old data, which might be confusing or appear as no change.
Put these steps in the correct order to create a trigger that logs both INSERT and UPDATE actions on employees.
Think about what you need before creating triggers and testing.
First create the audit_log table to store logs. Then write the trigger function that inserts logs. Next create the trigger that calls this function on insert or update. Finally, test the setup.
In a high-traffic database, which method best prevents audit logging triggers from slowing down main data changes?
Consider how to avoid slowing down the main transaction.
Writing audit logs synchronously inside triggers can slow down transactions. Disabling triggers or batching once a day risks losing audit detail or timeliness. Using asynchronous logging with a queue table lets main transactions finish quickly, and audit logs are processed separately.