What is the difference between a unique key and primary key?
Explanation
The PRIMARY KEY constraint is used to identify each row of data in a table. It doesn't allow NULL values. A table can have only one primary key, which may consist of single or multiple fields.
The UNIQUE KEY constraint ensures that all values in a column are different. It allows only one record to have a NULL value.
Both UNIQUE and PRIMARY KEY constraints provide a guarantee for uniqueness for a column or set of columns.
A PRIMARY KEY constraint automatically has a UNIQUE constraint though.
Several UNIQUE KEY constraints may exist per table, but only one PRIMARY KEY, though.
Theory
  • SQL UNIQUE Constraint

    The UNIQUE constraint uniquely identifies each record in a database table.
    The UNIQUE and PRIMARY KEY constraints both provide a guarantee for uniqueness for a column or set of columns.
    A PRIMARY KEY constraint automatically has a UNIQUE constraint defined on it.
    Note that you can have many UNIQUE constraints per table, but only one PRIMARY KEY constraint per table. Read more: SQL UNIQUE Constraint
  • SQL PRIMARY KEY Constraint

    The PRIMARY KEY constraint uniquely identifies each record in a database table.
    Primary keys must contain UNIQUE values.
    A primary key column cannot contain NULL values.
    Most tables should have a primary key, and each table can have only ONE primary key.
    Read more: SQL UNIQUE Constraint

Follow CodeGalaxy

Mobile Beta

Get it on Google Play
Send Feedback
Keep exploring
SQL quizzes
Cosmo
Sign Up Now
or Subscribe for future quizzes