DavidTonarini
DavidTonarini

Reputation: 951

mySql ORDER BY with some elements first?

I have a mySql database and I am performing a LEFT JOIN search combining two table courses and sessions.

This is the query stripped to minimun

SELECT 
`course_title`,`session_start_date` 
FROM `courses` 
  LEFT JOIN `sessions` ON `courses`.`course_id` = `sessions`.`course_id`

Not all elements of the courses table have a currently available session. Now, the problem is that I want to show first the courses that have a currently open session, in an ascendant order, and at the end those courses that have no session (session_start_date = NULL)

Therefore I cannot simply use

ORDER BY `session_start_date` ASC

since this would show first the elements without a session

Now, I can figure out a couple of ways of handling this programmatically with later php, or I could use two separate query selecting first only those courses that have a open session, and then the rest.

But is there a smart way to perform this directly by ordering the query in some way I am not aware of?

So, the idea would be something like

ORDER BY 
(FIRST `session_start_date` ASC where `session_start_date` is not null  
THEN anything else)

Is there any construct that would allow something like this?

Upvotes: 0

Views: 39

Answers (1)

user1932079
user1932079

Reputation:

This clause should do it

ORDER BY `session_start_date` IS NULL, `session_start_date` ASC

Upvotes: 1

Related Questions