Refactoring query