i have a upsert statement (http://www.the-art-of-web.com/sql/upsert/) doing an insert whenever a row with id does not exist and updating the column when the row exists :
WITH upsert AS
(UPDATE foo SET counter=counter+1 WHERE id='bar' RETURNING *)
INSERT INTO foo(id, counter) SELECT 'bar', 0
WHERE NOT EXISTS (SELECT * FROM upsert) RETURNING counter;
id is the primary key column (as expected). until here everything works fine.
but there is a 3rd column 'position' which can be used for custom ordering. in case of an update i want to keep the current value.
but the insert statement needs an additional subquery returning the lowest possible position not in use:
WITH upsert AS
(UPDATE foo SET counter=counter+1 WHERE id='bar' RETURNING *)
INSERT INTO foo(id, counter, position) SELECT 'bar', 0, MIN( position)-1 from foo
WHERE NOT EXISTS (SELECT * FROM upsert) RETURNING counter;
using this statement i get an error
ERROR: duplicate key value violates unique constraint "id"
whats wrong here ?