When building an application and you are using a table that has a primary key, should you check to see if the table has a primary key or does not have duplicate IDs?
I ran into some code I’m maintaining that is checking to ensure no duplicate ids are in the result set. But the id that is being checked is a primary key. So to me this check is not needed since you cannot have a primary keys with the same value.
But… should this be checked in case a DBA disabled the primary key on the table for any reason or assume the primary key should always be there?
Make sure that the query is actually returning data only from the table with the primary key. If this table is joined to another table in the query, and it isn’t a one-to-one relationship, it could cause multiple rows to be returned which have the same ID in the primary table. In this case, the code checking for duplicates may actually be doing something valuable.
As long as this isn’t the case, remove the code that checks for duplicates. It’s a waste of CPU cycles and memory to verify that the database is doing its job.