Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 777
SeanFromIT Avatar asked Feb 20 '11 03:02

SeanFromIT


People also ask

How do I sort a varchar column in MySQL?

'LPAD(lower(column_name))' is used to sort the varchar field numerically in MySQL.

How do I sort MySQL results?

The ORDER BY keyword is used to sort the result-set in ascending or descending order. The ORDER BY keyword sorts the records in ascending order by default. To sort the records in descending order, use the DESC keyword.

How do I change the order of rows in MySQL?

An "ALTER TABLE ORDER BY" statement exist in the syntaxes accepted by MySQL. According to the documentation, this syntax: - only accept *one* column, as in "ALTER TABLE t ORDER BY col;" - is used to reorder physically the rows in a table, for optimizations.

How do I show ascending order in MySQL?

You can use the keyword ASC or DESC to get result in ascending or descending order. By default, it's the ascending order.


1 Answers

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;
like image 79
RichardTheKiwi Avatar answered Oct 16 '22 10:10

RichardTheKiwi