What is the difference between a primary key and an attribute which is declared as UNIQUE and NOT NULL in the same table in a database?
- You can only have one primary key per table.Mihai– Mihai2013-10-05 17:03:10 +00:00Commented Oct 5, 2013 at 17:03
- 1also u might want to read the second comment in the above duplicate link ;)Vandesh– Vandesh2013-10-05 17:05:41 +00:00Commented Oct 5, 2013 at 17:05
- Logically speaking there is no difference. In practice there may be some subtle differences depending on your DBMS software - usually to do with internal storage and indexing.nvogel– nvogel2013-10-23 02:18:28 +00:00Commented Oct 23, 2013 at 2:18
2 Answers
There can only be one primary key in a table and that cannot be null. You dont have to explicitly specify the NOT NULL attribute for primary key.
There can be more than one unique key in the table. Unique key can be null
When you specify any column as NOT NULL then it means that you cannot leave the column as NULL
EDIT:-
As per your comments, you cannot have more than one primary key in your table.
Also a unique key constraint does not imply the NOT NULL constraint in practice. Besides what is the use of writing NOT NULL for unique key as that is the only difference between Primary key and Unique key.
3 Comments
It is unfortunate that that SQL constraint was named primary key because it confuses the related but different concepts of the Logical Entity primary key and the Physical Storage primary key of the entity. While it is certainly possible, and not infrequently the case, that the same fields are used for both the logical and physical primary key, this is not required and also frequently not desirable.
The Logical Entity primary key is the object referred to in Database textbooks discussing relational theory. It is this object that one refers to when Normalizing relation structures, and it is (of course) one of the candidate keys that exist for the Entity in the logical model.
The Physical Storage primary key is an attribute in the Physical Model, possibly in addition to those attributes defined in the Logical Model for the Entity, which is used by the DBMS to uniquely identify the storage for an instance of the Logical Entity. This is the object being referred to in the primary key constraint when defining the (physical) schema for an entity's storage. When this Physical Storage primary key differs from the Logical Entity primary key it is most commonly because an artificial key has been appended to the logical attributes in order to:
- Enable update of fields in the Logical Entity primary key;
- Improve performance by being a narrower key for foreign key reference refer to
All Logical Entity candidate keys should be defined in the Physical Model with uniqueness constraints. Only the Physical Storage primary key becomes the primary key constraint.