Optimizing queries for cost savings and better performance