0

I have these values: d1, d45, d79, d33, d100

I want to sort these variables in ascending order from my table.

What is the query to get the output as:

d1
d33
d45
d79
d100
morgb
  • 2,252
  • 2
  • 14
  • 14

4 Answers4

1

What you want is called a "natural sort". For Microsoft SQL Server 2005, see this question. For other languages, see (for example) this other question.

Community
  • 1
  • 1
Roger Lipscombe
  • 89,048
  • 55
  • 235
  • 380
0

Sorry, not SQL answer at all. :) For variant with one letter only order by length and alpha.

Android
  • 56
  • 3
0

If you can guarantee a pattern of /\w\d+/ ...

In postgres:

select foo from bar order by cast(substring(foo from 2) as int)

..and similar will exist for other SQL flavours. Expensive mind.

edit: androids solution looks good too:

..order by char_length(foo),foo
annakata
  • 74,572
  • 17
  • 113
  • 180
0

If we can assume that the data values only contain the letter d and a numeric value, then you can also use:

select column from YourTable
order by convert(int, replace(column, 'd', ''))

If it contains any other letters, then this method rapidly becomes unusable:

select column from YourTable
order by convert(int, 
        replace(replace(replace(replace(replace(
            column, 'a', ''),
                'b', ''),
                'c', ''),
                'd', ''), 
                'e', '')
        )
Jonathan
  • 25,873
  • 13
  • 66
  • 85