title: How to synchronize TRIGGER execution for UPDATE of certain row?
body: <p>Lets get straight to the point. I have application that concurrently inserts new rows into relational database. On the endpoint of one Many-To-One relation I want to track child rows count with triggers for later usage. Unfortunetly I am getting DEADLOCKS in case when new data contains reference to same parent row (<code>applicant</code>). How to aquire concurrent lock for updated row? Here are my triggers:</p>
  
  <pre>
  DROP TRIGGER IF EXISTS `incrementEntryCountTrigger`;
  
  DELIMITER $$
  CREATE TRIGGER `incrementEntryCountTrigger` AFTER INSERT ON trademark FOR EACH ROW
  BEGIN
      UPDATE applicant
          SET entryCount=entryCount+1,
              entryCountChanged=1
          WHERE applicant.id=NEW.applicant_id;
  END$$
  DELIMITER ;
  
  
  
  DROP TRIGGER IF EXISTS `decrementEntryCountTrigger`;
  DELIMITER $$
  CREATE TRIGGER `decrementEntryCountTrigger` AFTER DELETE ON trademark FOR EACH ROW
      BEGIN
          UPDATE applicant
              SET entryCount=entryCount-1,
                  entryCountChanged=1
              WHERE applicant.id=OLD.applicant_id;
      END$$
      DELIMITER ;
  </pre>
  
  <p>Structure of <code>trademark</code> table</p>
  
  <pre>
  CREATE TABLE `trademark` (
    `id` int(11) NOT NULL AUTO_INCREMENT,
    `applicationDate` datetime DEFAULT NULL,
    `applicationNumber` varchar(255) DEFAULT NULL,
    `class` varchar(255) DEFAULT NULL,
    `creationDate` datetime DEFAULT NULL,
    `deleted` tinyint(4) DEFAULT NULL,
    `imageDownloaded` tinyint(4) DEFAULT NULL,
    `modified` datetime DEFAULT NULL,
    `name` varchar(255) DEFAULT NULL,
    `registrationDate` datetime DEFAULT NULL,
    `registrationNumber` varchar(255) DEFAULT NULL,
    `trademarkType` varchar(255) DEFAULT NULL,
    `applicant_id` int(11) DEFAULT NULL,
    `country_id` int(11) DEFAULT NULL,
    `service_id` int(11) DEFAULT NULL,
    PRIMARY KEY (`id`),
    UNIQUE KEY `uniqueApplicationPerServiceContraint` (`applicationNumber`,`service_id`),
    KEY `FK_sv7x27shne6cro3hch7who6vr` (`applicant_id`),
    KEY `FK_4fuuxl1srjn7svpby7rd6j1er` (`country_id`),
    KEY `FK_1g62lp3kjl15f789m7netvlsk` (`service_id`),
    CONSTRAINT `FK_1g62lp3kjl15f789m7netvlsk` FOREIGN KEY (`service_id`) REFERENCES `service` (`id`),
    CONSTRAINT `FK_4fuuxl1srjn7svpby7rd6j1er` FOREIGN KEY (`country_id`) REFERENCES `country` (`id`),
    CONSTRAINT `FK_sv7x27shne6cro3hch7who6vr` FOREIGN KEY (`applicant_id`) REFERENCES `applicant` (`id`)
  ) ENGINE=InnoDB AUTO_INCREMENT=2101 DEFAULT CHARSET=utf8
  </pre>