Skip to content
Advertisement

PostgreSQL Partial Indexes and UPSERT

After googling a lot my question is described below:

Attempting to insert values:

Results in:

Altho this works(per spec):

PostgreSQL documentation stands that it should work

PostgreSQL v9.5

My aim is to find way to create unique index on this table on multiple nullable columns and update old rows with new ones on UPSERT

Advertisement

Answer

The conflict_target used in on conflict must identify an existing unique index. You cannot use

because you have no index on the three columns. Postgres is not so smart to combine multiple indexes to satisfy your conflict target.

You can however create a single partial index like this one:

Now you can use the three columns as a conflict target:

Note the use of the special record excluded. For the documentation:

The SET and WHERE clauses in ON CONFLICT DO UPDATE have access to the existing row using the table’s name (or an alias), and to rows proposed for insertion using the special excluded table.

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement