Refactor query logic