diff --git a/lib/moodlelib.php b/lib/moodlelib.php
index <HASH>..<HASH> 100644
--- a/lib/moodlelib.php
+++ b/lib/moodlelib.php
@@ -4015,6 +4015,12 @@ function remove_course_contents($courseid, $showfeedback=true) {
         }
     }
 
+/// Remove all data from gradebook - this needs to be done before course modules
+/// because while deleting this information, the system may need to reference
+/// the course modules that own the grades.
+    remove_course_grades($courseid, $showfeedback);
+    remove_grade_letters($context, $showfeedback);
+
 /// Delete every instance of every module
 
     if ($allmods = $DB->get_records('modules') ) {
@@ -4088,10 +4094,6 @@ function remove_course_contents($courseid, $showfeedback=true) {
 /// Delete questions and question categories
     question_delete_course($course, $showfeedback);
 
-/// Remove all data from gradebook
-    remove_course_grades($courseid, $showfeedback);
-    remove_grade_letters($context, $showfeedback);
-
 /// Delete course tags
     require_once($CFG->dirroot.'/tag/coursetagslib.php');
     coursetag_delete_course_tags($course->id, $showfeedback);
course MDL-<I>: Fixed order of deleting entire course to delete grades before course-modules, avoiding dependency problem