MySQL query to get the max value with numeric values in varchar field?


To get the max value, use the max() function. Let us create a table first −

mysql> create table findMaxValueInVarcharField
   -> (
   -> Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   -> Value varchar(200)
   -> );
Query OK, 0 rows affected (1.09 sec)

Following is the query to insert some records in the table using insert command −

mysql> insert into findMaxValueInVarcharField(Value) values('200');
Query OK, 1 row affected (0.14 sec)

mysql> insert into findMaxValueInVarcharField(Value) values('1000');
Query OK, 1 row affected (0.25 sec)

mysql> insert into findMaxValueInVarcharField(Value) values('899474');
Query OK, 1 row affected (0.18 sec)

mysql> insert into findMaxValueInVarcharField(Value) values('39474');
Query OK, 1 row affected (0.15 sec)

mysql> insert into findMaxValueInVarcharField(Value) values('4958');
Query OK, 1 row affected (0.12 sec)

Following is the query to display all records from the table using select statement −

mysql> select * from findMaxValueInVarcharField;

This will produce the following output −

+----+--------+
| Id | Value  |
+----+--------+
| 1  | 200    |
| 2  | 1000   |
| 3  | 899474 |
| 4  | 39474  |
| 5  | 4958   |
+----+--------+
5 rows in set (0.00 sec)

Following is the query to get the maximum from numeric values in a varchar field −

mysql> select max(cast(Value as unsigned) ) AS MaximumValueFromVarcharField from
findMaxValueInVarcharField;

This will produce the following output −

+------------------------------+
| MaximumValueFromVarcharField |
+------------------------------+
| 899474                       |
+------------------------------+
1 row in set (0.00 sec)

Updated on: 30-Jul-2019

342 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements