tags:

views:

52

answers:

4

To prevent duplicate table entries in a database I use a primary key. I just add the information and if it is a duplicate then the primary will be a duplicate and it will not add to the table.

Should I also do a SQL query (before trying to add to the database) to see if the entry exists? Or is this redundant since I already have the primary key set?

A: 

With most database platforms, when you create the primary key, the operation will fail if there are duplicate entries, so there should be no need to test for this beforehand.

RedFilter
+4  A: 

It is redundant to check for presence of a value if you already have a constraint to prevent duplicates.

But it would also be ineffective to check before you insert, because some other concurrent client might insert that value in the moment between your check and your insert. So even if you check first, you'd still need to handle duplicate key errors.

Bill Karwin
A: 

Usually you'd get an exception or an error code from the call to SQL engine. If you need to handle that or not depends on your application logic. For example if it is a new username, and it already exists in the database, then exception is part of you application logic, and you will provide new user with a message about why registration failed.

Leonid
+1  A: 

Defining "unique constraint" on table with desired column will fix everything. If there's a dupplicate you will get error.

Burçin Yazıcı