cleaned up query logic