DELIMITER $$ CREATE OR REPLACE DEFINER=`root`@`localhost` TRIGGER `vn`.`expeditionPallet_beforeInsert` BEFORE INSERT ON `expeditionPallet` FOR EACH ROW BEGIN DECLARE vNewPosition INT; SELECT MAX(position) + 1 INTO vNewPosition FROM vn.expeditionPallet WHERE truckFk = NEW.truckFk; SET NEW.position = IFNULL(vNewPosition,1); END$$ DELIMITER ;