finished sql refactor