2

I have an SQL database with I'm calling through a php file. The column can contain both numbers and words. For example it could countain:

1
4
clowns
12
46

Naturally, ORDER BY returns:

1
12
4
46
clowns

but I would like it to sort how it would sort integers with the numbers:

1
4
12
46
clowns

Is it possible to do this?

Jonathan
  • 2,778
  • 13
  • 23
wha1e
  • 31
  • 2

1 Answers1

3

add some new columns to solve this, first order by whether or not it is a number, then by the number value, and finally alphabetically by the word value.

In MSSQL you have access to the isnumeric function.
In ORACLE you could create a custom function using THIS
In MYSQL you could create a custom function using THIS

select your_column from(
select *, 
isnumeric(your_column) as ISNUMBER,
CASE WHEN ISNUMERIC(your_column) = 1 THEN CAST(your_column AS INT) ELSE null END as NUMBERVALUE,
case when isnumeric(your_column) = 1 then null else your_column end as TEXTVALUE )
order by isnumber desc, numbervalue asc, textvalue asc
...
Community
  • 1
  • 1
Brino
  • 2,442
  • 1
  • 21
  • 36