If I have an array of ints, how can I get the min value out of the array?
The min()
and least()
functions won’t work directly on the array.
for example if I have an array like below:
select 'a', array[1,2,3];
I want ‘a’, 1 as the results of my query.
I’ve tried select 'a', min(array[1,2,3]);
and select 'a', least(array[1,2,3]);
4
Answers
we can unnest the array, then group by the unique id, and use the min() function on that query to get the min for each unique row.
run the following queries one by one to see how it works.
You can install the intarray extension to sort the array and then pick the first element:
Alternatively you can write such a function:
For the corresponding implementation of
array_max()
you need to use anorder by ... desc
LEAST()
is only good for a small, known number of array elements, allowing us to spell it out like this:Else look to the answers of Adrian and a_horse.