Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting array elements

Tags:

postgresql

I want to write a stored procedure that gets an array as input parameter and sort that array and return the sorted array.

Kindly help.

like image 225
giri Avatar asked May 26 '10 13:05

giri


People also ask

Can we sort elements in array?

The sort() method sorts the elements of an array in place and returns the reference to the same array, now sorted.

What is an array What is sorting sort an array with an example?

Sorting an array means to arrange the elements in the array in a certain order. Various algorithms have been designed that sort the array using different methods. Some of these sorts are more useful than the others in certain situations.


2 Answers

The best way to sort an array of integers is without a doubt to use the intarray extension, which will do it much, much, much faster than any SQL formulation:

CREATE EXTENSION intarray;  SELECT sort( ARRAY[4,3,2,1] ); 

A function that works for any array type is:

CREATE OR REPLACE FUNCTION array_sort (ANYARRAY) RETURNS ANYARRAY LANGUAGE SQL AS $$ SELECT ARRAY(SELECT unnest($1) ORDER BY 1) $$; 

(I've replaced my version with Pavel's slightly faster one after discussion elsewhere).

like image 191
Craig Ringer Avatar answered Sep 24 '22 02:09

Craig Ringer


In PostrgreSQL 8.4 and up you can use:

select array_agg(x) from (select unnest(ARRAY[1,5,3,7,2]) AS x order by x) as _; 

But it will not be very fast.


In older Postgres you can implement unnest like this

CREATE OR REPLACE FUNCTION unnest(anyarray)   RETURNS SETOF anyelement AS $BODY$ SELECT $1[i] FROM     generate_series(array_lower($1,1),                     array_upper($1,1)) i; $BODY$   LANGUAGE 'sql' IMMUTABLE 

And array_agg like this:

CREATE AGGREGATE array_agg (         sfunc = array_append,         basetype = anyelement,         stype = anyarray,         initcond = '{}' ); 

But it will be even slower.


You can also implement any sorting algorithm in pl/pgsql or any other language you can plug in to postgres.

like image 42
Tometzky Avatar answered Sep 26 '22 02:09

Tometzky