Quantcast
Channel: How to do an update + join in PostgreSQL? - Stack Overflow
Viewing all articles
Browse latest Browse all 19

Answer by Marmite Bomber for How to do an update + join in PostgreSQL?

$
0
0

Some care should be taken if the join is performed on a non-unique column. I.e. the result of the join produces more values that can be used in the update.

Some RDMS raise an exception is this case, but PostgreSQL apparently performs the update with a non deterministic outcome.

Example

Tested on 14.1

create table tab asselect * from  (values(1,'a'),(2,'b') ) t(id, att);

We use a CTE where the id = 1 id giving two possible values for the update. Using the order by in the CTE we get a different results.

with t as ( select * from  (values(1,'c'),(1,'d') ) t(id, att)order by 2   /* Based on this order different update is performed */)update tab set att = t.attfrom twhere tab.id = t.id

With the ascendig order the column is updated to the value of d (highest value)

id|att|--+---+ 1|d  | 2|b  |

while using a descending order in the CTE the column is updated to the value of c (lowest value)

id|att|--+---+ 1|c  | 2|b  |

The moral of the story always check if the join produce a unique result.

The relevant part of the documentation

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.


Viewing all articles
Browse latest Browse all 19

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>