Find maximum value from a VARCHAR column in MySQL

MySQLMySQLi Database

To find maximum value, use MAX() along with CAST(), since the values are of VARCHAR type. Let us first create a table −

mysql> create table DemoTable2030
   -> (
   -> Value varchar(20)
   -> );
Query OK, 0 rows affected (0.44 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable2030 values('8');
Query OK, 1 row affected (0.14 sec)

mysql> insert into DemoTable2030 values('1');
Query OK, 1 row affected (0.19 sec)

mysql> insert into DemoTable2030 values('10001');
Query OK, 1 row affected (0.11 sec)

mysql> insert into DemoTable2030 values('901');
Query OK, 1 row affected (0.22 sec)

Display all records from the table using select statement &miuns;

mysql> select *from DemoTable2030

This will produce the following output −

+-------+
| Value |
+-------+
| 8     |
| 1     |
| 10001 |
| 901   |
+-------+
4 rows in set (0.00 sec)

Following is the query to find maximum value from a VARCHAR column −

mysql> select max(cast(Value as unsigned)) from DemoTable2030;

This will produce the following output −

+------------------------------+
| max(cast(Value as unsigned)) |
+------------------------------+
| 10001                        |
+------------------------------+
1 row in set (0.00 sec)
raja
Published on 06-Apr-2020 17:12:14
Advertisements