Get MAX() on column in two MySQL tables?


Use GREATEST() to find the maximum. Let us first create a table −

mysql> create table DemoTable1
   (
   Number int
   );
Query OK, 0 rows affected (0.52 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable1 values(80);
Query OK, 1 row affected (0.26 sec)
mysql> insert into DemoTable1 values(229);
Query OK, 1 row affected (0.15 sec)
mysql> insert into DemoTable1 values(575);
Query OK, 1 row affected (0.24 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable1;

Output

+--------+
| Number |
+--------+
| 80     |
| 229    |
| 575    |
+--------+
3 rows in set (0.00 sec)

Following is the query to create second table −

mysql> create table DemoTable2
   (
   Number int
   );
Query OK, 0 rows affected (0.51 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable2 values(485);
Query OK, 1 row affected (0.17 sec)
mysql> insert into DemoTable2 values(10);
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable2 values(475);
Query OK, 1 row affected (0.12 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable2;

Output

+--------+
| Number |
+--------+
| 485    |
| 10     |
| 475    |
+--------+
3 rows in set (0.00 sec)

Following is the query to get MAX() on column in two tables −

mysql> select greatest((select max(Number) from DemoTable1),(select max(Number) from DemoTable2));

Output

+-----------------------------------------------------------------------------------------+
| greatest((select max(Number) from DemoTable1),(select max(Number) from DemoTable2))     |
+-----------------------------------------------------------------------------------------+
| 575                                                                                     |
+-----------------------------------------------------------------------------------------+
1 row in set (0.00 sec)
raja
Published on 13-Jun-2019 12:13:14
Advertisements