How can I find the last insert ID with Node.js and Postgresql?

The key here is using RETURNING id in your INSERT query.

The pg wiki has an example that shows how this is done.

// Let's pretend we have a user table with the 'id' as the auto-incrementing primary key
var queryText="INSERT INTO users(password_hash, email) VALUES($1, $2) RETURNING id"
client.query(queryText, ['841l14yah', 'test@te.st'], function(err, result) {
  if (err) //handle error
  else {
    var newlyCreatedUserId = result.rows[0].id;
  }
});

or with async/await:

const result = await client.query(queryText, ['841l14yah', 'test@te.st']);
const newlyCreatedUserId = result.rows[0].id;

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)