Multi-table JOIN with UPDATE creates questionable query #1967
Replies: 1 comment 2 replies
-
The Sequel behavior is expected, and I think the PostgreSQL behavior is as well. When you select from multiple tables, SQL treats that as an implicit CROSS JOIN, so if you don't add your own filter conditions, you get the CROSS JOIN equivalent, and for UPDATE, that means it uses the first row returned by the CROSS JOIN. This behavior could be documented better on the Sequel side, though. We could put it in |
Beta Was this translation helpful? Give feedback.
-
I am not sure if this is a Sequel issue per-se, it's rather some surprising (to me) Postgres behavior, but I wanted to see your take on it.
Assuming a structure like this:
I want to, in a single statement, set the immutable_quantity and cart_item_id. So I wrote the Sequel to do so:
And this generates the SQL, which at first looked fine to me:
The issue is that the
immutable_quantity
column gets set to the value of the first cart item row's quantity (ieSELECT quantity FROM commerce_cart_items
). This was... surprising! And hard to find in unit tests since it requires additional data...So the fix is adding the join condition to the where:
Which produces this SQL:
I have read the Postgres UPDATE docs and the explanation is pretty subtle, but it is covered in the examples (https://www.postgresql.org/docs/current/sql-update.html).
There is not a ton of documentation/examples on using Sequel with UPDATE FROM, so I wanted to mention this caveat here. Some of the examples I found are even incorrect with the above bug.
I know this is not a Sequel bug, but I wanted to check if I'm perhaps using
from/update
incorrectly, or if there's some way to automatically add the correct join criteria that I added explicitly above (I do have these things modeled correctly with associations but I'm not sure if that matters here).Beta Was this translation helpful? Give feedback.
All reactions