Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using MAX() in VARCHAR Field

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?

like image 519
Vivek Avatar asked Jun 15 '11 05:06

Vivek


People also ask

Can we use MAX function for VARCHAR?

The MAX() function can be allpied on the varchar columns.

How is VARCHAR max stored?

When VARCHAR(MAX) exceeds 8,000 characters, the pointer is stored “in row”, and the string is stored in “LOB” pages.

Can we use Max on a column?

MAX can be used with numeric, character, and datetime columns, but not with bit columns.

What is VARCHAR max length?

Values in VARCHAR columns are variable-length strings. The length can be specified as a value from 0 to 65,535. The effective maximum length of a VARCHAR is subject to the maximum row size (65,535 bytes, which is shared among all columns) and the character set used.


2 Answers

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.

like image 75
Thomas Avatar answered Oct 23 '22 07:10

Thomas


below code is working for me as per your expectation

select max(to_number(regexp_substr(id, '\d+'))) id from <yourtable>;
like image 5
Santhosh Avatar answered Oct 23 '22 06:10

Santhosh