Partial Index not used in ON CONFLICT clause while performing an upsert in Postgresql

爷,独闯天下 提交于 2019-11-29 14:19:55

You have to use an index predicate to use a partial unique index. Read in the documentation:

index_predicate

Used to allow inference of partial unique indexes. Any indexes that satisfy the predicate (which need not actually be partial indexes) can be inferred. Follows CREATE INDEX format.

In this case:

INSERT INTO key_value_pair (key, value, is_active) VALUES ('temperature','20', false) 
ON CONFLICT (key) WHERE is_active
DO UPDATE
SET value = '33', is_active = true;

Another example:

> users
id |  name   |  colour  |  active
---+---------+----------+--------
1  | 'greg'  |  'blue'  |  false
2  | 'kobus' |  'pink'  |  true

--------------------------------------------------------------------------
CREATE UNIQUE INDEX index_name
  --columns applicable to partial index
  ON users (name, colour)
  --partial index condition   **
  WHERE not active

--------------------------------------------------------------------------
INSERT INTO users (name, colour, active)
    --multiple inserts
VALUES ('greg', 'blue', false),  --this already exists for [false], conflict
       ('pieter', 'blue', true),  
       ('kobus', 'pink', false)  --this already exists for [true], no conflict
ON CONFLICT (name, colour)
    --partial index condition  **same as original partial index condition
WHERE not active
    --conflict action
  DO UPDATE SET
        active = not EXCLUDED.active
        --on conflict example, change some value, i.e. update [active]

Row where name = greg and colour = blue for active = false will now be updated to active = true, the rest will be inserted

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