SELECT or INSERT a row in one command

前端 未结 4 1924
囚心锁ツ
囚心锁ツ 2020-12-07 20:28

I\'m using PostgreSQL 9.0 and I have a table with just an artificial key (auto-incrementing sequence) and another unique key. (Yes, there is a reason for this table. :)) I w

4条回答
  •  萌比男神i
    2020-12-07 21:10

    using 9.5 i successfully tried this

    • based on Denis de Bernardy's answer
    • only 1 parameter
    • no union
    • no stored procedure
    • atomic, thus no concurrency problems (i think...)

    The Query:

    WITH neworexisting AS (
        INSERT INTO mytable(other_key) VALUES('hello 2') 
        ON CONFLICT(other_key) DO UPDATE SET existed=true -- need some update to return sth
        RETURNING * 
    )
    SELECT * FROM neworexisting
    

    first call:

    id|other_key|created            |existed|
    --|---------|-------------------|-------|
     6|hello 1  |2019-09-11 11:39:29|false  |
    

    second call:

    id|other_key|created            |existed|
    --|---------|-------------------|-------|
     6|hello 1  |2019-09-11 11:39:29|true   |
    

    First create your table ;-)

    CREATE TABLE mytable (
        id serial NOT NULL,
        other_key text NOT NULL,
        created timestamptz NOT NULL DEFAULT now(),
        existed bool NOT NULL DEFAULT false,
        CONSTRAINT mytable_pk PRIMARY KEY (id),
        CONSTRAINT mytable_uniq UNIQUE (other_key) --needed for on conflict
    );
    

提交回复
热议问题