Quantcast
Channel: Planet PostgreSQL
Viewing all articles
Browse latest Browse all 9645

Francois Marier: Taking the max/min of two columns in PostgreSQL

$
0
0
As part of a database view, I found myself wanting to get Postgres to display values from one of two columns, whichever was the largest.

My first attempt was:

SELECT id, MAX(column1, column2) FROM table1;

which of course didn't work because MAX() is an aggregate function which only takes a single parameter.

What I was looking for instead, is something that was introduced in 8.1:

SELECT id, GREATEST(column1, column2) FROM table1;

where GREATEST() (and its opposite: LEAST()) is a conditional expression.

Viewing all articles
Browse latest Browse all 9645

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>