Re: On insert duplicate row, return existing key

Started by Nickover 15 years ago2 messagesgeneral
Jump to latest
#1Nick
nboutelier@gmail.com

Anyone? Please

Show quoted text

On Jul 31, 12:36 pm, Nick <nboutel...@gmail.com> wrote:

If I insert a duplicate row into a table, id like to return the
existing key.

I tried creating a rule for this...

CREATE RULE no_duplicates AS ON INSERT TO names WHERE EXISTS (SELECT 1
FROM names WHERE new.name = name) DO INSTEAD SELECT id, name FROM
names WHERE name = new.name;

However, I get an error on...

INSERT INTO names (name) VALUES ('existing') RETURNING *;

ERROR:  cannot perform INSERT RETURNING on relation "names"
HINT:  You need an unconditional ON INSERT DO INSTEAD rule with a
RETURNING clause.

#2Craig Ringer
craig@2ndquadrant.com
In reply to: Nick (#1)

On 05/08/10 06:03, Nick wrote:

Anyone? Please

It's probably going to be a lot easier to do this with a stored
procedure. I don't rate your chances of making it work with a rule.
Rules work more like a macro system, and I'm not sure they can be
convinced to do what you're trying to do.

--
Craig Ringer