Reputation: 37
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?
Upvotes: 2
Views: 2103
Reputation: 985
Defining "unique constraint" on table with desired column will fix everything. If there's a dupplicate you will get error.
Upvotes: 1
Reputation: 23470
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.
Upvotes: 0
Reputation: 562498
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.
Upvotes: 5
Reputation: 171451
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.
Upvotes: 0