CREATE UNIQUE INDEX IF NOT EXISTS in postgreSQL

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

    If you are still stuck in previous versions, I would recommend not using count, but just the query directly in your if condition. Makes the code simpler. You can try something like this:

    do 
    $$
    begin
    if not exists (
        select indexname
            from pg_indexes
        where schemaname = 'schemaname'
            and tablename = 'tablename'
            and indexname = 'indexname'
    )
    then
        create unique indexname (...);
    end if;
    end 
    $$;
    

提交回复
热议问题