MySQL query to get max id from varchar type and the values in numeric?

MySQLMySQLi Database

Use CAST() in MAX() to get max id from varchar type and values in numeric. Let us first create a table. Here, we have a column with varchar type −

mysql> create table DemoTable
(
   UserMarks varchar(20)
);
Query OK, 0 rows affected (0.77 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable values('77');
Query OK, 1 row affected (0.10 sec)
mysql> insert into DemoTable values('98');
Query OK, 1 row affected (0.17 sec)
mysql> insert into DemoTable values('45');
Query OK, 1 row affected (0.12 sec)
mysql> insert into DemoTable values('56');
Query OK, 1 row affected (0.18 sec)
mysql> insert into DemoTable values('89');
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable values('99');
Query OK, 1 row affected (0.10 sec)
mysql> insert into DemoTable values('91');
Query OK, 1 row affected (0.11 sec)
mysql> insert into DemoTable values('94');
Query OK, 1 row affected (0.15 sec)

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

mysql> select *from DemoTable;

This will produce the Following output −

+-----------+
| UserMarks |
+-----------+
| 77        |
| 98        |
| 45        |
| 56        |
| 89        |
| 99        |
| 91        |
| 94        |
+-----------+
8 rows in set (0.00 sec)

Following is the query to get max id from varchar type and the values in numeric −

mysql> SELECT MAX(CAST(UserMarks AS SIGNED)) AS MAX_VALUE from DemoTable;

This will produce the Following output −

+-----------+
| MAX_VALUE |
+-----------+
| 99        |
+-----------+
1 row in set (0.00 sec)
raja
Published on 29-Apr-2019 08:39:57
Advertisements