Introduction
AFTER INSERT triggers run automatically after new data is added to a table. They help you do extra tasks right after inserting data.
AFTER INSERT triggers run automatically after new data is added to a table. They help you do extra tasks right after inserting data.
CREATE TRIGGER trigger_name AFTER INSERT ON table_name FOR EACH ROW BEGIN -- statements to execute END;
CREATE TRIGGER log_new_user AFTER INSERT ON users FOR EACH ROW BEGIN INSERT INTO user_log(user_id, action) VALUES (NEW.id, 'inserted'); END;
CREATE TRIGGER update_stats_after_insert AFTER INSERT ON orders FOR EACH ROW BEGIN UPDATE stats SET total_orders = total_orders + 1; END;
This example creates a products table and a product_log table. The trigger adds a log entry every time a new product is inserted.
CREATE TABLE products ( id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(50), price DECIMAL(10,2) ); CREATE TABLE product_log ( log_id INT AUTO_INCREMENT PRIMARY KEY, product_id INT, action VARCHAR(20), log_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP ); DELIMITER $$ CREATE TRIGGER after_product_insert AFTER INSERT ON products FOR EACH ROW BEGIN INSERT INTO product_log(product_id, action) VALUES (NEW.id, 'inserted'); END$$ DELIMITER ; INSERT INTO products(name, price) VALUES ('Pen', 1.20); SELECT * FROM product_log;
Remember to change the delimiter when creating triggers in MySQL to avoid errors.
AFTER INSERT triggers cannot modify the row being inserted, only act after insertion.
AFTER INSERT triggers run after new rows are added.
They help automate tasks like logging or updating related data.
Use NEW to access inserted row data inside the trigger.
AFTER INSERT trigger do in MySQL?AFTER INSERT trigger runs after a new row is successfully inserted into a table.AFTER INSERT.CREATE TRIGGER trg AFTER INSERT ON table_name FOR EACH ROW BEGIN ... END;.CREATE TABLE users (id INT, name VARCHAR(20));
CREATE TABLE logs (msg VARCHAR(50));
DELIMITER $$
CREATE TRIGGER after_user_insert AFTER INSERT ON users
FOR EACH ROW BEGIN
INSERT INTO logs VALUES (CONCAT('User ', NEW.name, ' added'));
END$$
DELIMITER ;
INSERT INTO users VALUES (1, 'Alice');
SELECT * FROM logs;NEW.name after a user is added.CREATE TRIGGER trg AFTER INSERT ON users
FOR EACH ROW
INSERT INTO logs VALUES ('New user added');
INSERT INTO logs VALUES ('Trigger fired');NEW.amount gives the inserted sale amount to add to the summary.Pass the test and this pattern moves unknown