Query refactoring