Ben
Ben

Reputation: 4279

SQL order varchar as decimals

I have a row that has both numbers ant strings. I whant to order it so that numbers will be ordered as numbers and all the strings would go to the end of table.

ORDER BY (
          CASE 
               WHEN `{$table}`.`{$row}` LIKE '%[^0-9]%' 
                    THEN CAST(`{$table}`.`{$row}` AS DECIMAL) 
               ELSE `{$table}`.`{$row}` 
          END
         ) ASC"

But instead the numbers are still sorted like strings.

Results: 
0
410
680
72
Some other string
Some string


It should be:
0
72
410
680
Some other string
Some string

Upvotes: 0

Views: 123

Answers (2)

Gordon Linoff
Gordon Linoff

Reputation: 1269643

Try this:

order by (case when left(`{$table}`.`{$row}`, 1) between '0' and '9' then 0 else 1 end),
         `{$table}`.`{$row}` + 0,
         `{$table}`.`{$row}`

The first expression puts numbers first (or at least strings that start with a number). The second is a nice MySQL feature that simply converts a string to a number. The third sorts the non-numeric strings.

EDIT:

To have only numbers (instead of leading numbers) go first:

order by (case when left(`{$table}`.`{$row}`, 1) REGEXP '^-?[0-9]+$' then 0 else 1 end),
         `{$table}`.`{$row}` + 0,
         `{$table}`.`{$row}`

Upvotes: 1

Linger
Linger

Reputation: 15048

How about the following (SQL Fiddle):

SELECT * FROM 
(
  SELECT field1
  FROM MyTable
  WHERE field1 REGEXP '^-?[0-9]+$'
  ORDER BY CAST(field1 AS DECIMAL)
  )AS m
UNION
SELECT * FROM 
(
  SELECT field1
  FROM MyTable
  WHERE field1 NOT REGEXP '^-?[0-9]+$'
  ORDER BY field1
) AS mm

Upvotes: 0

Related Questions