I have a table with three columns; the first column contains IDs and the other two columns contain dates (where at most one is null, but I don't think this should affect anything). How would I go about ordering the IDs based on which date is larger? I've tried
ORDER BY CASE
WHEN date1 > date2 THEN date1
ELSE date2
END
but this didn't work. Can anyone help me? Also, all of the similar problems that I've seen others post have it so that the query sorts the results based on the first column, and then if the first column is null, the second column. Would I first have to define every single null value? I'm creating this table by a full outer join, so that would be an entirely different question to ask, so hopefully it can be done with null values.
I believe your problem is related to the comparison failing when either column is NULL. So, you probably need:
ORDER BY CASE
WHEN date1 IS NULL THEN date2
WHEN date2 IS NULL THEN date1
WHEN date1 > date2 THEN date1
ELSE date2
END
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With