I have a very simple upsert I am trying to make work but unsuccessfully so far.
Consider the table:
CREATE TABLE bla(id TEXT PRIMARY KEY, data INT);
and the insert:
INSERT INTO bla(id, data) VALUES('12wed', 23) RETURNING (id);
And so far so good.
The logic I am trying to implement though is the following:
if no record with id=id:
insert and return id,
else:
do nothing
I tried
INSERT INTO bla(id, data) VALUES('12wed', 23)
RETURNING (id)
ON CONFLICT(id) DO NOTHING;
But I get the following error:
ERROR: syntax error at or near "ON"
LINE 3: ON CONFLICT(id) DO NOTHING;
You made a mistake with the expression. The correct version:
INSERT INTO bla(id, data) VALUES('12wed', 23)
ON CONFLICT(id) DO NOTHING
RETURNING (id);
It's exactly what you want:
hh=# INSERT INTO bla(id, data) VALUES('12wed', 23) ON CONFLICT(id) DO NOTHING RETURNING (id);
id
----
(0 rows)
INSERT 0 0
hh=# INSERT INTO bla(id, data) VALUES('12wed_new', 23) ON CONFLICT(id) DO NOTHING RETURNING (id);
id
--------
12wed_new
(1 row)
INSERT 0 1
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.