improved query code