In a SELECT statement, I have a varchar column with ORDER BY DESC on it. Examples of data in this column:
1234
987
12-a
13-bh
MySQL would r
The trick part is dealing about the "-": since its optional, you cant directly use SUBSTR in that field (as Marc B pointed out) to get rid of everything after it
So, the trick would be: append an "-" to the value!
Like this:
ORDER BY CAST(SUBSTR(CONCAT(yourfield,'-'), 0, LOCATE('-', CONCAT(yourfield,'-'))) AS UNSIGNED)
Another useful approach is to, instead of using SUBSTR to "remove" everything after the "-", replace it (and all letters) to "0", and THEN use CAST.
The easiest thing to do is this
SELECT *
FROM TBL
ORDER BY VARCHAR_COLUMN * 1;
To see what is happening, just add the column I used for ordering
SELECT *, VARCHAR_COLUMN * 1
FROM TBL
ORDER BY VARCHAR_COLUMN * 1;
...
....
CAST(COL as SIGNED) DESC