How to SELECT min and max value from the part of a table in MySQL?


To select min and max value from the part of a table in MySQL, use the following syntax −

select min(yourColumnName) as yourAliasName1,max(yourColumnName) as
yourAliasName2 from
(select yourColumnName from yourTableName limit yourLimitValue) tbl1;

Let us first create a table. Following is the query −

mysql> create table MinAndMaxValueDemo
   -> (
   -> Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   -> Value int
   -> );
Query OK, 0 rows affected (0.52 sec)

Insert records in the table using insert command. Following is the query −

mysql> insert into MinAndMaxValueDemo(Value) values(10);
Query OK, 1 row affected (0.16 sec)

mysql> insert into MinAndMaxValueDemo(Value) values(100);
Query OK, 1 row affected (0.11 sec)

mysql> insert into MinAndMaxValueDemo(Value) values(50);
Query OK, 1 row affected (0.13 sec)

mysql> insert into MinAndMaxValueDemo(Value) values(40);
Query OK, 1 row affected (0.12 sec)

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

mysql> select * from MinAndMaxValueDemo;

This will produce the following output −

+----+-------+
| Id | Value |
+----+-------+
| 1  | 10    |
| 2  | 100   |
| 3  | 50    |
| 4  | 40    |
+----+-------+
4 rows in set (0.00 sec)

Following is the query to select min and max value from the part of a table in MySQL −

mysql> select min(Value) as MinimumValue,max(Value) as MaximumValue from
   -> (select Value from MinAndMaxValueDemo limit 3) tbl1;

This will produce the following output −

+--------------+--------------+
| MinimumValue | MaximumValue |
+--------------+--------------+
| 10           | 100          |
+--------------+--------------+
1 row in set (0.07 sec)

Updated on: 30-Jul-2019

332 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements