question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Question: Multi-insert statement

See original GitHub issue

Postgres supports something like: INSERT INTO foo(a,b) VALUES (q,r), (s,t) ...

How can I do this in node-postgres? Right now I’m using a transaction, and async.parallelLimit for individual INSERTs. But this seems rather inefficient, and it’s as I need it for a reasonably high-volume log – where every few seconds I need to insert quite a bit of data – performance matters.

So I’m wondering if there’s a better way. (And I happy to string concat my own query, but I don’t an escaping function exposed)

Issue Analytics

  • State:closed
  • Created 10 years ago
  • Comments:12 (2 by maintainers)

github_iconTop GitHub Comments

12reactions
kethinovcommented, Dec 25, 2016

The above needs a slight tweak in the middle to actually work:

var rows = [{
  name: 'Brian',
  age: 31
}, {
  name: 'Aaron',
  age: 29
}]

function buildStatement (insert, rows) {
  const params = []
  const chunks = []
  rows.forEach(row => {
    const valueClause = []
    Object.keys(row).forEach(p => {
      params.push(row[p])
      valueClause.push('$' + params.length)
    })
    chunks.push('(' + valueClause.join(', ') + ')')
  })
  return {
    text: insert + chunks.join(', '),
    values: params
  }
}

client.query(buildStatement('INSERT INTO foo(name, age) VALUES ', rows))

FYI for anyone reading the thread, buildStatement returns the following SQL:

{ statement: 'INSERT INTO foo(name, age) VALUES ($1, $2), ($3, $4)',
  params: [ 'Brian', 31, 'Aaron', 29 ] }
9reactions
brianccommented, Mar 12, 2014

You can still do this with a prepared statement, you’ll just have to build up the parameters and append them all to the query…something like:

var rows = [{
  name: 'Brian',
  age: 31
}, {
  name: 'Aaron',
  age: 29
}]

var buildStatement = function(rows) {
  var params = []
  var chunks = []
  for(var i = 0; i < rows.lenght; i++) {
    var row = rows[i]
    var valuesClause = []
    params.push(row.name)
    valueClause.push('$' + params.length)
    params.push(row.age)
    valueClause.push('$' + params.length)
    chunks.push('(' + valueClause.join(', ') + ')')
  }
  return {
    text: 'INSERT INTO foo(name, age) VALUES ' + chunks.join(', '),
    values: params
  } 
}

client.query(buildStatement(rows))

Something like that. I wrote it off the top of my head. There are also a myriad of query builders for node which should help make this much easier.

Read more comments on GitHub >

github_iconTop Results From Across the Web

Inserting multiple rows in a single SQL query? - Stack Overflow
In SQL Server 2008 you can insert multiple rows using a single SQL INSERT statement. INSERT INTO MyTable ( Column1, Column2 ) VALUES ......
Read more >
SQL Query to Insert Multiple Rows - GeeksforGeeks
In this article, we see how to insert individual as well as multiple rows in a database using the INSERT statement in the...
Read more >
How to INSERT Multiple Records in SQL - DigitalOcean
The SQL UNION query helps to select all the data that has been enclosed by the SELECT query through the INSERT statement.
Read more >
How to Insert Multiple Rows in SQL - Database Star
This works in all database vendors. INSERT INTO customer (first_name, last_name) SELECT fname, lname FROM list_of_customers WHERE active = 1;
Read more >
How to Insert Multiple Rows in a Single SQL Query
Answer: Writing a code to insert multiple rows in a single SQL query is not a difficult task, but it is indeed a...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found