Full answer
CREATE TABLE members (email TEXT PRIMARY KEY, name TEXT);
INSERT INTO members VALUES ('a@x.com', 'Ana');The query as written:
INSERT INTO members VALUES ('a@x.com', 'Ana Lopez'), ('b@x.com', 'Ben'), ('b@x.com', 'Benjamin') ON CONFLICT DO NOTHING;
SELECT changes() AS inserted, (SELECT COUNT(*) FROM members) AS total;| inserted | total |
|---|---|
| 1 | 2 |
Three rows were sent and only one was inserted. 'a@x.com' already existed and the second 'b@x.com' collided with the first; neither raised an error, and Ana's new surname was also silently ignored.
A corrected version:
CREATE TABLE import_rejects (email TEXT, name TEXT);
INSERT INTO import_rejects SELECT column1, column2 FROM (VALUES ('a@x.com', 'Ana Lopez'), ('b@x.com', 'Ben'), ('b@x.com', 'Benjamin')) v WHERE EXISTS (SELECT 1 FROM members m WHERE m.email = v.column1) OR (SELECT COUNT(*) FROM (VALUES ('a@x.com'), ('b@x.com'), ('b@x.com')) w WHERE w.column1 = v.column1) > 1;
SELECT * FROM import_rejects ORDER BY email, name;| name | |
|---|---|
| a@x.com | Ana Lopez |
| b@x.com | Ben |
| b@x.com | Benjamin |
Checked against the same batch, the query lists every row involved in a conflict: Ana's new version, which collides with the existing row, and both Ben rows, which collide with each other (the first was inserted and the second skipped). In practice, load the file into a staging table first, find duplicates and existing keys with SQL, and only then insert, reporting counts for inserted, updated and rejected rows. Choose DO UPDATE when newer values should win.
CREATE TABLE members (email TEXT PRIMARY KEY, name TEXT);
INSERT INTO members VALUES ('a@x.com', 'Ana');
INSERT INTO members VALUES ('a@x.com', 'Ana Lopez'), ('b@x.com', 'Ben'), ('b@x.com', 'Benjamin') ON CONFLICT DO NOTHING;
SELECT changes() AS inserted, (SELECT COUNT(*) FROM members) AS total;
CREATE TABLE import_rejects (email TEXT, name TEXT);
INSERT INTO import_rejects SELECT column1, column2 FROM (VALUES ('a@x.com', 'Ana Lopez'), ('b@x.com', 'Ben'), ('b@x.com', 'Benjamin')) v WHERE EXISTS (SELECT 1 FROM members m WHERE m.email = v.column1) OR (SELECT COUNT(*) FROM (VALUES ('a@x.com'), ('b@x.com'), ('b@x.com')) w WHERE w.column1 = v.column1) > 1;
SELECT * FROM import_rejects ORDER BY email, name;Checked on SQLite 3.46.1, run twice with identical output.
Key points
- DO NOTHING hides conflicts
- Check changes() or RETURNING counts
- Duplicates within the file also conflict
- Stage and report rejects
- Use DO UPDATE when updates should apply
Common mistakes
- Reporting success from the absence of errors
- Ignoring duplicates inside the batch
Follow-ups
- How would you keep the latest of two duplicates in a file?
- How would you report inserted versus updated rows?
Tips
- Compare rows sent with rows inserted