0

Suppose I want to insert multiple rows into a table in PostregSQL. The example below shows how to do that using only one row, but what if I want to insert several rows? How to do that? If I have several names with the same email?

const text = 'INSERT INTO users(name, email) VALUES($1, $2) RETURNING *'
const values = ['brianc', 'brian.m.carlson@gmail.com']

// promise
client
  .query(text, values)
  .then(res => {
    console.log(res.rows[0])
    // { name: 'brianc', email: 'brian.m.carlson@gmail.com' }
  })
  .catch(e => console.error(e.stack))

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
Aerodynamika
  • 7,883
  • 16
  • 78
  • 137
  • 2
    are you looking for a js solution, or a postgres solution? in postgres, it is simply, `insert into users(name, email) values('foo', 'foo@email.com') ('bar', 'bar@email.com'), ('qux', 'qux@email.com')`. – marmeladze Oct 22 '21 at 13:18
  • well actually i'm looking for a js solution where i could insert several rows of values without bloating the request for readability. thanks! – Aerodynamika Oct 22 '21 at 13:51
  • 1
    does [this](https://stackoverflow.com/questions/34990186/how-do-i-properly-insert-multiple-rows-into-pg-with-node-postgres) answer your question? – marmeladze Oct 22 '21 at 13:56
  • 1
    Does this answer your question? [How do I properly insert multiple rows into PG with node-postgres?](https://stackoverflow.com/questions/34990186/how-do-i-properly-insert-multiple-rows-into-pg-with-node-postgres) – Pooya Oct 22 '21 at 16:57
  • @marmeladze yes, this is exactly what I was looking for, `pg-format` is great. will be great if you want to post it as an answer, so I can accept it! thank you for your help! – Aerodynamika Oct 22 '21 at 17:13

0 Answers0