JRehkemper.de

Update a Joined Table in PostgreSQL

If you joined two tables and need to update one of them, there are multiple ways to do so.

Select Query

My Example uses a join to lookup a name to an id.

SELECT
	a.id
	b.name
	a.value1
	a.value2
FROM tablea a
JOIN tableb b
ON a.id = b.id;

Using Subquery

One approach is to use a subquery.

UPDATE tablea a
SET
	value1 = 1,
	value2 = 2
WHERE
	a.id = (SELECT "id" FROM tableb WHERE "name" = 'John');

Using Joined Update

You can also join while doing the update.

UPDATE tablea a
SET
	value1 = 1,
	value2 = 2
FROM tableb b
WHERE
	a.id = b.id
	AND
	b.name = 'John';

The FROM in this context is initiating the join.

profile picture of the author

Jannik Rehkemper

I'm an professional Linux Administrator and Hobby Programmer. My training as an IT-Professional started in 2019 and ended in 2022. Since 2023 I'm working as an Linux Administrator.