SeanFromIT
SeanFromIT

Reputation: 676

How to Order MySQL VARCHAR Results

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 return the select something like the following:

987
12-a
1234
13-bh

It puts three character long results before four character long results and so on. I would like it to ignore length and just sort the numbers that come before the '-' char. Is there something that I can ORDER on like SUBSTRING in an IF() which would remove all data in a row starting with the '-' char, so that I can CAST as an integer?

Upvotes: 6

Views: 8173

Answers (3)

keithics
keithics

Reputation: 8758

...
....
CAST(COL as SIGNED)  DESC

Upvotes: 0

MestreLion
MestreLion

Reputation: 13686

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.

Upvotes: 0

RichardTheKiwi
RichardTheKiwi

Reputation: 107716

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;

Upvotes: 16

Related Questions