- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Get MAX and MIN values along with their row id in MySQL?
You can use aggregate function MAX() and MIN() for this.
Let us first create a table −
mysql> create table DemoTable ( Id int NOT NULL AUTO_INCREMENT PRIMARY KEY, Number1 int, Number2 int ); Query OK, 0 rows affected (0.89 sec)
Insert records in the table using insert command −
mysql> insert into DemoTable(Number1,Number2) values(67,45); Query OK, 1 row affected (0.18 sec) mysql> insert into DemoTable(Number1,Number2) values(90,40); Query OK, 1 row affected (0.18 sec) mysql> insert into DemoTable(Number1,Number2) values(80,43); Query OK, 1 row affected (0.48 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable ;
This will produce the following output −
+----+---------+---------+ | Id | Number1 | Number2 | +----+---------+---------+ | 1 | 67 | 45 | | 2 | 90 | 40 | | 3 | 80 | 43 | +----+---------+---------+ 3 rows in set (0.00 sec)
Following is the query to get MAX and MIN values along with their row id −
mysql> select * from DemoTable where Number1 = (select max(Number1) from DemoTable) or Number2 = (select min(Number2) from DemoTable);
This will produce the following output −
+----+---------+---------+ | Id | Number1 | Number2 | +----+---------+---------+ | 2 | 90 | 40 | +----+---------+---------+ 1 row in set (0.00 sec)
- Related Articles
- How to get max(id) of row data in MySQL?
- Get max and min values of an array in Arduino
- MySQL query to get max id from varchar type and the values in numeric?
- Retrieve MIN and MAX date in a single MySQL query from a column with date values
- How to get element with max id in MongoDB?
- Min and max values of an array in MongoDB?
- How to determine the row that have min and max values in an R data frame column?
- Only display row with highest ID in MySQL
- Sorting max to min value in MySQL
- Find max and min values in array of primitives using Java
- max() and min() in Python
- MySQL query to get the max value with numeric values in varchar field?
- Find max and min values in an array of primitives using Java
- Explain the use of MIN() and MAX() using MySQL in Python?
- Perform min/max with MongoDB aggregation

Advertisements