Using a before insert trigger to place a hard limit on the number of rows in a table
This code creates a before trigger on the users table limiting the number of rows to 5,000:
- DELIMITER $$
- create trigger before_users_insert
- before insert
- on users for each row
- begin
- if (select count(user_id) from users) >= (select 5000) then
- SIGNAL SQLSTATE '45000'
- SET MESSAGE_TEXT = 'Maximum users reached';
- end if;
- end$$
- DELIMITER ;