1

What is the easiest way to insert a row in a database and returning its id if that row doesn't exist, otherwise return the ID of that word?

 INSERT INTO mytable (name) 
 SELECT 'd' 
 WHERE NOT EXISTS (SELECT id FROM mytable WHERE name='d') 
 RETURNING id

This code works only if the row doesn't exist.

I either do that and then a SELECT, or try the INSERT with ON CONFLICT DO NOTHING and then a SELECT again.

Is there a better solution?

a_horse_with_no_name
  • 440,273
  • 77
  • 685
  • 758
maugch
  • 1,208
  • 1
  • 20
  • 42

0 Answers0