Kris
Kris

Reputation: 35

SQL sorting by asc/ desc

How do i sort my data in sql in asc or desc order?

I am using :

ORDER BY DESC

but my data is not in order. The data for my codes are below :

AC1, AC2 ,AC3 ..., AC30,AC31

The sql sorts the data by the first letter and not the value of the data so my data is sorted like this

AC10, AC11, AC12, AC13 ... AC19

Next in line would be :

AC20, AC21, AC22, AC23

I would like my data to be sorted from the very first number (AC1,AC2,AC3...) and not (AC1,AC10,AC11)

Upvotes: 0

Views: 404

Answers (1)

Gordon Linoff
Gordon Linoff

Reputation: 1271241

The order by is working correctly. Your expectation is wrong. Strings are sorted alphabetically.

You can easily get what you want. Assuming the column starts with two letters, you can do:

order by char_length(col) desc, col desc

If you want the default sort to work, then just pad the numbers . . . AC01, AC02, and so on.

Upvotes: 5

Related Questions