CREATE UNIQUE INDEX IF NOT EXISTS in postgreSQL

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

    You need some procedural code for this, something like this (untested!):

    do
    $$
    declare 
       l_count integer;
    begin
      select count(*)
         into l_count
      from pg_indexes
      where schemaname = 'public'
        and tablename = 'your_table'
        and indexname = 'your_index_name';
    
      if l_count = 0 then 
         execute 'create unique index public.your_index_name on public.your_table(id)';
      end if;
    
    end;
    $$
    

提交回复
热议问题