Added more SQL optimizations where possible.