move query creation out of loop again as it was not the issue