sqlitesqlite3-python

Prevent duplicate insertion based on two columns in a table


I have a table with below columns and trying to insert values real time.

TableName: ML_data

ref:

  s.No colA colB colC colD
   1   xxx  123  7   9   
   2   yyy  345  9   4
   3   xxx  456  3   5
   4   xxx  123  6   5

possible duplicates of above table are rows 1 and 4 with colA colB having similar values. I want to restrict my insert when such data occurs in sqlite3 with unique constraints on colA and colB.

Also is there a way to catch the error and not stop my insertion process in the real time.

tried:

alter table ML_data add unique index(colA,colB);

Solution

  • CREATE UNIQUE INDEX IF NOT EXISTS ON ML_data (colA,colB);
    

    You may wish to refer to https://sqlite.org/lang_altertable.html (i.e. there is no ADD INDEX ability) And also https://www.sqlite.org/lang_createindex.html