Complete the code to create a trigger that automatically updates the 'last_modified' column when a row is updated.
CREATE TRIGGER update_timestamp BEFORE UPDATE ON employees FOR EACH ROW SET NEW.last_modified = [1];The NOW() function returns the current date and time in SQL, which is used here to update the 'last_modified' column automatically.
Complete the code to create a trigger that prevents deletion of rows from the 'orders' table.
CREATE TRIGGER prevent_delete BEFORE DELETE ON orders FOR EACH ROW BEGIN SIGNAL SQLSTATE [1] SET MESSAGE_TEXT = 'Deletion not allowed'; END;
The SQLSTATE code '45000' is a generic user-defined exception used to signal an error in triggers.
Fix the error in the trigger code that should log insertions into the 'audit_log' table.
CREATE TRIGGER log_insert AFTER INSERT ON products FOR EACH ROW INSERT INTO audit_log (product_id, action) VALUES ([1], 'INSERT');
In an AFTER INSERT trigger, the NEW keyword refers to the newly inserted row. So, NEW.product_id correctly accesses the inserted product's ID.
Fill both blanks to create a trigger that updates stock quantity after a sale is inserted.
CREATE TRIGGER update_stock AFTER INSERT ON sales FOR EACH ROW BEGIN UPDATE products SET stock = stock [1] NEW.quantity WHERE product_id = [2]; END;
The trigger subtracts the sold quantity from the stock, so the operator is -. The product to update is identified by NEW.product_id from the inserted sale.
Fill all three blanks to create a trigger that prevents negative stock after an update.
CREATE TRIGGER check_stock BEFORE UPDATE ON products FOR EACH ROW BEGIN IF NEW.stock [1] [2] THEN SIGNAL SQLSTATE [3] SET MESSAGE_TEXT = 'Stock cannot be negative'; END IF; END;
The trigger checks if the new stock is less than zero (< 0) and raises an error with SQLSTATE '45000' if true.