views:

63

answers:

2

I have a database where I need to avoid inserting duplicates. The requirements are:

For the subset of rows with matching column 1, there can not be any that have the same column 2.

For the subset of rows with matching column 1, there can not be any that have the same column 3 and 4.

I'm new to SQL so is there a way of setting these relationships when I create the database (create table) or do I have to do a select and do these checks manually before inserting into the table?

A: 

Just to get the ball rolling ...

Could you go back immediately after the insert and delete duplicated rows based on the contraints you mentioned?

pavium
Ugh...to be polite about it. Yes, you can; but no, it would be horrendously inefficient to do so.
Jonathan Leffler
Fair enough. I learned from Todd Owen's answer that CONSTRAINT is necessary when the table is created. I suppose it can be changed after creation. Back to the manual ...
pavium
+3  A: 

In effect, you need the column 1 and 2 to be unique, and also columns 1,3 and 4 to be unique. So when you create the table, you can use two UNIQUE constaints:

CREATE TABLE tbl (
  col1 varchar(255),
  col2 varchar(255),
  col3 varchar(255),
  col4 varchar(255),
  CONSTRAINT uc_first UNIQUE(col1, col2),
  CONSTRAINT uc_second UNIQUE(col1, col3, col4)
)
Todd Owen
Thanks. One thing, is there any way to know which constraint is being triggered in sqlite? Google shows some people complaining that they need to do string comparisons (.IsSameAs("SQLITE_CONSTRAINT[19]: columns 1, 3, 4, are not unique")). Seem klunky.
max