I have a table:
CREATE TABLE mytable (id SERIAL, name VARCHAR(10) PRIMARY KEY)
Now I want to add names to this table, but only if they not exist in the table already, and in both cases return the id
. How can I do this with PostgreSQL?
I have seen a few scripts for this, but is there no single SQL-statement to do it?
E.g. I can INSERT and return id
with:
INSERT INTO mytable (name) VALUES ('Jonas') RETURNING id
it works the first time and returns id
. But it fails if Jonas
already exist in the table, but I want to return the id
even if the Insert fails. Is this possible to do with PostgreSQL?