Insert if not exists, else return id in postgresql

后端 未结 3 1931
無奈伤痛
無奈伤痛 2020-11-29 18:51

I have a simple table in PostgreSQL that has three columns:

  • id serial primary key
  • key varchar
  • value varchar

I have already see

相关标签:
3条回答
  • 2020-11-29 19:03

    And you can store value returned to variables in form of ... RETURNING field1, field2,... INTO var1, var2,...

    RETURNING will normally return a query which would return Error 'query has no destination for result data' if you call it in plpgsql without using its returned result set.

    0 讨论(0)
  • 2020-11-29 19:10

    Yes there is returning

    INSERT INTO tag ("key", "value")
    SELECT 'key1', 'value1'
    WHERE NOT EXISTS (
        SELECT id, "key", "value"
        FROM node_tag
        WHERE key = 'key1' AND value = 'value1'
        )
    returning id, "key", "value"
    

    To return the row if it already exists

    with s as (
        select id, "key", "value"
        from tag
        where key = 'key1' and value = 'value1'
    ), i as (
        insert into tag ("key", "value")
        select 'key1', 'value1'
        where not exists (select 1 from s)
        returning id, "key", "value"
    )
    select id, "key", "value"
    from i
    union all
    select id, "key", "value"
    from s
    

    If the row does not exist it will return the inserted one else the existing one.

    BTW, if the pair "key"/"value" makes it unique then it is the primary key, and there is no need for an id column. Unless one or both of the "key"/"value" pair can be null.

    0 讨论(0)
  • 2020-11-29 19:26
    with vals as (
      select 'key5' as key, 'value2' as value
    )
    insert into Test1 (key, value)
    select v.key, v.value
    from vals as v
    where not exists (select * from Test1 as t where t.key = v.key and t.value = v.value)
    returning id
    

    sql fiddle demo

    0 讨论(0)
提交回复
热议问题