tags:

views:

1074

answers:

4

Here's the query (the largest table has about 40,000 rows)

SELECT
  Course.CourseID,
  Course.Description,
  UserCourse.UserID,
  UserCourse.TimeAllowed,
  UserCourse.CreatedOn,
  UserCourse.PassedOn,
  UserCourse.IssuedOn,
  C.LessonCnt
FROM
  UserCourse
INNER JOIN
  Course
USING(CourseID)
INNER JOIN
(
  SELECT CourseID, COUNT(*) AS LessonCnt FROM CourseSection GROUP BY CourseID
) C
USING(CourseID)
WHERE 
  UserCourse.UserID = 8810

If I run this, it executes very quickly (.05 seconds roughly). It returns 13 rows.

When I add an ORDER BY clause at the end of the query (ordering by any column) the query takes about 10 seconds.

I'm using this database in production now, and everything is working fine. All my other queries are speedy.

Any ideas of what it could be? I ran the query in MySQL's Query Browser, and from the command line. Both places it was dead slow with the ORDER BY.

EDIT: Tolgahan ALBAYRAK solution works, but can anyone explain why it works?

+3  A: 

Is the column you're ordering by indexed?

Indexing drastically speeds up ordering and filtering.

ceejayoz
the op mentioned using any column in the order by reduces performance
northpole
Any column, including the indexed columns, make it run slow.
+1  A: 

maybe this helps:

SELECT * FROM (    
     SELECT
      Course.CourseID,
      Course.Description,
      UserCourse.UserID,
      UserCourse.TimeAllowed,
      UserCourse.CreatedOn,
      UserCourse.PassedOn,
      UserCourse.IssuedOn,
      C.LessonCnt
    FROM
      UserCourse
    INNER JOIN
      Course
    USING(CourseID)
    INNER JOIN
    (
      SELECT CourseID, COUNT(*) AS LessonCnt FROM CourseSection GROUP BY CourseID
    ) C
    USING(CourseID)
    WHERE 
      UserCourse.UserID = 8810
) ORDER BY CourseID
Tolgahan Albayrak
Huh, that works (makes it execute fast). Do you know why though? I've never had to do that before.
40k isnt that many records; typically have to deal with millions soyour milage may vary but this may help improve the performance further on this as the joins will be done on a reduced dataset....FROM (Select * from UserCourseWhere UserID = 8810) UserCourse
u07ch
@Dude -- the slow down comes because it is probably choosing to do the ordering before doing the join. Doing the order by in an outer query forces it to only order the selected items.
tvanfosson
tvanfosson, I always thought the ORDER BY was processed after the results were returned. I guess that isn't necessarily the case. I'll have to investigate a bit more. Thanks.
A: 

Have you updated the statistics on your database? I ran into something similar on mine where I had 2 identical queries where the only difference was a capital letter and one returned in 1/2 a second and the other took nearly 5 minutes. Updating the statistics resolved the issue

Fry
A: 

A similar question was asked before here.

It might help you as well. Basically it describes using composite indexes and how order by works.

northpole