user468311
user468311

Reputation:

How do I order results based on two columns conditionally

I have two columns: created_at and updated_at. I wan't to order results of a query by date, if updated_at is present in a row, then use this column for ordering, otherwise use created_at. Is this possible to do in one query?

Upvotes: 0

Views: 49

Answers (2)

TJB
TJB

Reputation: 877

SELECT
created_at
,updated_at
,COALESCE(updated_at,created_at) AS MostRecentDate
FROM [Table]
ORDER BY MostRecentDate ASC

Upvotes: 1

Shushil Bohara
Shushil Bohara

Reputation: 5656

you can use case as following

ORDER BY CASE WHEN updated_at IS NOT NULL THEN updated_at ELSE created_at END

Upvotes: 0

Related Questions