The difference between a primary key and a unique constraint in a database is as follows:
- Primary Key
Purpose: Uniquely identifies each row in a table.
Uniqueness: Ensures that no two rows have the same value for the primary key column(s).
Null Values: Cannot contain null values.
Count per Table: A table can have only one primary key.
Default Index: Automatically creates a unique clustered index (in most databases).
- Unique Constraint
Purpose: Ensures that all values in a column (or combination of columns) are unique.
Uniqueness: Similar to a primary key, it ensures uniqueness but allows flexibility.
Null Values: Can contain one or more null values (depends on the database).
Count per Table: A table can have multiple unique constraints.
Default Index: Automatically creates a unique non-clustered index.
CREATE TABLE Example (
id INT PRIMARY KEY, -- Primary key
email VARCHAR(255) UNIQUE -- Unique constraint
);
id is the primary key: It cannot be null, and each value must be unique.
email has a unique constraint: Each value must be unique, but it can have null values.