You can use stored procedure instead of regular INSERT statement. The stored procedure will first add the row based on the input parameters and then delete old rows if required. Please see below example. You will probably have to adjust the input parameters for limitedInsert
procedure based on your table's columns.
My example table schema
CREATE TABLE IF NOT EXISTS `test` (
`id` int(1) NOT NULL AUTO_INCREMENT,
`timestamp` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`value` tinyint(4) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
Procedure
DELIMITER //
CREATE DEFINER=`root`@`%` PROCEDURE `limitedInsert`(
IN `parameter_1` INT
)
BEGIN
DECLARE rowsNumber INT;
DECLARE idToRemove INT;
insert into test(value) values(parameter_1);
select count(*) into rowsNumber from test;
if rowsNumber > 30 then
select id into idToRemove from test order by timestamp asc limit 1;
delete from test where id = idToRemove;
end if;
END//
DELIMITER ;
Insert data using stored procedure
call limitedInsert(2);