13

I have a table with following set of data

ID (VARCHAR2 field)
D001
D002
D010
D0012

I use max() in this field.

Select max(ID) from <table-name>;

It returns D010 as result.

Why is the result not D0012?

APC
  • 144,005
  • 19
  • 170
  • 281
Vivek
  • 4,452
  • 10
  • 27
  • 45

6 Answers6

30

You get D010 because alphabetically, D010 comes after D0012 or said another way, D01 comes after D00 and therefore anything that is D01x comes after anything that starts D00x.

Thomas
  • 63,911
  • 12
  • 95
  • 141
  • 1
    And here is an example, how to deal with such problem -- http://stackoverflow.com/a/16496963/1469208 – trejder Sep 16 '15 at 12:09
5

below code is working for me as per your expectation

select max(to_number(regexp_substr(id, '\d+'))) id from <yourtable>;
Santhosh
  • 113
  • 1
  • 3
  • 8
1
SELECT * 
FROM  `<TABLE_NAME>` 
ORDER BY CAST(  `ID` AS DECIMAL( 10, 3 ) ) DESC 
RF1991
  • 2,037
  • 4
  • 8
  • 17
Muhammad ali
  • 287
  • 4
  • 17
0

this should work

Select MAX(ID) from table where IsNumeric(ID) = 1 ; 
Mohamed Islam Fares
  • 193
  • 1
  • 2
  • 10
0

This will surely work.

    select MAX(CAST(REPLACE(REPLACE(ID, 'D', ''), '', '') as int)) from <table-name>
Ketan Dubey
  • 430
  • 8
  • 19
0

First Varchar need to Casted as int to select as MAX. Use below query:

select max(CAST(ID as signed)) as max_id from <table-name>;

BSB
  • 2,270
  • 17
  • 26