How to get the maximum value from a column with alphanumeric strings beginning with specific characters in MYSQL?


For maximum value, use MAX() along with CAST() for conversion. Since we want maximum value from string-numbers beginning with specific characters, use RLIKE. Let us first create a table −

mysql> create table DemoTable1381
   -> (
   -> DepartmentId varchar(40)
   -> );
Query OK, 0 rows affected (0.48 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable1381 values('IT794');
Query OK, 1 row affected (0.19 sec)
mysql> insert into DemoTable1381 values('AT1034');
Query OK, 1 row affected (0.52 sec)
mysql> insert into DemoTable1381 values('IT967');
Query OK, 1 row affected (0.12 sec)
mysql> insert into DemoTable1381 values('IT874');
Query OK, 1 row affected (0.17 sec)
mysql> insert into DemoTable1381 values('AT967');
Query OK, 1 row affected (0.09 sec)

Display all records from the table using select statement −

mysql> select * from DemoTable1381;

This will produce the following output −

+--------------+
| DepartmentId |
+--------------+
| IT794        |
| AT1034       |
| IT967        |
| IT874        |
| AT967        |
+--------------+
5 rows in set (0.00 sec)

Following is the query to get the maximum value from a column with alphanumeric strings beginning with specific characters i.e. “IT” here −

mysql> select max(cast(substr(trim(DepartmentId),3) AS UNSIGNED)) from DemoTable1381 where DepartmentId RLIKE 'IT';

This will produce the following output −

+-----------------------------------------------------+
| max(cast(substr(trim(DepartmentId),3) AS UNSIGNED)) |
+-----------------------------------------------------+
|                                                 967 |
+-----------------------------------------------------+
1 row in set (0.10 sec)

Updated on: 11-Nov-2019

462 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements