Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does a table with a surrogate key require a unique constraint on a natural key to be in 1NF?

The pragmatists have won the argument of surrogate vs. natural primary keys in favor of surrogate keys*. In my own work I always use SQL Server identity columns without a second thought. But it occurs to me that, for a table to be in 1st normal form, I should be able to identify a natural key and enforce it with a unique constraint. I can't do this for all the tables in my database, so my database doesn't even meet the lowest criteria of normalization.

Do you agree that a table with a surrogate primary key must also have a unique constraint on a natural key in order to be in 1NF?

*I think Joe Celko is still fighting the good fight, see the last paragraph.

Edited to add: Thanks for the responses. My impression is that adding a unique constraint is not a common practice, so I'm somewhat surprised that the responses so far have been unanimous.

like image 764
Jamie Ide Avatar asked May 08 '09 15:05

Jamie Ide


People also ask

Is surrogate key unique?

Surrogate keys are unique. Because surrogate keys are system-generated, it is impossible for the system to create and store a duplicate value.

Is surrogate key a natural key?

Data comprises a natural key. A surrogate key is a meaningless value, usually generated by the system. Some developers use both, allowing the application and data to guide their decision, while others use one or the other religiously.

Is surrogate key a constraint?

Surrogate keys can result in duplicate values in any natural keys. To prevent duplication, one must preserve the role of the natural keys as unique constraints when defining the table using either SQL's CREATE TABLE statement or ALTER TABLE ...ADD CONSTRAINT statement, if the constraints are added as an afterthought.

What is difference between surrogate key natural key and primary key?

Natural key: an attribute that can uniquely identify a row, and exists in the real world. Surrogate key: an attribute that can uniquely identify a row, and does not exist in the real world. Composite key: more than one attribute that when combined can uniquely identify a row.


1 Answers

Yes!

If the table is supposed to record at most instance of the natural key, you need a constraint on the relevant column(s) to enforce that. Otherwise, you can end up with a table of 50,000,000 rows, each with a different ID value but otherwise identical -- which is pathetic or ludicrous or a travesty, depending on your viewpoint.

like image 173
Jonathan Leffler Avatar answered Oct 21 '22 11:10

Jonathan Leffler