Fetch maximum value from a column with values as string numbers like Value440, Value345, etc. in SQL

MySQLMySQLi Database

For this, you can use MAX() along with substring(). Let us first create a table −

mysql> create table DemoTable1337
   -> (
   -> Value varchar(50)
   -> );
Query OK, 0 rows affected (0.58 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable1337 values('Value400');
Query OK, 1 row affected (0.15 sec)
mysql> insert into DemoTable1337 values('Value345');
Query OK, 1 row affected (0.12 sec)
mysql> insert into DemoTable1337 values('Value567');
Query OK, 1 row affected (0.17 sec)
mysql> insert into DemoTable1337 values('Value489');
Query OK, 1 row affected (0.22 sec)

Display all records from the table using select statement −

mysql> select * from DemoTable1337;

This will produce the following output −

+----------+
| Value    |
+----------+
| Value400 |
| Value345 |
| Value567 |
| Value489 |
+----------+
4 rows in set (0.00 sec)

Following is the query to find maximum in value in MySQL when column is varchar −

mysql> select max(cast(substring(Value, 6) as decimal(10,2))) as MaximumValue from DemoTable1337;

This will produce the following output −

+--------------+
| MaximumValue |
+--------------+
|       567.00 |
+--------------+
1 row in set (0.04 sec)
raja
Published on 05-Nov-2019 07:08:47
Advertisements