refactored database logic in a single query