Mínimo e Máximo no postgres dentro de arrays

Estava procurando na internet e achei várias soluções, porém, a melhor foi esta:

Menor valor

create function minimum(anyarray)
returns anyelement as $$
   SELECT min($1[i])
   FROM generate_series(array_lower($1,1), array_upper($1,1)) g(i);
$$ language sql immutable strict;

Maior valor

create function maximum(anyarray)
returns anyelement as $$
   SELECT max($1[i])
   FROM generate_series(array_lower($1,1), array_upper($1,1)) g(i);
$$ language sql immutable strict;

Testando:

SELECT *, minimum(abc), maximum(abc)
FROM qualquer_tabela;

Legal eim? Porém, diga-se de passagem, não é aconselhável usar campos arrays para fazer pesquisas de dados. Para isso, existem as FKs, que usam indexes.

Consultas:

  • procurar array o Máximo e Mínimo postgres
  • consultar o mínimo e máximo numa array no postgres
This entry was posted in geral. Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>