refactor replace conditional with query