refactor SQL queries for optimization