Modularize SQL optimization
Fixed wrong count
Added type hint