refactor complex sql conditions