Using MAX () in a VARCHAR field

I have a table with the following dataset

ID (VARCHAR2 field)
D001
D002
D010
D0012

I use max()in this field.

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

As a result, returns D010.

Why is the result not D0012?

+5
source share
4 answers

You get D010it because it D010appears in alphabetical order after D0012or in another way, D01appears after D00, and therefore everything that is D01xcomes after everything that begins with D00x.

+13
source

below code works for me according to your expectation

select max(to_number(regexp_substr(id, '\d+'))) id from <yourtable>;
+1
source

, , .

    select MAX(CAST(REPLACE(REPLACE(ID, 'D', ''), '', '') as int)) from <table-name>
0

it should work

Select MAX(ID) from table where IsNumeric(ID) = 1 ; 
-1
source

All Articles