Also add checks for no ORDER BY or LIMIT:

    if (!queryPlan.getOrderBy().getOrderByExpressions().isEmpty() || queryPlan.getLimit() != null) {