Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find Closest Date

Tags:

sqlite

I'm trying to run a query that will return rows sorted by closest to today's date.

Here is some data:

|   date   |
|----------|
|2012-12-02|
|2012-12-04|
|2012-12-10|
|2012-12-15|
|2012-12-29|
|2013-01-02|
|2013-01-04|

Here is my query:

SELECT * FROM days
    ORDER BY ABS( strftime( "%s", date ) - strftime( "%s", 2012-12-28 ) ) ASC

It just returns the rows in the same order I posted above, I want to get a result like

|   date   |
|----------|
|2012-12-29|
|2013-01-02|
|2013-01-04|
|2012-12-15|
|2012-12-10|
|2012-12-04|

My date field is a string in the format yyyy-MM-dd (there's a reason I'm not storing it as a timestamp). What am I doing wrong?

like image 766
Ralgha Avatar asked Aug 24 '26 04:08

Ralgha


2 Answers

There seems to be a mistake on the code:

SELECT * FROM days
    ORDER BY ABS( strftime( "%s", date ) - strftime( "%s", 2012-12-28 ) ) ASC

Written this way, the query will show the results just ordered by date.

The reason: 2012-12-28 will be treated as an arithmetic operation between integers. You should write '2012-12-28', to indicate that this is a date.

like image 95
jap1968 Avatar answered Aug 26 '26 23:08

jap1968


You don't have to use strftime.

SELECT * FROM days
 WHERE date <= '2012-12-28'
    ORDER BY date ASC
    -- LIMIT 5
like image 40
AFD Avatar answered Aug 27 '26 00:08

AFD



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!