Improved query generation