2

I have the following table

CREATE TABLE arr(
id int,
arr_r int []
);
INSERT INTO arr(arr_r ) VALUES
( ARRAY [1 ,2 ,3]) ,
( ARRAY [4 ,3]) ,
( ARRAY [7 ,6]) ,
( ARRAY [2 ,2]);

and I want to output the arrays in the table which are sorted in ascending order. An output would be

1, 2, 3
2, 2

I tried some stuff with array_agg and an order by inside the array_agg but that did not work. How would I go about getting the desired output?

2 Answers 2

2

You can install the intarray extension, then you can do:

select *
from arr
where arr_r = sort(arr_r);

If you don't want to install the extension, you can create your own sort function:

create function sort(p_input int[]) 
  returns int[]
as
$$
  select array_agg(i order by i)
  from unnest(p_input) as a(i);
$$
language sql
immutable;

Online example

Sign up to request clarification or add additional context in comments.

4 Comments

Wow thanks! The only problem I have left is that it gives me multiple rows of the same results. Using distinct didnt do the job here.
@NuTa: well, then you have duplicates in your initial table, which will obviously be returned by this query.
@NuTa: do you want to remove duplicate entries from the array?
oh, you were right. I didnt drop the table when I ran my script so it created multiple lines and therefore showed many lines.
0

You can eliminate duplicates by selecting unique values from unnest

create or replace 
function sort_int_array(p_input int[]) 
 returns int[]
as
$$
  select array_agg(i order by i)
    from ( select distinct unnest(p_input) i) a;
$$
language sql
immutable;

--- Test
select sort_int_array(array[1,3,2,5,7,5,3,6,8,8,9,0]) 

2 Comments

you can also use array_agg(distinct i ...)
True, I forgot about the distinct option in array_agg; which is better. Oh well, guess we all have there moments especially when switching between databases.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.