refactoring query, sorting