I have the table courses where we have some fields and also the field course(string), favorited(bool), favoritedDate(dateTime), dateUpload.

The teacher uploads the course and this date is stored in the dateUpload field. If the teacher flag this course as favorite this information is a number 1 in the field favorited and the date it was flagged is stored in the field favoritedDate.

Now I need to retrieve all courses from a specific teacher and then order the list by date: If the course is flagged favorited=1 should ordered by favoritedDate,dateUpload desc, if favorited=0 should be ordered only by dateUpload desc.

This is what I have so far but it is not working:

SELECT * from courses where teacherId = 23 
  CASE favorited WHEN 1 THEN favoritedDate, dateUpload
    else dateUpload

Any idea how to solve this?


2 Answers 2


A case expression returns an atomic value so you can't return:

favoritedDate, dateUpload

I think this will do what you want:

    CASE favorited WHEN 1 THEN favoritedDate 
                          ELSE dateUpload 
    END DESC, dateUpload

As Lennart explains, a CASE expression in MySQL can only produce a single value, not two or more. I think this would suite your problem:

    CASE WHEN favorited = 1 THEN 0 ELSE 1 END,
    CASE WHEN favorited = 1 THEN favoritedDate END,
    dateUpload DESC ;

If the favoritedDate values are NULL when the item is not "favourited", then you really don't need the favorited column at all. The information is stored in favoritedDate: If it's null, it's not a favourite. If it's not null, it is. The ORDER BY in that case (not much simpler, due to MySQL sorting nulls before not null values):

    (favoritedDate IS NULL),
    dateUpload DESC ;

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.