How to create an index for elements of an array in PostgreSQL?

后端 未结 3 1192
我在风中等你
我在风中等你 2020-12-03 19:51

With this schema:

create table object (
   obj_id      serial      primary key,
   name        varchar(80) not null unique,
   description text,
   tag_arr            


        
3条回答
  •  甜味超标
    2020-12-03 20:36

    This is my workaround, because I see no PostgreSQL optimized internal function for do the same,

    CREATE FUNCTION unnest_with_idx(anyarray) RETURNS 
    table(idx integer, val anyelement) AS $$ 
       SELECT generate_series(1,array_upper($1,1)) as idx, unnest($1) as val;
    $$ LANGUAGE SQL IMMUTABLE;
    -- Test:
    SELECT idx,val from unnest_with_idx(array[1,20,3,5]) as t;
    

    For check if exists an internal function, see "How to acess array internal index with postgreSQL?" question.


    Edited after @JimNasby comment

    Solution for pg9.4+

    SELECT * FROM unnest(array[20,11,3,5]) WITH ORDINALITY;
    

    the WITH ORDINALITY produces a new column "ordinality" that is the array-index. See also this tutorial.

    In pg9.5+, it works fine also for JSON arrays!

     SELECT * FROM jsonb_array_elements( '[20,11,3,5]'::JSONB ) WITH ORDINALITY
    

提交回复
热议问题