title: Get minimum difference of non-equal elements in integer array
body: <p>I would like to analyze column of integer arrays in PostgreSQL (9.1). Using <code>intarray</code> (<a href="http://www.postgresql.org/docs/9.1/static/intarray.html" rel="nofollow">docs here</a>) I am able to calculate:</p>
  
  <ul>
  <li>array length</li>
  <li>minimum value</li>
  <li>maximum value</li>
  <li>number of unique elements</li>
  </ul>
  
  <p>My query is:</p>
  
  <pre><code>    select 
          (array_length(string_to_array(num_partition,' ')::int[], 1))::smallint as part_len,
          icount(uniq(sort(string_to_array(num_partition,' ')::int[])))::smallint as part_unq,
          ((sort(string_to_array(num_partition,' ')::int[],'desc'))[1])::smallint as part_max,
          ((sort(string_to_array(num_partition,' ')::int[]))[1])::smallint as part_min    
      from 
          tmp.npart 
  </code></pre>
  
  <p>Now I would like to calculate minimum difference between any non-equal elements. Example:</p>
  
  <pre><code>Array [1,5,5,10]
  Expected result: 4 (because of 5-1 equals to 4)
  </code></pre>
  
  <p>I think I can calculate is using the following approach:</p>
  
  <ol>
  <li>Get unique elements of array</li>
  <li>Sort array </li>
  <li>For each element in array substract A[I] - A[I+1]</li>
  <li>Get maximum of the result in step 3</li>
  </ol>
  
  <p>Example:</p>
  
  <pre><code>Input: [7,9,12,20,25,1,1,20,25]
  1) Unique [1,7,9,12,20,25]
  2) Sort (desc): [25,20,12,9,7,1] 
  3) Diff A[i] - A[i+1]: [5,8,3,2,6]
  4) Min: 2
  </code></pre>
  
  <p>Is there any simple way how to do this? I need to calculate this on a table with 150 000 000 rows.</p>
  
  <p>Sample data (or <a href="http://sqlfiddle.com/#!1/c717e/1" rel="nofollow">sqlfiddle</a>):</p>
  
  <pre><code>create table tmp (intarr int[]);
  
  insert into tmp values (ARRAY[1,1,3,6,9,25]);
  insert into tmp values (ARRAY[10,20,30,50]);
  insert into tmp values (ARRAY[1,4,8,15,21]);
  insert into tmp values (ARRAY[1]);
  insert into tmp values (ARRAY[1,1,1,1,9,9,9,9,20,20,20]);
  </code></pre>