Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Date_Format and sort by date

Tags:

mysql

I am currently experiencing a problem with sorting a result by a data column which is using date_format.

I have the below dates:

  • 12-03-12
  • 21-03-12
  • 25-03-12
  • 17-04-12

When I perform the query:

SELECT date FROM myTable ORDER date DESC

The dates are ordered in the correct order

  • 17-04-12
  • 25-03-12
  • 21-03-12
  • 12-03-12

When I perform the query

SELECT DATE_FORMAT(date, '%d-%m-%Y') as `date` ORDER BY date

The dates are now in the wrong order

  • 25-03-12
  • 21-03-12
  • 17-04-12
  • 17-03-12
  • 14-03-12

I've also tried running the query SELECT DATE_FORMAT(date, '%d-%m-%Y') as date ORDER BY DATE_FORMAT(date, '%d-%m-%Y') but has made no difference.

How can I get this to sort in the correct order.

like image 304
Boardy Avatar asked Apr 17 '12 22:04

Boardy


People also ask

How to sort based on 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 to order by date and time in MySQL?

You can use the following query. SELECT column1,column2, UNIX_TIMESTAMP(CONCAT( event_date ,' ', event_time )) as unixtimestamp from table_name Order by unixtimestamp desc; Note:(There is a space between event_date and event_time in the CONCAT function.

How do I sort descending dates in SQL?

The ORDER BY statement in SQL is used to sort the fetched data in either ascending or descending according to one or more columns. By default ORDER BY sorts the data in ascending order. We can use the keyword DESC to sort the data in descending order and the keyword ASC to sort in ascending order.

How do I sort by month in SQL?

To order by month, create a date with this month. To do this, use the STR_TO_DATE() function. If you have a date stored as a string in the ' Year Month Day ' format, you can cast it to a date using STR_TO_DATE(date_string, '%Y %M %d') . The CONCAT() function combines all the arguments into one string.


2 Answers

The problem is that you are overriding the column name with the alias.

Choose another alias:

SELECT DATE_FORMAT(`date`, '%d-%m-%Y') as date_formatted
FROM myTable 
ORDER BY `date` DESC
like image 61
ypercubeᵀᴹ Avatar answered Nov 19 '22 09:11

ypercubeᵀᴹ


Just specify table name for the column in ORDER BY clause:

  SELECT DATE_FORMAT(date, '%d-%m-%Y') as `date`
    FROM myTable
ORDER BY myTable.`date` DESC -- <<<<<<

In this case mysql knows you want to sort by table column, not by the expression you've evaluated in the SELECT part

like image 6
zerkms Avatar answered Nov 19 '22 07:11

zerkms