Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MYSQL - Order column by ASCII Value

I have a column with texts, sorted by ASCII it should be ordered as:

-  (hyphen)
0
1  (numbers)
2
A  (uppercase)
B
_  (underscore)
a
b  (lowercase)
c

However it is being ordered as:

-  (hyphen)
0
1  (numbers)
2
a
b  (lowercase)
c
A
B  (uppercase)
C
_  (underscore)

How can I do the sorting by ASCII value?

like image 316
htafoya Avatar asked Apr 09 '18 19:04

htafoya


2 Answers

The sort order is controlled by the collation. You can use the BINARY collation to sort by raw bytes, which in the case of ASCII data will cause it to sort by ASCII value. See https://dev.mysql.com/doc/refman/5.7/en/sorting-rows.html

SELECT ...
FROM mytable
ORDER BY BINARY mycolumn

This will be more flexible than using the ASCII() function because that function only returns the ASCII value of the first character. Using the BINARY collation allows sorting by the full string.

like image 116
Bill Karwin Avatar answered Sep 18 '22 07:09

Bill Karwin


You could use ASCII:

SELECT *
FROM tab
ORDER BY ASCII(col_name) ASC
like image 42
Lukasz Szozda Avatar answered Sep 22 '22 07:09

Lukasz Szozda