0

I have 3 arrays. For example :

let status = [1,2,3];
let name = ['Andrey','Vasya','Petia'];
let age = [23,45,54];

Also I have array of ids for each user which I want to update .

let id_list = [2323,3434,3434] 

I want to send postgres request by which I update this data in this way by one request :

UPDATE users SET status = '1' , name = 'Andrey', age = '23' WHERE id ='2323'
UPDATE users SET status = '2' , name = 'Vasya', age = '45' WHERE id ='3434'

etc .

All data I want to update in one request

1 Answer 1

6

First of all you must unnest your array:

WITH sample (id, name, status, age) AS (
    SELECT 
        * 
    FROM 
        --Using unnest function
        unnest(
            ARRAY[2323, 3434, 3434], 
            ARRAY['Andrey','Vasya','Petia'], 
            ARRAY[1,2,3], 
            ARRAY[23,45,54]
        )
)
--And then proceed to your update
UPDATE 
    users 
    SET status = s.status , name = s.name, age = s.age 
    FROM sample s
    WHERE users.id = s.id;

More info about unnest function here.

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

1 Comment

is it all one request ?

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.