Write a Postgres Get or Create SQL Query

前端 未结 4 1000
佛祖请我去吃肉
佛祖请我去吃肉 2021-02-13 12:42

I want to write a single Postgres SQL statement that says look for a user with color X and brightness Y. If that user exists, return all of its row data. If not, create a new

4条回答
  •  时光取名叫无心
    2021-02-13 12:58

    Adding my solution here. It is a tad different than @Clodoaldo Neto and @astef's solutions.

    WITH ins AS (
      INSERT INTO mytable (color, brightness, size, age)
      VALUES ('X', 'Y', 'big', 'old')
      ON CONFLICT (color) DO NOTHING
      RETURNING *
    )
    SELECT * FROM ins
    UNION
    SELECT * FROM mytable
      WHERE color = 'X';
    

    I found astef's solution inadequate for my purposes: it doesn't perform the "get" portion of "get or create"! If the value already existed, nothing would happen.

    The union at the end of the statement ensures that if the value was not inserted (since it already existed) we still retrieve that value from the table.

提交回复
热议问题