A
A
Alexander Afanasiev2018-02-28 10:05:52
PostgreSQL
Alexander Afanasiev, 2018-02-28 10:05:52

How to update table records by pairs old value -> new value?

There is a table and a dozen records:

CREATE TABLE test
(
  id serial,
  target_id integer
);
INSERT INTO test (1, 1206);
INSERT INTO test (1, 1210);
INSERT INTO test (1, 1211);
INSERT INTO test (1, 1250);

and I have pairs of values ​​"on hand" (let it be an array):
1206=>1281,
1210=>1282,
1211=>1283,
1250=>1287

can I somehow replace 1206 in the table with 1281 and further down the list a simple or complex query without running as many queries as there are pairs of values?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
0
0xD34F, 2018-02-28
@XanderEVG

UPDATE test SET
  target_id = t.new_id
FROM (
  SELECT
    unnest(ARRAY[1206, 1210, 1211, 1250]) AS old_id,
    unnest(ARRAY[1281, 1282, 1283, 1287]) AS new_id
) AS t
WHERE target_id = t.old_id

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question