Refactor query for inheritance