Junior
What are the differences between PRIMARY and UNIQUE constraints in a database?
sobes.tech AI
Answer from AI
-
PRIMARYKey:- Ensures the uniqueness of values in a column (or set of columns).
- Automatically creates an index to speed up searches.
- Does not allow
NULLvalues in the column (or any column in the set). - There can be only one
PRIMARYKey in a table. - Used for the unique identification of each row in the table.
-
UNIQUEConstraint:- Ensures the uniqueness of values in a column (or set of columns).
- Automatically creates an index to speed up searches.
- Allows
NULLvalues (but only oneNULL, sinceNULLis not considered equal to anotherNULLin the context of uniqueness). - A table can have multiple
UNIQUEconstraints.
The main difference is that a PRIMARY Key is an entity identifier in the table and does not allow NULL, whereas UNIQUE simply enforces the uniqueness of values, allowing NULL. The PRIMARY Key is essentially a special case of a UNIQUE constraint with an added NOT NULL restriction.