Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ORDER BY date with past dates after upcoming dates

I need do execute a query on a table in a MySql database where the order of the resulting rows will be like this:

If today is 10/09/12:

...
11/09/12 
12/09/12
15/09/12
08/09/12  <--here start the past dates
07/09/12
05/09/12
....

Is there a way to achive this directly in MySQL?


I've resolved in this way:

First, the select statement include a new boolean that mark if the date is past or future by:

SELECT DISTINCT *,CASE  WHEN startdate < CURDATE() THEN 0
                ELSE 1 END AS past_or_future 

Second, I've done a double 'Order by': first on the past_or_future boolean and then on the date, with the conditional like this:

ORDER BY past_or_future  DESC , CASE WHEN past_or_future  = 1 THEN startdate END ASC, CASE WHEN past = 0 THEN startdate END DESC

in this way I've obtained for first all the upcoming dates ordered by date (from the lower value to higher) then all the past dates ordered from the date (from the higher to the lower)

like image 702
AleCat83 Avatar asked Sep 11 '12 07:09

AleCat83


People also ask

Can we use order by on date?

ORDER BY is a clause in SQL which is used with SELECT query to fetch the records in ascending or descending order from a table. Just like we sort the integer and the string values stored in the column of the tables, similarly, we can sort the dates stored in the SQL table's column.

How do I sort by date in SQL?

Use the ORDER BY keyword and the name of the column by which you want to sort. This way, you'll sort the data in ascending order by this column. You could also use the ASC keyword to make it clear that the order is ascending (the earliest date is shown first, the latest date is shown last, etc.).

How do I sort a list in MySQL?

The MySQL ORDER BY Keyword The ORDER BY keyword is used to sort the result-set in ascending or descending order. The ORDER BY keyword sorts the records in ascending order by default. To sort the records in descending order, use the DESC keyword.


1 Answers

You can still do CASE statement even in ORDER BY clause,

SELECT *
FROM tableName
ORDER BY (CASE WHEN DATE(dateColumn) < DATE(GETDATE())
              THEN 1
              ELSE 0
         END) DESC, dateColumn ASC
like image 90
John Woo Avatar answered Sep 19 '22 10:09

John Woo