Andrew Latham
Andrew Latham

Reputation: 6132

SQL order numbers alphabetically

Currently I have an SQL query that selects some columns and then does ORDER_BY ID.

Simple enough. The output is i.e. 92, 101, 105, 200, 1234

Problem is, the program I am trying to use it in will only accept input in alphanumerical order. That means I need it to be 101, 105, 1234, 200, 92.

How can I modify the SQL query to order the numbers alphanumerically?

Upvotes: 2

Views: 3096

Answers (3)

jstromwick
jstromwick

Reputation: 1206

One option would be to convert the column to a VARCHAR then sort on that

SELECT OrderID
FROM dbo.FooTable
ORDER BY CAST(OrderID AS VARCHAR(255)) 

Upvotes: 5

TomGough
TomGough

Reputation: 16

You should be able to just re-cast the data type for your ID column:

order by cast(ID as varchar(10))

This should work on most systems

Upvotes: 0

Gordon Linoff
Gordon Linoff

Reputation: 1269443

You can do this by converting the number to a character string:

order by cast(col as varchar(255))

For instance.

Upvotes: 2

Related Questions