Cherry-picked custom sql refactoring