Index: course/report/stats/lib.php
===================================================================
RCS file: /cvsroot/moodle/moodle/course/report/stats/lib.php,v
retrieving revision 1.11
diff -u -r1.11 lib.php
--- course/report/stats/lib.php	29 Nov 2008 14:22:14 -0000	1.11
+++ course/report/stats/lib.php	13 Jul 2009 06:26:02 -0000
@@ -32,13 +32,13 @@
         global $CFG, $DB;
         
         if ($mode == STATS_MODE_DETAILED) {
-            $earliestday = $DB->get_field_sql('SELECT timeend FROM {stats_user_daily} ORDER BY timeend');
-            $earliestweek = $DB->get_field_sql('SELECT timeend FROM {stats_user_weekly} ORDER BY timeend');
-            $earliestmonth = $DB->get_field_sql('SELECT timeend FROM {stats_user_monthly} ORDER BY timeend');
+            $earliestday = $DB->get_field_sql('SELECT MIN(timeend) FROM {stats_user_daily}');
+            $earliestweek = $DB->get_field_sql('SELECT MIN(timeend) FROM {stats_user_weekly}');
+            $earliestmonth = $DB->get_field_sql('SELECT MIN(timeend) FROM {stats_user_monthly}');
         } else {
-            $earliestday = $DB->get_field_sql('SELECT timeend FROM {stats_daily} ORDER BY timeend');
-            $earliestweek = $DB->get_field_sql('SELECT timeend FROM {stats_weekly} ORDER BY timeend');
-            $earliestmonth = $DB->get_field_sql('SELECT timeend FROM {stats_monthly} ORDER BY timeend');
+            $earliestday = $DB->get_field_sql('SELECT MIN(timeend) FROM {stats_daily}');
+            $earliestweek = $DB->get_field_sql('SELECT MIN(timeend) FROM {stats_weekly}');
+            $earliestmonth = $DB->get_field_sql('SELECT MIN(timeend) FROM {stats_monthly}');
         }
 
 
Index: lib/statslib.php
===================================================================
RCS file: /cvsroot/moodle/moodle/lib/statslib.php,v
retrieving revision 1.76
diff -u -r1.76 statslib.php
--- lib/statslib.php	26 May 2009 03:57:03 -0000	1.76
+++ lib/statslib.php	13 Jul 2009 06:26:06 -0000
@@ -899,13 +899,13 @@
     global $CFG, $DB;
 
     // are there any data in stats table? Should not be...
-    if ($timeend = $DB->get_field_sql('SELECT timeend FROM {stats_'.$str.'} ORDER BY timeend DESC')) {
+    if ($timeend = $DB->get_field_sql('SELECT MAX(timeend) FROM {stats_'.$str.'}')) {
         return $timeend;
     }
     // decide what to do based on our config setting (either all or none or a timestamp)
     switch ($CFG->statsfirstrun) {
         case 'all':
-            if ($firstlog = $DB->get_field_sql('SELECT time FROM {log} ORDER BY time ASC')) {
+            if ($firstlog = $DB->get_field_sql('SELECT MIN(time) FROM {log}')) {
                 return $firstlog;
             }
         default:
