snippetsqlMinor
How to use a conditional ORDER BY in MySQL?
Viewed 0 times
orderconditionalmysqlhowuse
Problem
I have the table courses where we have some fields and also the field
The teacher uploads the course and this date is stored in the
Now I need to retrieve all courses from a specific teacher and then order the list by date: If the course is flagged
This is what I have so far but it is not working:
Any idea how to solve this?
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
ORDER BY
CASE favorited WHEN 1 THEN favoritedDate, dateUpload
else dateUpload
END
DESC
;Any idea how to solve this?
Solution
As Lennart explains, a
If the
CASE expression in MySQL can only produce a single value, not two or more. I think this would suite your problem:ORDER BY
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):ORDER BY
(favoritedDate IS NULL),
favoritedDate,
dateUpload DESC ;Code Snippets
ORDER BY
CASE WHEN favorited = 1 THEN 0 ELSE 1 END,
CASE WHEN favorited = 1 THEN favoritedDate END,
dateUpload DESC ;ORDER BY
(favoritedDate IS NULL),
favoritedDate,
dateUpload DESC ;Context
StackExchange Database Administrators Q#201719, answer score: 6
Revisions (0)
No revisions yet.