How to find the minimum and maximum values in a single MySQL Query?

MySQLMySQLi Database

To find the minimum and maximum values in a single query, use MySQL UNION. Let us first create a table −

mysql> create table DemoTable
(
   Price int
);
Query OK, 0 rows affected (0.57 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable values(88);
Query OK, 1 row affected (0.30 sec)
mysql> insert into DemoTable values(100);
Query OK, 1 row affected (0.22 sec)
mysql> insert into DemoTable values(98);
Query OK, 1 row affected (0.15 sec)
mysql> insert into DemoTable values(120);
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 −

+-------+
| Price |
+-------+
| 88    |
| 100   |
| 98    |
| 120   |
+-------+
4 rows in set (0.00 sec)

Following is the query to find the minimum and maximum values in a single MySQL Query −

mysql> select Price from DemoTable where Price=(select min(Price) from DemoTable)
   UNION
   select Price from DemoTable where Price=(select max(Price) from DemoTable);

This will produce the following output −

+-------+
| Price |
+-------+
| 88    |
| 120   |
+-------+
2 rows in set (0.00 sec)
raja
Published on 27-Sep-2019 10:22:25
Advertisements