Re: ON CONFLICT and WHERE

From: Tom Lane <tgl(at)sss(dot)pgh(dot)pa(dot)us>
To: Adrian Klaver <adrian(dot)klaver(at)aklaver(dot)com>
Cc: pgsql-general <pgsql-general(at)postgresql(dot)org>, Peter Geoghegan <pg(at)bowt(dot)ie>
Subject: Re: ON CONFLICT and WHERE
Date: 2022-11-13 21:07:44
Message-ID: 736683.1668373664@sss.pgh.pa.us
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general

Adrian Klaver <adrian(dot)klaver(at)aklaver(dot)com> writes:
> INSERT INTO books VALUES (12, 0, CURRENT_TIMESTAMP)
> ON CONFLICT (id)
> WHERE updated IS NULL OR updated + INTERVAL '2min' < CURRENT_TIMESTAMP
> DO UPDATE
> SET version = books.version + 1, updated = CURRENT_TIMESTAMP;

> I have not used WHERE with ON CONFLICT myself so it took longer then I
> care to admit to correct the above to:

> INSERT INTO books VALUES (12, 0, CURRENT_TIMESTAMP)
> ON CONFLICT (id)
> DO UPDATE
> SET version = books.version + 1, updated = CURRENT_TIMESTAMP
> WHERE books.version IS NULL OR books.updated + INTERVAL '2min' <
> CURRENT_TIMESTAMP;

> The question is why did the first case just ignore the WHERE instead of
> throwing a syntax error?

A WHERE placed there is an index_predicate attachment to the ON CONFLICT
clause. It doesn't have any run-time effect other than to allow partial
indexes to be chosen as arbiter indexes. TFM explains

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.

This strikes me as a bit of a foot-gun. I wonder if we should make
it safer by insisting that the resolved index be partial when there's
a WHERE clause here. (This documentation text is about as clear as
mud, too. What does "inferred" mean here? I think it means "chosen as
arbiter index", but maybe I misunderstand.)

regards, tom lane

In response to

Responses

Browse pgsql-general by date

  From Date Subject
Next Message Adrian Klaver 2022-11-13 21:24:51 Re: ON CONFLICT and WHERE
Previous Message Ron 2022-11-13 20:54:54 Re: Setting up replication on Windows, v9.4