Lets say that I have a table which contains a column for invoice number, the data type is VARCHAR with mixed string/int values like:
invoice_number
**************
HKL1
HKL2
HKL3
.....
HKL12
HKL13
HKL14
HKL15
I tried to select max of it, but it returns with "HKL9", not the highest value "HKL15".
SELECT MAX( invoice_number )
FROM `invoice_header`
HKL9
(string) is greater thanHKL15
, because they are compared as strings. One way to deal with your problem is to define a column function that returns only the numeric part of the invoice number.If all your invoice numbers start with
HKL
, then you can use:It takes the invoice_number excluding the 3 first characters, converts to int, and selects max from it.
This should work also
After a while of searching I found the easiest solution to this.
select ifnull(max(CONVERT(invoice_number ,SIGNED INTEGER)),0) from invoice_header where invoice_number REGEXP '^[0-9]+$'
Your problem is more one of definition & design.
Select the invoice number with highest ID or DATE, or -- if those really don't correlate with "highest invoice number" -- define an additional column, which does correlate with invoice-number and is simple enough for the poor database to understand.
It's not that the database isn't smart enough.. it's that you're asking it the wrong question.