Ben G
Ben G

Reputation: 26761

Get MAX() on column in two tables

I have two tables which both have the column DateTime.

How can I get the MAX() DateTime?

The shorter/simpler the better, because this is just part of a larger query.

Upvotes: 3

Views: 10884

Answers (2)

OMG Ponies
OMG Ponies

Reputation: 332541

You could 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 ALL for this - it's faster because it doesn't remove duplicates, and it doesn't matter if duplicates are returned by the subquery in this example.

Upvotes: 17

Jürgen Steinblock
Jürgen Steinblock

Reputation: 31723

SELECT MAX(thedate) FROM (
    SELECT mydate as thedate FROM TABLE1

    UNION

    SELECT anotherdate as thedate FROM TABLE2
) as tablealias

Upvotes: 3

Related Questions