Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort by distance from now() (future first) in PostgreSQL

Tags:

sql

postgresql

I've got a date field which is displayed as the number of days from today. So 2055-01-01 and 1950-01-01 would be displayed as positive and negative numbers respectively. Now I'd like these to be ordered so that the non-negative numbers come first, in ascending order, then negative numbers come in descending order. For example:

0
1
2
3
4
-1
-2
-3
like image 258
l0b0 Avatar asked Sep 12 '25 01:09

l0b0


1 Answers

The following would also work:

 ORDER BY expiry < CURRENT_DATE, abs(expiry - CURRENT_DATE)

However this form won't use an index to produce the rows in the desired order. If your query would benefit from that (selects most of the rows from the table or uses a limit), then you'll need to use a union:

SELECT ... WHERE ... AND expiry >= CURRENT_DATE ORDER BY expiry
    UNION ALL
SELECT ... WHERE ... AND expiry < CURRENT_DATE ORDER BY expiry DESC
like image 68
Ants Aasma Avatar answered Sep 14 '25 14:09

Ants Aasma