Fix database concurrency issue

This seems to solve a concurrency issue where every so often the database
will acquire a lock on thousands of row because the limit is applied only
afterwards.