refactor sql