0

I have an id column in table with following data:

K1
K2
K3
....
876
765
887
K12
K13

I want to find the max id with constant 'K' I have used following syntax

Select max(id) from table where id like 'k%'

The end result is K9 How can I get the accurate result which is k13

Madhur Bhaiya
  • 28,155
  • 10
  • 49
  • 57
Imran
  • 35
  • 1
  • 5
  • Possible duplicate of [How to get only Digits from String in mysql?](https://stackoverflow.com/questions/37268248/how-to-get-only-digits-from-string-in-mysql) – Justinas Nov 28 '18 at 07:50
  • You could try using `SUBSTRING()` to remove the k before checking the max, but that might require using a sub-select. It would be helpful to know more about the table structure. – Snake14 Nov 28 '18 at 07:53

2 Answers2

3

You where close, try:

Select CONCAT('K', MAX(CAST(REPLACE(id, 'K', '') AS UNSIGNED))) as maximum 
from table 
where id like 'K%'
TalESid
  • 2,304
  • 1
  • 20
  • 41
  • Added `CAST.. AS UNSIGNED` to your query; it is required to treat the modified string as integer value for comparison and determining MAX() value. – Madhur Bhaiya Nov 28 '18 at 07:54
1

Try this.

  1. Replace K with Empty String.
  2. Convert String to Number.
  3. Take MAX from the result.
  4. Finally append K with MAX value.

    SELECT CONCAT('K', MAX(CAST(REPLACE(id, 'K', '') AS UNSIGNED))) as max
    FROM table
    WHERE id LIKE 'K%';

TalESid
  • 2,304
  • 1
  • 20
  • 41
  • That's the good one (Last point). Just a suggestion: Write your code in code blocks so the answer would be easily readable!!! – TalESid Nov 28 '18 at 08:17