Refactoring sql stuff