History query refactor