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'));

                            })
}
1

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.