3

LARGE lets you find the nth largest value in an array. SMALL lets you find the nth smallest value in an array.

I want to do something like select SMALL([col1, col2, col3, 2], 2), LARGE([col1, col2, col3, 5], 2) from table1;

I am not looking for the GREATEST and LEAST FUNCTIONS. I want to find the nth smallest/largest values and not the smallest/largest values.

6
  • Are those numbers or character values?
    – user330315
    Feb 7, 2017 at 8:10
  • Numbers is what I will supply in args Feb 7, 2017 at 9:20
  • 1
    If it's only integers, consider using the intarray extension's sort() function instead of unnesting and aggregating in the function, e.g: (sort(array[3,5,1,2]))[2] that will be a lot faster.
    – user330315
    Feb 7, 2017 at 9:24
  • The columns I plan to use are Numeric. Is there a NumericArray sort of thing? I look at the solution and worry about performance for large number of rows. Feb 7, 2017 at 9:27
  • 1
    No, that extension is only for integers.
    – user330315
    Feb 7, 2017 at 9:28

1 Answer 1

5

The implementation is very simple:

CREATE OR REPLACE FUNCTION large(anyarray, int)
 RETURNS anyelement AS $$
  SELECT (ARRAY(SELECT unnest($1) ORDER BY 1 DESC))[$2]
 $$ LANGUAGE sql;

postgres=# SELECT large(ARRAY[3,2,1,4,5,0], 2);
┌───────┐
│ large │
╞═══════╡
│     4 │
└───────┘
(1 row)

For a "small" function - remove DESC in ORDER BY clause.

The implementation is based on unnest function - it transforms a array to table. It is sorted by ORDER BY clause - like any other table. A array constructor ARRAY(subselect) transforms sorted relation to array.

This functions uses a polymorphic arguments - it is similar to templates in C++. With these parameters this function is working with any array type.

7
  • using a variadic parameter probably matches the original function better.
    – user330315
    Feb 7, 2017 at 8:23
  • @a_horse_with_no_name - why - there is not necessary variadic, because first argument is a array already. Feb 7, 2017 at 8:26
  • But you can't call it like this then large(col1, col2, col3, 1) as show in the question.
    – user330315
    Feb 7, 2017 at 8:30
  • I see in question some different select SMALL([col1, col2, col3, 2], 2), and when I look to ms doc, then this function is not variadic too. Feb 7, 2017 at 8:33
  • @a_horse_with_no_name I love your idea too. I am not so particular about one way or another. Thanks for the answer pavel-stehule! Feb 7, 2017 at 9:20

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.