Problem solve Get help with specific problems with your technologies, process and projects.

Preventing duplicate entries on multiple columns

I have a table in SQL Server with three columns: col1, col2, col3. I have inserted a row with values 1,2,3, and it should not repeat again. Through a trigger, how it is possible to restrict a user from inserting the same values? I don't want to create primary keys, or even any identity columns. It should not be allowed to insert 1,2,3, but one could insert 1,2,5 and 1,2,4.

May I suggest a UNIQUE constraint.

alter table yourtable
  add constraint nodupes123
        unique nonclustered
        ( col1, col2, col3 )

You could get the same result using a trigger, but why? In the trigger code, you would have to do a SELECT to see if any row exists already with the particular values for the three columns, and this SELECT is going to be inefficient unless there is an index defined on those three columns. You might as well define the UNIQUE constraint because this creates the index automatically, and then you don't have to write any code.

For More Information

Dig Deeper on Oracle and SQL