Optimize DB check

For some reason one of the DB checks became really slow while I was working on #2579, this PR rewrites that check in a much more efficient form.