Getting the maximum value from a varchar field in MySQL

MySQLMySQLi Database

Use MAX() function along with SUBSTRING() for this. Let us first create a table −

mysql> create table DemoTable
   -> (
   -> Id varchar(200)
   -> );
Query OK, 0 rows affected (0.52 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable values('2019-0515-1980');
Query OK, 1 row affected (0.49 sec)

mysql> insert into DemoTable values('2019-0516-780');
Query OK, 1 row affected (0.19 sec)

mysql> insert into DemoTable values('2019-0517-2780');
Query OK, 1 row affected (0.16 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable;

Output

+----------------+
| Id             |
+----------------+
| 2019-0515-1980 |
| 2019-0516-780  |
| 2019-0517-2780 |
+----------------+
3 rows in set (0.00 sec)

Following is the query to get the maximum value from a varchar field −

mysql> select max(Id) from DemoTable
   -> where Id LIKE  CONCAT(SUBSTRING(Id, 1, 4),'%');

Output

+----------------+
| max(Id)        |
+----------------+
| 2019-0517-2780 |
+----------------+
1 row in set (0.00 sec)
raja
Published on 10-Jul-2019 15:31:47
Advertisements