Partial Unique Index not working with on conflict clause PostgreSQL

一笑奈何 提交于 2020-12-15 05:27:10

问题


Table Structure:

create table example (a_id integer, b_id integer, c_id integer, flag integer);

Partial Index:

create unique index u_idx on example (a_id, b_id, c_id) where flag = 0;

My Code for upsert:

with a_ins_upd as (
    Insert into example (a_id, b_id, c_id, flag)
        select x.a_id, x.b_id, x.c_id, x.flag
        from <input_tableType> x
    on conflict (a_id, b_id, c_id) where flag = 0
    do update
    set
        a_id = excluded.a_id,
        b_id = excluded.b_id,
        c_id = excluded.c_id,
        flag = excluded.flag
returning *
)
insert into <some_other_table>

Result Entries, as of now : Input and Operations

Entry_1 is the data already in the table. Entry_2 , is the new input. The new input should update the Entry_1, rather than Inserting a new entry.

Where I am going wrong. I want the second entry to get updated, not Inserted.

I tried to include the flag as a part of the index. Then also, records are getting inserted. Does partial index not work with on conflict() clause?

How do I achieve this - I want to ignore the records with flag = 1, existing in the table (like blind to flag = 1), and do the merge operations on other records (the records which are having flag = 0, unique constraint remains on (a_id, b_id, c_id)). I thought of doing partial constraint/index and do on conflict. Seems tricky now.

来源:https://stackoverflow.com/questions/65142186/partial-unique-index-not-working-with-on-conflict-clause-postgresql

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!