0

i have to "UPDATE" data in postgresql if data is already present in database and "INSERT" i.e create a new user_Id and insert data using IF condition. i have tried with this but i am not getting output. please help me if you know .

if(data.Details){
    db.query('UPDATE Details SET fullName = $2,address= $3,phone = $4 WHERE user_id = $1 RETURNING *', [query, data.Details.fullName, data.Details.address, data.Details.phone],function(err,details) {
                if (err) return callback(new Error('error'));
             })
}else{
db.query('INSERT INTO Details(user_id,fullName,address,phone) VALUES($1,$2,$3,$4) RETURNING *', [query, data.Details.fullName, data.Details.address, data.Details.phone],function(err,details) {
                                if (err) return callback(new Error('error'));

                            })
}
e4c5
  • 52,766
  • 11
  • 101
  • 134
katy
  • 15
  • 3
  • 2
    Possible duplicate of [Insert, on duplicate update in PostgreSQL?](http://stackoverflow.com/questions/1109061/insert-on-duplicate-update-in-postgresql) – vitaly-t May 11 '17 at 12:19

1 Answers1

1

If you want to get fancy, you can also use UPSERT/ON CONFLICT in Postgres 9.5 and later.

It is designed for this exact use case, and executes as a single "instruction", rather than having to do a query check whether something exists, and another one to update or insert, both in a transaction.

Horia Coman
  • 8,681
  • 2
  • 23
  • 25
  • actually upsert is way better than manually checking. because right after you "checked/selected" for a record, another request or client can insert it before this session. – ncank May 11 '17 at 21:23