simplified and optimized the SQL queries