Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Query between datetime columns

I have a table with two DateTime columns, _dateEntry and _dateUpdate.

I've to create a query and choose the right datetime column based on these conditions: take the most recent between _dateEntry and _dateUpdate. _dateUpdate might be null, so I wrote this condition

SELECT id, description, ISNULL(_dateUpdate, _dateEntry) as date FROM mytable

but is not enought as I've to get also the most recent. How can I modify my query?

like image 300
Ras Avatar asked Mar 02 '26 19:03

Ras


2 Answers

You can use a case to return what you want:

SELECT
    id
    , description
    , CASE WHEN _dateEntry > ISNULL(_dateUpdate,0) 
           THEN _dateEntry ELSE _dateUpdate END AS date
FROM
    mytable
like image 63
Andrei Hirsu Avatar answered Mar 05 '26 10:03

Andrei Hirsu


I suppose _dateEntry is never NULL. If can be NULL tell me because I change my query

Try this:

SELECT id, description, 
CASE
   WHEN _dateUpdate IS NULL THEN _dateEntry
   WHEN _dateUpdate > _dateEntry THEN dateUpdate
   ELSE _dateEntry
END as date 
FROM mytable 
ORDER BY 
CASE
   WHEN _dateUpdate IS NULL THEN _dateEntry
   WHEN _dateUpdate > _dateEntry THEN dateUpdate
   ELSE _dateEntry
END desc

So if _dateUpdate IS NULL you'll get the value of _dateEntry, so the order is on two fields

like image 38
Joe Taras Avatar answered Mar 05 '26 10:03

Joe Taras