SQL and performance optimizations for large data sets, fixed #981.