Updated query logic