While creating a blog, I’ve decided that using triggers would be a convenient way to add and remove posts while maintaining a counter within the category table. Here are my two triggers for incrementing and decrementing the counter in my categories table:
delimiter |
CREATE TRIGGER increment_category_count AFTER INSERT ON posts
FOR EACH ROW BEGIN
UPDATE categories SET count = count + 1 WHERE id = NEW.category_id;
END;
|
delimiter ;
delimiter |
CREATE TRIGGER decrement_category_count AFTER DELETE on posts
FOR EACH ROW BEGIN
UPDATE categories SET count = count - 1 WHERE id = OLD.category_id;
END;
|
delimiter ;
I’m concerned that if something goes wrong while inserting or deleting a post, then my counters would become inaccurate. Is there something in MySQL that would enable me to do a rollback in a trigger if something goes wrong?
Any change that is done in a trigger will be rolled back (or committed) with the transaction that fired the trigger (assuming you do use InnoDB for your tables).