0

I have 4 tables need to update likewise ( need to update around 50 records in each table hence 50 update queries each):

table1:

id website_id   other_column
1   14            33
2   12            90
3   56            51
....

same for table2, .....

Need to update website_id by other new website_id

for example: 14 need to replace with 67,

12 need to replace with 34 ,

56 need to replace with 92,

likewise....

Note: I have a data regarding which website_id need to replace with which new website_id.

Around 50 multiply by 4 = 200 update queries is not a feasible solution!

What is the feasible way other than executing multiple update queries?

2
  • Sorry for incomplete question previously, now updated. Thanks! Commented Oct 10, 2018 at 12:15
  • 1
    If you want to the same update or calculation it's easy to update multiple rows at the same time. It all depends on what you do/don't put in the WHERE clause. If your updates are all different, then there's nothing wrong with multiple statements. You need all the specifics changes no matter what. Single statement doesn't make it any easier. Commented Oct 10, 2018 at 12:25

2 Answers 2

1

You can update all tables in a single data modifying CTE which also means you only need to specify the replacements once:

with replacement (old_id, new_id) as (
  values 
     (12, 34),
     (56, 92), 
     .... other old/new mappings ...
     (14, 67)
), t1_update as (
  update t1 
    set website_id = r.new_id
  from replacement r
  where r.old_id = t1.website_id
), t2_update as (
  update t2
    set website_id = r.new_id
  from replacement r
  where r.old_id = t2.website_id
), t3_update as (
  update t3
    set website_id = r.new_id
  from replacement r
  where r.old_id = t3.website_id
)
update t4
  set website_id = r.new_id
from replacement r
where r.old_id = t4.website_id;

Online example: https://rextester.com/OQI6307

Sign up to request clarification or add additional context in comments.

Comments

0

Could look something like this. Can be made dynamic by looping through the rows/tables in table_mapped_changes.

UPDATE
    table1
SET
    id = c.new_id
FROM
    table_mapped_changes c
ON 
    id = c.old_id AND
    c.table_name = 'table1'

2 Comments

Can you provide the Postgres documentation that says, do not repeat the target table ....?
postgresql.org/docs/current/static/sql-update.html - see the from_list explanation "Note that the target table must not appear in the from_list, unless you intend a self-join"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.