atoroqo — 2013-05-08T16:08:06-04:00 — #1
I have a couple of ORDER BY questions that I hope someone can and want to answer.
1) Is there any easy way I can achieve a natural sorting order with both numbers and letter (i.e. 1, 2, 10, 11, 20, 100, a2, a100, b5 etc.) in MySQL? I've found some suggestions involving ASC 0, but they don't seem to work when letters are involved.
2) Is there any way to create a sort on SQL level (rather than, e.g., PHP) that puts all rows with a certain value at the end of the list, for example 0 in an INT column that contains years. In the cases where the years is unknown the rows have 0, which I would like to come last in both ascending and descending order. Similarly with empty strings in other column types.
r937 — 2013-05-08T17:03:54-04:00 — #2
1) nothing easy... i recommend a second column, declared INTEGER, for sorting
2) use a CASE statement
for example, to put 0's last in ascending order...
BY CASE WHEN foo = 0
ELSE 'dumpty' ASC
, foo ASC
atoroqo — 2013-05-09T07:05:09-04:00 — #3
Great suggestion, as always. Thanks.
Probably great as well. I'll just have to understand it before deciding.
Edit: I obviously need to read up a little more on CASE syntax, but is the first ASC a typo for END, or have I done something wrong that makes it work with END but not ASC?
r937 — 2013-05-09T07:35:29-04:00 — #4
aaargh, my bad, yes, i forgot to put END before ASC there
ASC, of course, because you want dumpty rows before humpty rows
i know ASC is default, but in these cases it helps to have it there explicitly
atoroqo — 2013-05-09T07:59:35-04:00 — #5
Ah, yes, thanks for the clarification.
system — 2014-10-08T00:12:10-04:00 — #6
This topic is now closed. New replies are no longer allowed.