ADD PRIMARY KEY enforces row uniqueness in a SQL Server table by creating a clustered or non-clustered index on one or more columns.
Late modeling, data import, or legacy systems may leave tables without a primary key. ALTER TABLE … ADD CONSTRAINT lets you enforce uniqueness without recreating the table.
The command attaches a PRIMARY KEY constraint to one or multiple columns. Optionally specify CLUSTERED | NONCLUSTERED.
Use one numeric, unique, NOT NULL column—typically an identity column like id.
ALTER TABLE Customers
ADD CONSTRAINT PK_Customers PRIMARY KEY CLUSTERED (id);
Yes—combine columns that together guarantee uniqueness.
ALTER TABLE OrderItems
ADD CONSTRAINT PK_OrderItems PRIMARY KEY (
order_id, product_id
);
The following statements enforce primary keys on previously imported CSV data.
-- Customers
ALTER TABLE Customers
ADD CONSTRAINT PK_Customers PRIMARY KEY CLUSTERED (id);
-- Orders
ALTER TABLE Orders
ADD CONSTRAINT PK_Orders PRIMARY KEY (id);
-- Products
ALTER TABLE Products
ADD CONSTRAINT PK_Products PRIMARY KEY (id);
CLUSTERED reorders data pages by the key—great for range scans on id. NONCLUSTERED leaves the table order intact, useful when a table already has a clustered index.
SQL Server refuses to add the constraint if duplicate or NULL values exist. Clean or deduplicate data first:
WITH dups AS (
SELECT id, COUNT(*) AS c FROM Customers GROUP BY id HAVING COUNT(*)>1
)
DELETE c
FROM Customers c
JOIN dups d ON d.id = c.id;
1. Use integer surrogate keys for performance.
2. Name constraints with the PK_TableName
pattern.
3. Create keys in maintenance windows when tables are large.
4. Combine the operation with foreign key creation for referential integrity.
Yes, SQL Server acquires schema modification locks. On large tables, schedule downtime or use ONLINE = ON in Enterprise Edition.
Yes. Use ALTER TABLE … DROP CONSTRAINT PK_name, then re-add it. Be aware that foreign keys referencing the PK must be dropped first.
No. Any NOT NULL unique column or column combination can serve as the primary key; identity just simplifies value generation.