5 What is the difference between a primary key and a unique key?
A primary key and a unique key (a UNIQUE constraint) both guarantee that the values in a column, or a set of columns, are unique across every row. The difference is about how many you can have, how they treat NULL, and the role each plays in the table design.
- How many per table. A table can have exactly one primary key. You can define many unique constraints on the same table, one per set of columns that must stay distinct.
- NULL handling. A primary key column is implicitly
NOT NULLand rejects NULLs. A unique constraint allows a singleNULLin SQL Server (because two NULLs are treated as equal for uniqueness), so at most one row can leave that column empty. - Physical storage. A primary key creates a clustered index by default, so it also sets the physical row order. A unique constraint creates a nonclustered index by default. Both defaults can be overridden.
- Intent. The primary key is the row identity that other tables point at; a unique constraint protects an alternate key such as an email or SSN.
Both are valid constraints that a foreign key can reference. A child table can point its foreign key at a primary key or at any unique constraint on the parent, as long as the referenced columns are guaranteed unique. See also primary key vs foreign key for the relationship side of this.
When you insert or update a duplicate value, SQL Server raises one of two closely related errors. Violating a primary key or a UNIQUE constraint raises error 2627, while violating a plain unique index raises error 2601. Both mean the same thing at heart: the value you tried to write already exists.
CREATE TABLE Customers (
customer_id INT NOT NULL,
email VARCHAR(255) NULL,
CONSTRAINT PK_Customers PRIMARY KEY (customer_id)
);
customer_id is the row identity: unique, non-nullable, and (by default) the clustered index that orders the table.
ALTER TABLE Customers
ADD CONSTRAINT UQ_Customers_Email UNIQUE (email);
-- A second row with the same email fails with error 2627.
-- A single row may still leave email NULL; a second NULL would also fail.
email is an alternate key: it must be unique but is allowed to be NULL in exactly one row.
- Can a foreign key reference a unique constraint instead of a primary key?
- Why can a primary key never contain a NULL?
- What is the difference between a unique constraint and a unique index?
- What does it mean that a primary key is clustered by default?
Related: What is a primary key? · What is the difference between a candidate key and a primary key? · What does DISTINCT do and how do you remove duplicate rows?