0
WITH x AS (
   INSERT INTO users(name, age)
    SELECT 'john', 30
    WHERE NOT EXISTS (
       SELECT id FROM users WHERE name = 'john' 
    ) u
    RETURNING (CASE WHEN u.id > 0 THEN u.id ELSE id END)
)

SELECT * FROM x

How can I always return an id and if the id is not present, then insert it. Also, I need this to be in a CTE.

user962449
  • 3,377
  • 9
  • 36
  • 52
  • You may be interested in this: http://stackoverflow.com/questions/17267417/how-do-i-do-an-upsert-merge-insert-on-duplicate-update-in-postgresql. – Gordon Linoff Jun 05 '14 at 02:44
  • This is *not* about UPSERT, but rather obviously about INSERT / SELECT, something like this: http://stackoverflow.com/questions/15939902/is-select-or-insert-in-a-function-prone-to-race-conditions/15950324#15950324 – Erwin Brandstetter Jun 05 '14 at 04:00

0 Answers0