I’m attempting to order by a number column in my database which has values 1-999
When I use
ORDER_BY registration_no ASC
I get….
1
101
102
103
104
105
106
107
108
109
11
110
Etc…
So it appears to be ordering by the first digit as oppose to the number.
Does anyone know what SQL to use if I want to order this by value? So 1,2,3,4,5,6
etc
Syntax. SELECT column-list FROM table_name [WHERE condition] [ORDER BY column1, column2, .. columnN] [ASC | DESC];
The ORDER BY statement in SQL is used to sort the fetched data in either ascending or descending according to one or more columns. By default ORDER BY sorts the data in ascending order. We can use the keyword DESC to sort the data in descending order and the keyword ASC to sort in ascending order.
The correct answer is Select, where, group by, having.
One way to order by positive integers, when they are stored as varchar
, is to order by the length first and then the value:
order by len(registration_no), registration_no
This is particularly useful when the column might contain non-numeric values.
Note: in some databases, the function to get the length of a string might be called length()
instead of len()
.
ORDER_BY cast(registration_no as unsigned) ASC
explicitly converts the value to a number. Another possibility to achieve the same would be
ORDER_BY registration_no + 0 ASC
which will force an implicit conversation.
Actually you should check the table definition and change it. You can change the data type to int
like this
ALTER TABLE your_table MODIFY COLUMN registration_no int;
That way indexes can be used properly and the order by
won't slow down the query.
If you are using SQL Server:
ORDER_BY cast(registration_no as int) ASC
ORDER_BY cast(registration_no as unsigned) ASC
gives the desired result with warnings.
Hence, better to go for
ORDER_BY registration_no + 0 ASC
for a clean result without any SQL warnings.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With