Optimize the query