This article is half-done without your Comment! *** Please share your thoughts via Comment ***
I already a shared article on ON CONFLICT clause of PostgreSQL 9.5
PostgreSQL 9.5: Insert IF not Exists, Update IF Exists (Insert ON CONFLICT option)
In above article, I used only one single key in ON CONFLICT clause.
A day before yesterday, I got an email like, does it require to add a unique index on those columns which we require to be in ON CONFLICT clause?
The answer is: Yes
You must need to define a unique index on those columns which you are planning to use in ON CONFLICT clause because it can only check the duplicates bases on unique indexes only.
Below is a demonstration of this:
Create a table with sample data with composite PRIMARY KEY:
1 2 3 4 5 6 7 8 9 10 |
CREATE TABLE tbl_Employee ( EmpID INT ,EmpName CHARACTER VARYING ,CONSTRAINT pk_tbl_Employee_EmpID_EmpName PRIMARY KEY (EmpID,EmpName) ); INSERT INTO tbl_Employee VALUES (1,'Anvesh'),(2,'Roy'),(3,'Lee') ,(4,'Nivu'),(5,'Rajesh'),(6,'Nupur'); |
Try to insert a duplicate EmpID record, using option INSERT ON DO NOTHING:
It will insert a new record because key EmpID + EmpName is not duplicate. But if you execute the same, insert the second time, it will do nothing.
1 2 3 4 |
INSERT INTO tbl_Employee VALUES (6,'Noor') ON CONFLICT (EmpID,EmpName) DO NOTHING; |
Check the result:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
SELECT *FROM tbl_Employee; /* EmpID EmpName ----------------- 1 Anvesh 2 Roy 3 Lee 4 Nivu 5 Rajesh 6 Nupur 6 Noor */ |
Leave a Reply