Bug fixes and SQL optimization