query optimization + refactoring