Optimize methods by rewriting subqueries