Skip to content
Advertisement

PostgreSQL UPSERT (INSERT … ON CONFLICT UPDATE) fails

I have a row in my postgresql database that I want to update.

My code generates this SQL statement to insert else update the one field that’s changed:

What I don’t understand is that I can select that one row and it is present with a non-NULL num_syncs. But the UPSERT is failing because it doesn’t (re)set num_syncs (value 4 unchanged).

Anyone see what I’m missing?

Fwiw, the table definition is this:

Advertisement

Answer

The NOT NULL constraints are checked first. That makes sense, because they must be satisfied for an INSERT to succeed.

If you know for sure that there is already a matching row, use a regular UPDATE.

An alternative might be to use a CHECK (colname IS NOT NULL) constraint instead of NOT NULL.

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