There is a table with records. Records have a date_start field ( DATE type).
I want to get a record whose date is as close as possible to Time.zone.today .

The first thing that comes to mind is to initially sort them by date_start , and then:

 .order(date_start: :desc).where('date_start <= ?', Time.zone.today).first 

But this method does not work exactly and sometimes gives incorrect results.

  • one
    "close" on one side or both? What query produces the described construction? What does the supposedly wrong result look like? - D-side

1 answer 1

 select sku.sku_id, sku.name, abs(date(now())-date(sku.created)) as diff from sku order by diff limit 1; 

Get an entry for the sku table with the creation date closest to the current one.

The size of the sku table in my database is 88432 records, execution time ~ 50 ms