A
A
Alexey Trigubin2021-01-26 15:06:14
PostgreSQL
Alexey Trigubin, 2021-01-26 15:06:14

How to update the data if it already exists and add it if it doesn't exist?

For example, look. There is a table with fields id and chtoto (array) and you need to check if it has a record with id 74291910, for example, and if so, then update the record, if not, add a record. Here is the request I got:

INSERT INTO table (id, chtoto) VALUES (74291910, array_append(chtoto, 'string') 
ON CONFLICT (id) DO UPDATE SET chtoto=array_append(chtoto, 'string')

But there is a problem with this - chtoto is specified many times. How it is possible to rewrite this request correctly?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Andrey Tsvetkov, 2021-01-26
@kirick29

INSERT INTO table (id, chtoto) VALUES (74291910, array_append(chtoto, 'string') 
ON CONFLICT (id) DO UPDATE SET chtoto=EXCLUDED.chtoto

R
rrambo, 2021-01-26
@rrambo

first insert with a unique field - the record will not be added if it already exists.
and then the update request.
More precisely, it is better to change places, probably. at first to update records that already are, and then to add. there will be no duplicates since id is made as a unique field.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question