refactored query code