Link to home
Start Free TrialLog in
Avatar of dirknibleck
dirknibleck

asked on

Return numeric part from varchar field

I have a field in a table with data in the format of:

R100
R101
R102

I need to return the maximum of the numeric part and increment by 1 to assist the user in setting a unique value that has not been used yet. I had thought regexp might work for me, but it does not seem to be the right fit - as it returns only a 1 or 0.

Is there another way to do this?

Avatar of Dave Baldwin
Dave Baldwin
Flag of United States of America image

If the format is consistent with the same letter 'R' followed by 3 numbers, then you can use 'ORDER BY' that column 'DESC' with a 'LIMIT' of 1 to get the highest value in the table and remove the 'R' to get only the number.
You could use this

select max(substr(col,2)*1)+1 from tbl

Assuming the number starts from position 2 in the string.
So R0001, R0101, R1010, R99 etc

*1 is used to convert to number, so that "1010" > "99"
Avatar of dirknibleck
dirknibleck

ASKER

What if the alpha characters are not in a constant position?

I can have R001, but I could also have RR001 or R001-R, or technically any combination thereof.

Does the table have a unique key?
ASKER CERTIFIED SOLUTION
Avatar of cyberkiwi
cyberkiwi
Flag of New Zealand image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial