EDIT: do not use, execution time increases quadratically
It's a pity that the runtime is so bad, because the syntax was very elegant.
I'm leaving this answer up to save others from going down this path.
This answer is different from the rest because
you don't have to repeat the join condition.
- You join once in the FROM clause
- and the WHERE clause checks that rows from X are present in (X as X_joined join Y).
As a result this works with natural joins, which is very nice.
Example query
Say that you have a table shipment
that you want to augment with information from table vehicle
, and both tables have a column vehicle_id
so you can use NATURAL JOIN
.
---- DO NOT USE, quadratic runtime ----
EXPLAIN UPDATE shipment
SET shipment.speed = vehicle.average_speed
FROM
shipment s_joined NATURAL JOIN vehicle
WHERE
-- This is the magic condition
-- (EDIT: ... it probably causes the quadratic runtime, too)
shipment = s_joined
-- any further limitations go here:
AND shipment.destination = 'Perth'
Minimal working example
-- A table with shipments, some with missing speeds
create temporary table shipment (
vehicle_id varchar(20),
cargo varchar(20),
speed integer
);
insert into shipment values
('cart', 'flowers', 60),
('boat', 'cabbage', null),
('cart', 'potatos', null),
('foot', 'carrots', null);
-- A table with vehicles whose average speed we know about
create temporary table vehicle (
vehicle_id varchar(20),
average_speed integer
);
insert into vehicle values
('cart', 6),
('foot', 5);
-- If the shipment has vehicle info, update its speed
---- DO NOT USE, quadratic runtime ----
UPDATE shipment
SET speed = vehicle.average_speed
FROM shipment as s_joined natural join vehicle
WHERE shipment = s_joined
AND shipment.speed is null;
-- After:
TABLE shipment;
┌────────────┬─────────┬───────┐
│ vehicle_id │ cargo │ speed │
├────────────┼─────────┼───────┤
│ cart │ flowers │ 60 │ <- not updated: speed was not null
│ boat │ cabbage │ │ <- not updated: no boat in join
│ cart │ potatos │ 6 │ <- updated
│ foot │ carrots │ 5 │ <- updated
└────────────┴─────────┴───────┘