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

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

$
0
0

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 becauseyou 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 shipmentSET shipment.speed = vehicle.average_speedFROM    shipment s_joined NATURAL JOIN vehicleWHERE    -- 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 speedscreate 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 aboutcreate 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 shipmentSET   speed = vehicle.average_speedFROM  shipment as s_joined natural join vehicleWHERE 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└────────────┴─────────┴───────┘

Viewing all articles
Browse latest Browse all 19

Trending Articles



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