Refactor the query