Skip to content
Advertisement

SQL – Update multiple tables, the same column across one query

I have a postgres database

There are 3 tables, I’m trying to make a sql UPDATE statement that updates an active column in each table.

Table1 has a field record that looks like this:

table1_id: 40b77068-4693-4593-8ea9-996501414101
table1_name: Digital Only
active: false

Table2

table2_id: [some randomId we don't care about]
table1_fk: 40b77068-4693-4593-8ea9-996501414101
active: false

Table3 is the same as table 2

table2_id: [some randomId we don't care about]
table1_fk: 40b77068-4693-4593-8ea9-996501414101
active: false

I need a query that looks for the name “Digital Only” and it’s ID on table1. Update it’s active column. Update corresponding active columns in the 2 other tables matching the original ID in table1

The tables have pretty long names so ideally I want to alias them:

So far I have something along the lines of this in pseudocode

UPDATE a.active, b.active, c.active
INNER JOIN
FROM table1 a, table2 b, table3 c
SET a.active=true, b.active=true, c.active=true
WHERE a.active=true, b.active=true, c.active=true

Not sure how to do this. The table relationships look like this: enter image description here

Advertisement

Answer

I think this does what you want. The idea is first update table1, and to use the returning clause to return the table1_id, that can be used to update the two other tables:

with 
    t1 as (
        update table1
        set active = true
        where table1_name = 'Digital Only'
        returning table1_id
    ),
    t2 as (
        update table2
        set active = true
        from t1
        where table1_fk = t1.table1_id
    )
update table3
set active = true
from t1
where table1_fk = t1.table1_id
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement