简体   繁体   中英

MySQL Varchar Sorting as Int

Here is my problem. I have a table such as the following:

+-----------+--------+
| data      | number | 
+-----------+--------+
| Something | NULL   |
| Test      | 1      |
| Another   | 5      |
| Testy     | 22     |
| Tester    | NULL   |
| Test2     | 3      |
+-----------+--------+

The Number field is of type VARCHAR , and I need to sort by this column. I can't do a blanket CAST because I need to preserve the NULL values; I don't want to turn them into 0 .

Here is what I've tried so far:

IF ( number != NULL, CAST( number AS UNSIGNED ), number ) as int_number

+

ORDER BY int_number

But this doesn't work, I presume because CAST can only effect a column as a whole, not each value on an individual basis.

I can't convert this column to an INT field for reasons that I can't explain here.

Please test any answers you come up with. The answer I mark correct won't be the first answer I see unless it has already been tested and works.

CAST() and CONVERT() functions do not convert nulls to 0, you need to use IFNULL() or COALESCE() for that. So, you can do an order by cast(fieldname as signed integer) to leave null values intact.

NULL should appear before all numbers

One easy way to achieve it is just use CAST :

SELECT * FROM tab ORDER BY CAST(number AS UNSIGNED)

SqlFiddleDemo

Output:

╔════════════╦════════╗
║   data     ║ number ║
╠════════════╬════════╣
║ Something  ║ (null) ║
║ Tester     ║ (null) ║
║ Test       ║ 1      ║
║ Test2      ║ 3      ║
║ Another    ║ 5      ║
║ Testy      ║ 22     ║
╚════════════╩════════╝

You should consider changing datatype to INT if it is possible.


Another way is to use implicit conversion as Abhik Chakraborty proposed in comment:

 SELECT * FROM tab ORDER BY number + 0 

use this

IF ( number  IS NOT NULL, CAST( number AS UNSIGNED ), NULL ) AS int_number

Note:

NULL values cannot be used with most comparison operators. For example, =, >, >=, <=, <, or != cannot be used, as any comparison with a NULL always returns a NULL value, never true (1) or false(0)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM