2

what is the best way to prevent duplicate records in a SQL Server database? Using triggers? Using a unique constraint?

Shana
  • 70
  • 1
  • 1
  • 8

2 Answers2

9

Use unique constraints on one or more columns in the table. Example:

CREATE TABLE Persons
(
P_Id int NOT NULL UNIQUE,
LastName varchar(255) NOT NULL UNIQUE,
FirstName varchar(255) NOT NULL UNIQUE, 
Address varchar(255),
City varchar(255)
)

Alter existing table as below

ALTER TABLE Persons
ADD CONSTRAINT uc_PersonID UNIQUE (P_Id,LastName)

If you are using a front-end application to populate the table in the database. Do your validation select query from the application on the database to check for duplicates before inserting into the database. Using constraints will prevent duplicates by throwing an exception.

Note: The above example is SQL SERVER, Oracle, ms access

For much more indepth solution see How to prevent duplicate records being inserted with SqlBulkCopy when there is no primary key

Knox
  • 2,909
  • 11
  • 37
  • 65
Ifeanyi Chukwu
  • 3,187
  • 3
  • 28
  • 32
1

If you don't want error throw from unique constraint and you also want database to receive duplicated data but insert nothing. You may look at merge statement

https://technet.microsoft.com/en-us/library/bb522522%28v=sql.105%29.aspx?f=255&MSPPError=-2147217396

Ray Krungkaew
  • 6,652
  • 1
  • 17
  • 28