protected static function get_enrolled_sql_on_courses_with_capability($capability) {
        // Get all courses where user have the capability.
        $courses = get_user_capability_course($capability, null, true,
                implode(',', array_values(context_helper::get_preload_record_columns('ctx'))));
        if (!$courses) {
            return [null, null];
        }

        // Loop around all courses getting the SQL for enrolled users. Note: This query could
        // probably be more efficient (without the union) if get_enrolled_sql had a way to
        // pass an array of courseids, but it doesn't.
        $unionsql = '';
        $unionparams = [];
        foreach ($courses as $course) {
            // Get SQL to list user ids enrolled in this course.
            \context_helper::preload_from_record($course);
            list ($sql, $params) = get_enrolled_sql(\context_course::instance($course->id));

            // Combine to a big union query.
            if ($unionsql) {
                $unionsql .= ' UNION ';
            }
            $unionsql .= $sql;
            $unionparams = array_merge($unionparams, $params);
        }

        return [$unionsql, $unionparams];
    }