I have two columns products/tmp_products
with following specification
(id bigint primary key ,price int not null,quantity int not null ,lastupdate timestamp)
I want sql to
Insert from tmp_products to products when id not in products.
Update only if (price or quantity) values are changed.
INSERT INTO products(id,price,quantity,lastupdate) SELECT (id,price,quantity,lastupdate) FROM tmp_products ON CONFLICT (id) DO UPDATE SET price=EXCLUDED.price, quantity=EXCLUDED.quantity, lastupdate=EXCLUDED.lastupdate where price!=EXCLUDED.price or quantity!=EXCLUDED.quantity;
I’m getting following error
column reference "price" is ambiguous
I want to know how to approach this problem?
Advertisement
Answer
The problem is in the where
clause. You need to qualify the columns so there are unambiguous:
INSERT INTO products(id,price,quantity,lastupdate) SELECT id,price,quantity,lastupdate FROM tmp_products ON CONFLICT (id) DO UPDATE SET price = EXCLUDED.price, quantity = EXCLUDED.quantity, lastupdate = EXCLUDED.lastupdate WHERE products.price <> EXCLUDED.price OR products.quantity <> EXCLUDED.quantity;
Note that you also need to remove the parentheses around the SELECT
, otherwise your query is not valid Postgres SQL, and would raise error INSERT has more target columns than expressions
.