Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What can make a trigger to fail and what happens if it fails

I've created a trigger (never done it before).
My goal is:
WHEN one or more rows are INSERTED into the table 'userlite'
IF there are rows with 'IdLite' as in the new row inserted in the table 'litedetails'
THEN add a row to the table 'informations' for each row counted.

The new rows data fields will be:

IdUser -> from new row inserted into the table 'userlite'

IdLite -> it's the same on new row inserted into the table 'userlite' and into rows selected from the table 'litedetails'

IdEvent -> from rows selected

I used the code below to create the trigger

DELIMITER $$
CREATE TRIGGER after_newuserlite
AFTER INSERT ON userlite
FOR EACH ROW
BEGIN
IF (
    (
     SELECT COUNT(*) 
     FROM litedetails
     WHERE IdLite = NEW.IdLite
    ) > 0
   ) THEN
   INSERT INTO informations (IdUser, IdLite, IdEvent)
   SELECT NEW.IdUser AS IdUser, IdLite, IdEvent
   FROM litedetails
   WHERE IdLite = NEW.IdLite;
END IF;
END;
$$

I've tested it and all seems to work but I'm worried for my inexperience, so my questions are:
1) Is there anything that can cause my trigger to fail?
2) what happens if the trigger fails?
3) If the trigger fails the query who started the trigger will mantain its effects?

like image 746
genespos Avatar asked Oct 31 '25 17:10

genespos


1 Answers

As per comment: when using tables that support transactions, the triggers are then part of the statement. If a trigger fails, it causes the query that triggered it to fail as well, which causes a rollback. This applies to InnoDB and TokuDB storage engines.

For MyISAM, which isn't transactional engine, the trigger might error out but it won't cause a rollback (because it isn't supported by that storage engine).

Triggers can fail due to many reasons, just like regular queries can, but if they fail - you will receive an error message / notification that will let you act upon it (notify the user about failure, log the message, try again etc.).

like image 185
N.B. Avatar answered Nov 02 '25 13:11

N.B.