change query generation to improve performance