Refactored querying the database a bit