Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort by month expressed by a string in SQL

I have the following sorting problem in SQL.

SELECT time, orderValue
FROM orders
ORDER BY time

The issue is that time is expressed by a string in the following format:

May 2012

June 2012

...

June 2013

The ORDER BY clause however sorts the problem in an alphabetic order (which is not strange since it's defined as a string). How to sort this in a correct order based on year and month?

like image 299
user1319951 Avatar asked Jun 27 '13 08:06

user1319951


1 Answers

Try:

SELECT time, orderValue
FROM orders
ORDER BY CONVERT (DATETIME, '01 ' + time, 104)
like image 135
Darren Avatar answered Oct 07 '22 03:10

Darren