levi levi - 1 month ago 5
SQL Question

Selecting max value between values PostgreSQL

Let's say I want to select max attribute between two columns on a query. it isn't the whole table max.

Something like that:

SELECT MAX(t1.c1, t2.c2)
FROM Table1 as t1, Table2 as t2
WHERE t1.id = t2.t1_id
AND ...... here goes more conditions.

I want to each row has mapped value representing the max between

Is that possible ?


Use union all:

select max(c1)
from (select c1 from t1 union all select c2 from t2) t;

Or -- probably more efficient -- use greatest():

select greatest(c1, c2)
from (select max(c1) as c1 from t1) t1 cross join
     (select max(c2) as c2 from t2) t2;