Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL: how do I limit the number of records stored for a value of a column?

Tags:

mysql

Lets say I have a column of user ID's storing past login successes.

Now, I only want the most recent 20 login attempts, so Is there a way to specify the table to not store more than 20 records per user id?

like image 693
NullVoxPopuli Avatar asked Nov 25 '25 17:11

NullVoxPopuli


1 Answers

There are a few possible ways, one would be to use a Stored Procedure to insert the records. That way, the SP would check if there are more than 20 and drop old ones after inserting the new one. The drawback is that if you manually insert a row, it won't get dropped.

A trigger might work... Create an AFTER INSERT trigger that then deletes the older logins > 20...

like image 81
ircmaxell Avatar answered Nov 28 '25 07:11

ircmaxell