code cleanup - refactor SQL