moved sql preparation around