0

I was having some trouble when trying to write an SQLstatement which sorted by time column which is in varchar format in ascending order. Here is my SQL statement:

SELECT mrtpopTime, mrtpopAmt
FROM tm_mrtpop
WHERE mrtpopName = ''
ORDER BY mrtpopTime

And I am getting these results:

enter image description here

As you can see from the picture, it was sorted by character by character. Is there anyway to sort it like:

0:00, 1:00, 2:00, 3:00 all the way to 23:00

Any ideas? Thanks in advance.

QWERTY
  • 2,303
  • 9
  • 44
  • 85

2 Answers2

3

Convert varchar time column to a time (or dummy date plus time) and order by that:

SELECT mrtpopTime, mrtpopAmt
FROM tm_mrtpop
WHERE mrtpopName = ''
ORDER BY STR_TO_DATE(mrtpopTime, '%H:%i')
Mitch Wheat
  • 295,962
  • 43
  • 465
  • 541
2

As the mrtpopTime is in varchar it won't sort. Hence cast it into float and order by

SELECT  mrtpopTime, mrtpopAmt
FROM tm_mrtpop
WHERE mrtpopName = ''
ORDER BY 'cast(mrtpopTime as float) time'
Naved Munshi
  • 487
  • 1
  • 5
  • 17