Get MAX () in a column in two tables

I have two tables that have a DateTime column.

How can I get MAX () DateTime?

The shorter / simpler the better, because it is just part of a larger request.

+3
source share
2 answers

You can use the GREATEST function :

SELECT GREATEST((SELECT MAX(column) 
                   FROM TABLE_1),
                (SELECT MAX(column) 
                   FROM TABLE_2))

Using UNIONs:

SELECT MAX(col)
  FROM (SELECT col FROM TABLE_1
        UNION ALL
        SELECT col FROM TABLE_2)

Use UNION ALLfor this - faster, because it does not remove duplicates, and it doesn't matter if duplicates are returned by a subquery in this example.

+15
source
SELECT MAX(thedate) FROM (
    SELECT mydate as thedate FROM TABLE1

    UNION

    SELECT anotherdate as thedate FROM TABLE2
) as tablealias
+3
source

Source: https://habr.com/ru/post/1758569/


All Articles