CREATE UNIQUE INDEX IF NOT EXISTS in postgreSQL

前端 未结 6 1444
天命终不由人
天命终不由人 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:15

    I have wrapped a_horse_with_no_name's code with PLSQL function for more convenient usage. I hope somebody will find it useful.

    CREATE OR REPLACE FUNCTION create_index(table_name text, index_name text, column_name text) RETURNS void AS $$ 
    declare 
       l_count integer;
    begin
      select count(*)
         into l_count
      from pg_indexes
      where schemaname = 'public'
        and tablename = lower(table_name)
        and indexname = lower(index_name);
    
      if l_count = 0 then 
         execute 'create index ' || index_name || ' on ' || table_name || '(' || column_name || ')';
      end if;
    end;
    $$ LANGUAGE plpgsql;
    

    usage: select create_index('my_table', 'my_index_name', 'id');

提交回复
热议问题