Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Oracle SQL MAX function not returning max on VARCHAR to NUMBER conversion

I am attempting to get the highest system number from a set of rows. The system number is preceded with SYS, thus select SYSTEM_ID from TABLE would yield, {SYS901,SYS87,SYS3024.....}

This is the query I'm attempting to use:

select MAX(REPLACE(SYSTEM_ID,'SYS','')) from TABLE

The possible results are

{901,87,3024,20,1}

It is returning the 901 value where I'm expecting to see the 3024 value. I assume the problem is that the field is a VARCHAR not a NUMBER. How to address this problem, I do not know.

like image 277
Patrick J Abare II Avatar asked Dec 04 '25 13:12

Patrick J Abare II


2 Answers

select MAX(TO_NUMBER(REPLACE(SYSTEM_ID,'SYS',''))) from TABLE;

Use TO_NUMBER to convert VARCHAR2 to NUMBER otherwise Oracle compares strings using their ASCII codes ('9' > '3')

like image 72
Multisync Avatar answered Dec 07 '25 03:12

Multisync


Of course it is returning the max. It is just returning the max according to the rules of string comparisons, not numbers.

To get the numeric max, do a conversion:

select MAX(TO_NUMBER(REPLACE(SYSTEM_ID, 'SYS', ''))) from TABLE
like image 39
Gordon Linoff Avatar answered Dec 07 '25 04:12

Gordon Linoff



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!