Improved efficiency of SQL queries in loops