I have a sql table with several columns, two of which are the start and the finish time of an event. The query pulls rows from the table and sorts it by the start time - the finish time is irrelevant for the sorting. However in rare cases, there might be an entry without a start time. In this case I want the query to handle it like the start time would be the same value as the finish time, so it isn't placed at the beginning of the table:
Example Data:
| Start | Finish |
| -------- | -------- |
| 15:31:00 | 15:39:00 | 1st Event
| 00:00:00 | 15:36:00 | 2nd Event
| 15:37:00 | 15:42:00 | 3rd Event
The query looks like this:
SELECT FROM table ORDER BY Start ASC
Obviously what happens now is, that the 2nd Event (with an empty start time) will end up on top or at the bottom of the list, depending on ASC or DESC argument.
What I want is it to be put in the list as if the start time would also be 15:36:00. As if there was a function to say
If Start is '00:00:00'
then Start = Finish
Doing a COALESCE like
SELECT FROM table ORDER BY COALESCE(Start, Finish)
is not an option, because events have different lengths and in this example, the finish time of event 2 is before the finish time of event 1 so it would still end up at the beginning of the list.
Any way to do this directly within the SQL Query?
Best regards!
You may order using a CASE
expression:
SELECT *
FROM yourTable
ORDER BY CASE WHEN Start <> '00:00:00' THEN Start ELSE `End` END;
Note that END
is a keyword in MySQL and so you should avoid naming your columns using it.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.