Explain the difference between a primary key and a unique key in a database.

1 Answers
Answered by suresh

Primary Key vs Unique Key in Database Administration - Interview Questions

Primary Key vs Unique Key in Database

Primary Key:

A primary key is a column or a set of columns that uniquely identifies each record in a table. It must contain unique values, cannot have NULL values, and there can be only one primary key in a table. The primary key is used to enforce entity integrity in the database.

Unique Key:

A unique key is a constraint that ensures the uniqueness of values in a column or a set of columns. Unlike a primary key, a unique key can allow NULL values, and there can be multiple unique keys in a table. Unique keys are used to enforce domain integrity in the database.

Key Differences:

  • Primary Key uniquely identifies each record and enforces entity integrity.
  • Unique Key ensures uniqueness of values and enforces domain integrity.
  • Primary Key does not allow NULL values, while Unique Key may allow NULL values.
  • There can be only one Primary Key in a table, but there can be multiple Unique Keys.

It is essential to understand the distinctions between primary keys and unique keys in database design to maintain data integrity and avoid duplicate records.

Answer for Question: Explain the difference between a primary key and a unique key in a database.