2

I have a table with 2 date columns:

create_date and modify_date.
create_date is always set and modify_date sometimes.

Now I want to order my query by both of them with the same priority.

If I do this:

order by create_date desc, modify_date desc

I first get all rows sorted by create_date and then by modify_date but I want the rows sorted by both in the same priority. I need this:

create_date  |  modify_date
2011-12-31   |  -
2011-12-01   |  2011-12-30
2011-12-29   |  -
juergen d
  • 201,996
  • 37
  • 293
  • 362

3 Answers3

5
select *
from yourtable
order by coalesce(modify_date, create_date) desc
Andrew
  • 26,629
  • 5
  • 63
  • 86
3

Use ISNULL() to order by modify_date, and if modify_date is NULL, it will use the create_date value:

ORDER BY ISNULL(modify_date, create_date) DESC
Curtis
  • 101,612
  • 66
  • 270
  • 352
0

The column naming implies that modify_date is either not set or higher then creation date, so the other answers will work. If not, you may use a user defined function as described here (adjust to use Dates instead of int). Then use

ORDER BY dbo.HigherArgument(create_date, modify_date) DESC
Community
  • 1
  • 1
okrumnow
  • 2,346
  • 23
  • 39