Put SQL query out of the for loop