refactor query construction