I have a simple tag table in Postgres 9.3:
CREATE TABLE tag (
id SERIAL PRIMARY KEY,
text TEXT NOT NULL UNIQUE
);
Currently I can insert a new tag and get back the new id easily enough:
INSERT INTO tag (text) VALUES ('hey') RETURNING id
However I would like to check that the tag doesn't already exist (unique constraint) and if it does exist, return the id of the existing tag.
I attempted to use COALESCE
to achieve this:
SELECT COALESCE(
(SELECT id FROM tag WHERE text='hey'),
(INSERT INTO tag (text) VALUES ('hey') RETURNING id)
)
But unfortunately while I believe this logic is sound it doesn't look like I can have an INSERT
statement in a COALESCE
(generates a syntax error at INTO
).
What's the easiest way to accomplish this?