Query optimizations and bug fixes