Added an optimization for flattening queries