SQL optimizations
fixes