Write a Postgres Get or Create SQL Query

前端 未结 4 980
佛祖请我去吃肉
佛祖请我去吃肉 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:59

    In a SQL DBMS, the select-test-insert approach is a mistake: nothing prevents another process from inserting the "missing" row between your select and insert statements. Do this instead:

    insert into mytable (color, brightness, size, age)
    select color, brightness, size, age 
    from mytable
    where not exists (
        select 1 from 
        from mytable
        where color = 'X' and brightness = 'Y'
    );
    SELECT (color, brightness, size, age) 
    FROM mytable 
    WHERE color = 'X' AND brightness= 'Y';
    

    You should be able to pass that entire text as a single "query" to the DBMS. You might want to consider making it into a stored procedure.

提交回复
热议问题