php - SQL get nearest date record -


this sample data:

 booking_id   name   start_date    1            abc   1/1/2018    2            efg   5/2/2018    3            pqr   16/1/2018    4            xyz   19/2/2018 

i want in order nearest today date on top , past date in last

you need sort desc function on column start_date. below query produce desired result.

select * table1 order start_date desc; 

you can check sqlfiddle demo here

if dates in future, have use asc desired result.

select * table1 order start_date asc; 

if dates mix of past , future dates below sample data.

id name   start_date --------------------- 1  abc   2018-01-01 2  efg   2018-02-05 3  pqr   2018-01-16 4  xyz   2018-02-19 1  abc   2017-01-01 2  efg   2017-02-05 3  pqr   2017-01-16 4  xyz   2017-02-19 

below query can option show data in more friendly format.

select * ( select * table1 start_date < current_date order start_date desc ) b union select 0,'today_date', current_date union select * ( select * table1 start_date > current_date order start_date asc )  

it sort past dates data in desc order, add today date result , add future data in asc format below.

 id  name        start_date -------------------------- 4   xyz         2017-02-19 2   efg         2017-02-05 3   pqr         2017-01-16 1   abc         2017-01-01 0   today_date  2017-08-18 1   abc         2018-01-01 3   pqr         2018-01-16 2   efg         2018-02-05 4   xyz         2018-02-19 

check sqlfiddle demo here


Comments

Popular posts from this blog

Is there a better way to structure post methods in Class Based Views -

performance - Why is XCHG reg, reg a 3 micro-op instruction on modern Intel architectures? -

jquery - Responsive Navbar with Sub Navbar -