How to select a field corresponding to the field in which MAX() exists?


For this, you can use sub query along with aggregate function MAX(). Let us first create a table −

mysql> create table DemoTable
   -> (
   -> ProductId int,
   -> ProductAmount int
   -> );
Query OK, 0 rows affected (0.78 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable values(1001,7895);
Query OK, 1 row affected (0.32 sec)
mysql> insert into DemoTable values(1003,8903);
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable values(1010,7690);
Query OK, 1 row affected (0.15 sec)
mysql> insert into DemoTable values(2010,8450);
Query OK, 1 row affected (0.12 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable;

This will produce the following output −

+-----------+---------------+
| ProductId | ProductAmount |
+-----------+---------------+
|      1001 |          7895 |
|      1003 |          8903 |
|      1010 |          7690 |
|      2010 |          8450 |
+-----------+---------------+
4 rows in set (0.00 sec)

Following is the query to select a field corresponding to the field in which max() exists −

mysql> select *from DemoTable
   -> where ProductAmount=( select max(ProductAmount) from DemoTable);

This will produce the following output −

+-----------+---------------+
| ProductId | ProductAmount |
+-----------+---------------+
|      1003 |          8903 |
+-----------+---------------+
1 row in set (0.05 sec)

Updated on: 13-Dec-2019

67 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements