MySQL: Sorting VARCHAR Columns as Integers
Databases sometimes store numbers as strings (VARCHAR), often due to legacy systems or external dependencies. This can lead to incorrect sorting results when using standard string comparisons. Here's how to correctly sort these string-formatted numbers in MySQL:
Optimal Solution: Data Type Conversion
The best approach is to alter the table column's data type to an integer (INT, BIGINT, etc.). This ensures proper numerical sorting and avoids future issues.
Alternative Methods (When Data Type Change Isn't Feasible):
CAST()
function to explicitly convert the VARCHAR values to integers before sorting:<code class="language-sql">SELECT col FROM yourtable ORDER BY CAST(col AS UNSIGNED);</code>
This forces MySQL to treat the values numerically during the sorting process. UNSIGNED
prevents negative number interpretation.
<code class="language-sql">SELECT col FROM yourtable ORDER BY col + 0;</code>
MySQL will attempt to interpret the string as a number for the addition operation, triggering the implicit conversion.
String Value | Integer Value |
---|---|
'1' | 1 |
'ABC' | 0 |
'123miles' | 123 |
'3' | 0 |
Non-numeric characters will result in a 0 value. Leading non-numeric characters will cause the entire conversion to fail.
The above is the detailed content of How Can I Sort VARCHAR Numbers as Integers in MySQL?. For more information, please follow other related articles on the PHP Chinese website!