Revert "Revert "Refactored querying the database a bit""

This reverts commit 26f698021cca03122c1503c7fbad5f6dde4533d4.