0

When issuing a bulk insert statement, how can we ignore (supress) the exception thrown by DB and/or JDBC driver ?

Lets say I want to bulk insert some Users and I have an Id as a unique key

INSERT INTO users
(id,name,age,email,pass_code) 
VALUES 
(1,'Mark',18,'[email protected]',123),
(2,'Zak',18,'[email protected]',123),
(3,'Djigi',18,'[email protected]',123),

(1,'James Petkov',18,'[email protected]',123), --Duplicated by id ? 

(4,'Kinkinikin',18,'[email protected]',123),
(5,'A bula bula ',18,'[email protected]',123),
(6,'Shakazulo',18,'[email protected]',123);

How to tell the engine MySQL/PostgreSQL to continue inserting the remaining records ?

Is this supported in SQL at all ?

5
  • Then don't make this ID the primary key of your table. Since it is in duplicate anyway, let MySQL assign an ID. Commented Nov 28, 2016 at 12:23
  • is your question more about continuing insertions when errors are encountered along the way? Commented Nov 28, 2016 at 12:26
  • @TimBiegeleisen The ideas is not about generating ids but rather to suppress the exception when inserting duplicate records. Commented Nov 28, 2016 at 12:42
  • Are you using MySQL or Postgres? The error is there for a reason. If not primary key then don't read it in as such. Commented Nov 28, 2016 at 12:45
  • @TimBiegeleisen What I am asking, generally, if you are doing bulk insert and you have duplicate record regardless of which key is duplicated how can you continue the operation and skip the duplicated key, that's it :) Commented Nov 28, 2016 at 12:48

1 Answer 1

1

In PostgreSQL, you can ignore the failing rows with

INSERT ... ON CONFLICT (id) DO NOTHING;

A more general solution is to run each INSERT separately and ignore errors.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.