Search code examples
mysqlsqltriggersinnodb

MySQL: Syntax error when creating a trrigger


I am simply trying to insert a row into a parent table if the row doesn't exist in the parent table. I am getting "Statement incomplete. Expecting ';'" on the "INSERT INTO" line.

CREATE TRIGGER SellsInsertAlcoholAdd 
AFTER INSERT ON Sells
FOR EACH ROW
BEGIN
    IF(NEW.`Alcohol name` NOT IN
        (SELECT `Alcohol name` FROM Alcohol))
    THEN INSERT INTO Alcohol VALUES(NEW.`Alcohol Name`, NEW.`Type`, NEW.ABV, NEW.Manufacturer);
    END IF;
END

Solution

  • You are unnecessarily getting all the Alcohol name values, and then checking for the NEW value within it. Instead, you can change to using NOT EXISTS().

    You also need to change DELIMITER to something else (other than ;) at the beginning. At the end, redefine it back to ;

    DELIMITER $$
    CREATE TRIGGER SellsInsertAlcoholAdd 
    AFTER INSERT ON Sells
    FOR EACH ROW
    BEGIN
        IF NOT EXISTS(SELECT 1 FROM Alcohol 
                      WHERE `Alcohol name` = NEW.`Alcohol name`) THEN
          INSERT INTO Alcohol 
          VALUES(NEW.`Alcohol Name`, NEW.`Type`, NEW.ABV, NEW.Manufacturer);
        END IF;
    END $$
    DELIMITER ;