fixing sql for loops