refactoring query logic.