How to have Postgres return id when ON CONFLICT DO NOTHING
3
votes
1
answer
3499
views
Suppose we have the following table:
CREATE TABLE names(
id SERIAL NOT NULL,
CONSTRAINT names__pk PRIMARY KEY(id),
name TEXT NOT NULL,
CONSTRAINT names__name__unq UNIQUE(name)
);
INSERT INTO names(name)
VALUES('apple')
ON CONFLICT(name) DO NOTHING
RETURNING id;
When a row does not exist,
RETURNING
clause works, but if there already is a row, the query returns nothing. Is there a way to modify the query so that it always returns the field id
?
Asked by user14381362
(133 rep)
May 9, 2024, 01:24 PM
Last activity: May 10, 2024, 02:40 PM
Last activity: May 10, 2024, 02:40 PM