SQL Before Insert Trigger

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:

                
  1. DELIMITER $$
  2. create trigger before_users_insert
  3. before insert
  4. on users for each row
  5. begin
  6. if (select count(user_id) from users) >= (select 5000) then
  7. SIGNAL SQLSTATE '45000'
  8. SET MESSAGE_TEXT = 'Maximum users reached';
  9. end if;
  10. end$$
  11. DELIMITER ;