Consider a table users with columns id (auto-increment), username, and created_at. A BEFORE INSERT trigger sets created_at to the current date if not provided.
What will be the created_at value after running this insert?
CREATE TABLE users (id INT AUTO_INCREMENT PRIMARY KEY, username VARCHAR(50), created_at DATE); DELIMITER $$ CREATE TRIGGER before_insert_users BEFORE INSERT ON users FOR EACH ROW BEGIN IF NEW.created_at IS NULL THEN SET NEW.created_at = CURDATE(); END IF; END$$ DELIMITER ; INSERT INTO users (username) VALUES ('alice'); SELECT created_at FROM users WHERE username = 'alice';
Think about what the trigger does before the row is inserted.
The BEFORE INSERT trigger checks if created_at is NULL and sets it to the current date. Since no value was provided, it sets created_at to today's date.
What is the main purpose of a BEFORE INSERT trigger in a database?
Think about when the trigger runs in relation to the insert operation.
BEFORE INSERT triggers run before data is inserted, allowing modification or validation of the data before it is saved.
Which option contains a syntax error in the BEFORE INSERT trigger definition?
CREATE TABLE products (id INT PRIMARY KEY, price DECIMAL(10,2));
Remember how to refer to the new row's columns inside triggers.
Inside triggers, you must use NEW.column_name to refer to the new row's values. Option D uses price without NEW., causing a syntax error.
Given the following trigger, why does inserting a row cause an error?
CREATE TABLE orders (id INT PRIMARY KEY, quantity INT); DELIMITER $$ CREATE TRIGGER trg_before_insert_orders BEFORE INSERT ON orders FOR EACH ROW BEGIN IF NEW.quantity < 0 THEN SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = 'Quantity cannot be negative'; END IF; END$$ DELIMITER ; INSERT INTO orders (id, quantity) VALUES (1, -5);
Look at the SIGNAL statement inside the trigger.
The trigger checks if quantity is negative and raises a custom error using SIGNAL, preventing the insert.
You have a BEFORE INSERT trigger that sets a timestamp column to the current time if NULL. You notice bulk inserts are slow. Which optimization can improve performance?
Think about how to avoid running code for every row during insert.
Using a DEFAULT value for the timestamp column lets the database set it automatically without running trigger code, improving bulk insert speed.