Refactored database querying