Search code examples
node.jspostgresqlpg

Inserting multiple values to PostreSQL - pg


I have 2 variables:

let x = 2;
let y = [1,3,4];

I want to write this data to users table like following:

user1 - user2
+---+---+
| 2 | 1 |
+---+---+
| 2 | 3 |
+---+---+
| 2 | 4 |
+---+---+

I have a client object to make queries that I don't know how to give values and query?:

Client.query("INSERT INTO users (user1, user2) VALUES ($1, $2)", []);

Solution

  • Something like this?

    INSERT INTO users (user1, user2)
    SELECT  2 AS user1
        ,   UNNEST(ARRAY[1,3,4]) AS user2;
    

    I'm not familiar with node.js, can't help you there.