I’m trying to create an insert script to insert multiple rows and using "exists" condition, but it’s returning me an error, and I don’t know why,
I have a query like this:
INSERT INTO films (id, code, title, did, date_prod, kind) VALUES
(1, 'B6717', 'Tampopo', 110, '1985-02-10', 'Comedy'),
(2, 'HG120', 'The Dinner Game', 140, DEFAULT, 'Comedy'),
(3, 'HG770', 'The Tampopo', 140, DEFAULT, 'Comedy')
WHERE NOT EXISTS (SELECT 1 FROM films WHERE code in ('B6717', 'HG120', 'HG770')
AND NOT EXISTS (SELECT 1 FROM films WHERE id in (1,2,3));
I would like to know why this query is not possible, and the correct way to insert multiple rows using multiple "exists" conditions
2
Answers
The way you do this is by placing a unique constraint on
code
:Then you can use
INSERT ... ON CONFLICT
:You can use the upsert operation to insert multiple rows without using the EXISTS condition
The following query may help to insert multiple rows into your table.
The query is as follows :
The following query will attempt to insert a row into the films table with the specified values and if there is a conflict it will perform an update on the conflicting row instead.