[Answered ]-How to get latest timestamp from the two columns in django

1👍

Referring to the SQL you posted, you can place that into a Django extra() Queryset modifier:

qs = YourModel.objects.extra(select={
    'max_time': '''
    select * from t where (
        start_time_a in (
            select greatest(max(start_time_a), max(start_time_b)) from t
        ) or start_time_b in (
            select greatest(max(start_time_a), max(start_time_b)) from t
        )
    )'''
})

# each YourModel object in the queryset will have an extra attribute, max_time
for obj in qs:
    print obj.max_time

1👍

For getting row of greatest value from two column I found this answer and it is quite usefull

select * from t where (
                      start_time_a in (select greatest(max(start_time_a), max(start_time_b)) from t) or
                      start_time_b in (select greatest(max(start_time_a), max(start_time_b)) from t)
                      );

mysql greatest() function

0👍

MySQL solution:

If you want to identify latest dates from all records, irrespective of other column values, you can use MAX function on the date columns.

Example:

select max( start_time_a ) as mx_start_time_a
       , max( start_time_b ) as mx_start_time_b
from table_name

Leave a comment