code cleanup, SQL refactoring