CREATE UNIQUE INDEX IF NOT EXISTS in postgreSQL

前端 未结 6 1424
天命终不由人
天命终不由人 2021-01-01 20:50

Plese I would like to do in PostgreSQL something like

CREATE UNIQUE INDEX IF NOT EXISTS

Any idea?

6条回答
  •  鱼传尺愫
    2021-01-01 21:11

    Another solution that support multiple columns index, based on @Kragh answer

    CREATE or replace FUNCTION create_index(_index text, _table text, VARIA
    
    DIC param_args text[]) RETURNS void AS
    $$
    declare 
       l_count integer;
    begin
        select count(*) into l_count
        from pg_indexes
        where schemaname = 'public'
            and tablename = lower(_table)
            and indexname = lower(_index);
    
        if l_count = 0 then
            EXECUTE format('create index %I on %I (%s)', _index, _table, array_to_string($3,','));
        end if;
    END;
    $$
    LANGUAGE plpgsql;
    

    and then you can use it like any other pg function:

    select create_index('events_timestamp_type_idx', 'events', 'timestamp', 'type');

提交回复
热议问题