0

I have a unique column. I want to insert a row if it's not already there, and then return the id of that row.

INSERT INTO t(a) VALUES ('a') ON CONFLICT DO NOTHING RETURNING t.id;

returns nothing at all. Here's a fiddle.
I'm looking for how to get 1 each time, whether 'a' was newly inserted or not.

Hatshepsut
  • 5,962
  • 8
  • 44
  • 80

1 Answers1

4
with i as (
    INSERT INTO t(a) VALUES ('a') ON CONFLICT (a) DO NOTHING RETURNING id
)
select id from i
union all
select id from t where a = 'a'
limit 1
Clodoaldo Neto
  • 118,695
  • 26
  • 233
  • 260