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

Ensuring unique primary keys

When I use autonumbers for primary keys, I need to prevent the entry of duplicate records. I have been told that...

there is a standard SQL algorithm to prevent the entry of duplicate records, but I do not know where to find it.

Excellent question. One of the problems with using a surrogate key such as an autonumber for the table's primary key is that you can end up with duplicates in the "real" primary key.

Consider the following Product table:

prodID  prodCode  prodDescription

  1      XTBW     Widget size 27 
  2      XTCW     Widget size 52 
  3      XTDW     Widget one-size 
  4      YBWD     Widget size 27 
  5      YBWX     Widget size 52 

In this scenario, assuming prodID is an autonumber column, you could easily run:

insert 
  into Product
     ( ProdCode, ProdDescription )
values 
     ( 'XTDW', 'Widget any size' )

This insert would succeed, and now you have two rows with the same prodCode.

The "standard algorithm" you're looking for is the unique constraint.

alter table Product
  add constraint uniqueprodcode 
       unique (prodCode)

Note that "duplicate records" would have to be equal in all columns. Usually this is not a concern. If it is necessary to check multiple columns for uniqueness of the combinations of values, just list those columns in the UNIQUE clause when defining the constraint. For example,

alter table Customer
  add constraint uniquecustomer 
       unique (LastName, MiddleInit, FirstName)

For More Information


This was last published in December 2002

Dig Deeper on Oracle and SQL

PRO+

Content

Find more PRO+ content and other member only offers, here.

Have a question for an expert?

Please add a title for your question

Get answers from a TechTarget expert on whatever's puzzling you.

You will be able to add details on the next page.

Start the conversation

Send me notifications when other members comment.

By submitting you agree to receive email from TechTarget and its partners. If you reside outside of the United States, you consent to having your personal data transferred to and processed in the United States. Privacy

Please create a username to comment.

-ADS BY GOOGLE

SearchDataManagement

SearchBusinessAnalytics

SearchSAP

SearchSQLServer

TheServerSide

SearchDataCenter

SearchContentManagement

SearchFinancialApplications

Close