A single MySQL query to find the highest and lowest among two tables?


To find the highest and lowest from two tables, use MAX() and MIN(). Since the results are to be displayed from two tables, you need to use UNION. Let us first create a table −

mysql> create table DemoTable1
(
   UniqueId int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   Score1 int
);
Query OK, 0 rows affected (0.76 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable1(Score1) values(56);
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable1(Score1) values(76);
Query OK, 1 row affected (0.12 sec)
mysql> insert into DemoTable1(Score1) values(65);
Query OK, 1 row affected (0.09 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable1;

This will produce the following output −

+----------+--------+
| UniqueId | Score1 |
+----------+--------+
|        1 |     56 |
|        2 |     76 |
|        3 |     65 |
+----------+--------+
3 rows in set (0.00 sec)

Following is the query to create the second table −

mysql> create table DemoTable2
(
   UniqueId int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   Score2 int
);
Query OK, 0 rows affected (0.93 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable2(Score2) values(67);
Query OK, 1 row affected (0.68 sec)
mysql> insert into DemoTable2(Score2) values(94);
Query OK, 1 row affected (0.12 sec)
mysql> insert into DemoTable2(Score2) values(98);
Query OK, 1 row affected (0.08 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable2;

This will produce the following output −

+----------+--------+
| UniqueId | Score2 |
+----------+--------+
|        1 |     67 |
|        2 |     94 |
|        3 |     98 |
+----------+--------+
3 rows in set (0.00 sec)

Following is the query to find the highest and lowest among 2 tables −

mysql> select max(commonValue) AS Highest_Value,min(commonValue) AS Lowest_Value from
(
   select Score1 as commonValue from DemoTable1
   union
   select Score2 as commonValue from DemoTable2
) tbl;

This will produce the following output −

+---------------+--------------+
| Highest_Value | Lowest_Value |
+---------------+--------------+
|            98 |           56 |
+---------------+--------------+
1 row in set (0.04 sec)

Updated on: 01-Oct-2019

101 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements