Refactor to reduce duplication of queries