I have table stock_price_code
as below. value
column has a UNIQUE
constraint.
create table stock_price_code (
id serial primary key,
value text not null,
unique (value)
);
I want to INSERT
into table, if no record found for value
. I have these 2 queries:
-- query 1
INSERT INTO stock_price_code (value)
SELECT 'MCD'
WHERE NOT EXISTS (SELECT * FROM stock_price_code WHERE value = 'MCD')
RETURNING id;
-- query 2
INSERT INTO stock_price_code (value) VALUES ('MCD')
ON CONFLICT (value) DO NOTHING
RETURNING id;
I was using query 1
before Postgres 9.5. Then Postgres 9.5 started introducing INSERT ... ON CONFLICT ...
feature. If I substitude query 1
with query 2
, is there any known side effect or perfomance issue? Thanks.
query 2 will work if a row gets inserted between SELECT 'MCD' WHERE NOT EXISTS (SELECT * FROM stock_price_code WHERE value = 'MCD')
and INSERT INTO stock_price_code (value)
, while query 1 will fail with duplicate.
The overhead of ON CONFLICT
I believe is smaller then WHERE NOT EXISTS
, not sure though
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加