refactoring sql