Refactor sql