3

Below is my query. I am not sure what cause the Not A group by expression error. Any help is much appreciated. =)

SELECT c.courseID, c.courseName, AVG(a.Mark) as Average_Mark
FROM course c, assessment a
WHERE c.courseID = a.courseID
Group by c.courseID, c.courseName
ORDER BY Mark DESC;

2 Answers 2

11

Try:

SELECT c.courseid,
       c.coursename,
       AVG(a.mark) AS Average_Mark
FROM   COURSE c
       INNER JOIN ASSESSMENT a
               ON c.courseid = a.courseid
GROUP  BY c.courseid,
          c.coursename
ORDER  BY 3 DESC; -- or ORDER BY Average_Mark DESC

As you aggregate several values of Mark in order to compute the average, it becomes impossible to sort on each value of Mark. You have to sort on the result of the computation, i.e. Average_Mark.


From a more general point of view, you are allowed to ORDER BY a non SELECTed column only if this column is part of the queried tables and if you don't use any GROUP BY or DISTINCT (unless you GROUP BY this non displayed column, then you can ORDER BY it).

The reason is simple: If you use GROUP BY or DISTINCT, several rows will be potentially displayed as one. Non displayed values in those "merged" rows can potentially be different from each other, making any ORDER BY impossible on those values.

Some DBMS (MySQL at least) behave differently, allowing ORDERing BY non displayed values, even with GROUP BY. But MySQL seems then to order by the first encountered value of non displayed value (see fiddle). So, better keep in mind that this should be avoided, to prevent unpredictible results.

EDIT: See the documentation about MySQL GROUP BY handling.

2
  • 1
    And why does it report that error as "not A GROUP BY expression"? Also, I'm currently getting this error in a queue without any order by.
    – masterxilo
    Mar 25, 2014 at 9:23
  • @masterxilo Ask another question describing your specific problem, the DBMS you're using, and the code your trying to execute. Mar 25, 2014 at 9:28
2

try

ORDER BY Average_Mark

instead of

ORDER BY Mark

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.