Skip to content
Advertisement

PostgreSQL CTE UPDATE-FROM query skips rows

2 tables

table_1 rows: NOTE: id 2 has two rows

table_2 rows

Query:

When i ran above query i got table_2 output as

I noticed that above update query is considering only 1st match and skipping rest.

I can make it work by changing the query like below. Now the table_2 updates as expected since there are no duplicate rows from table_1.

But i would like to know why my previous query is not working. Is there anything wrong in it?

Schema

Advertisement

Answer

The problem is that an UPDATE in PostgreSQL creates a new version of the row rather than changing the row in place, but the new row version is not visible in the snapshot of the current query. So from the point of view of the query, the row “vanishes” when it is updated the first time.

The documentation says:

When a FROM clause is present, what essentially happens is that the target table is joined to the tables mentioned in the from_list, and each output row of the join represents an update operation for the target table. When using FROM you should ensure that the join produces at most one output row for each row to be modified. In other words, a target row shouldn’t join to more than one row from the other table(s). If it does, then only one of the join rows will be used to update the target row, but which one will be used is not readily predictable.

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