Error: Can't update table 'tableName' in stored function/trigger because it is already used by statement which invoked this stored function/trigger.
CREATE DEFINER=`root`@`localhost` TRIGGER `triggerName` BEFORE INSERT ON `tableName` FOR EACH ROW BEGIN
DECLARE current_count INT;
DECLARE oldest_data INT;
SELECT count(*) INTO current_count FROM tableName;
IF (current_count >= 500) THEN
SELECT min(ID) INTO oldest_data FROM tableName;
DELETE FROM tableName WHERE ID=oldest_data;
END IF;
END
The above trigger makes sure that there are only 500 records(latest) in a table. When new data comes in old data has to be deleted. I am unable to achieve this simple use case using triggers because of the above mentioned error.
People talk deadlocks but I am using innodb engine with MySQL 8. I read that innodb engine imposes row level lock hence deleting 'X' row before inserting 'Y' row should not cause any recursive triggers or waiting for locks. What am I missing????????