ALTER TABLE … ADD PRIMARY KEY creates a unique, not-null identifier for every row in a table.
Primary keys guarantee each row is unique and quickly locatable. They also become the target of foreign-key references, enabling reliable relationships between tables like Customers
and Orders
.
Use ALTER TABLE table_name ADD CONSTRAINT pk_name PRIMARY KEY (column[, …]);
.PostgreSQL creates a unique B-tree index behind the scenes.
Ensure the column is NOT NULL and contains no duplicates, then run ALTER TABLE Customers ADD PRIMARY KEY (id);
. The command fails if duplicate or NULL values exist.
Yes.Combine columns that jointly guarantee uniqueness, e.g., ALTER TABLE OrderItems ADD CONSTRAINT orderitems_pk PRIMARY KEY (order_id, product_id);
.
Always supply a meaningful name: ADD CONSTRAINT customers_pk PRIMARY KEY (id)
. Named constraints simplify future ALTER TABLE … DROP CONSTRAINT
commands.
Check for duplicates with SELECT id, COUNT(*) FROM Customers GROUP BY id HAVING COUNT(*) > 1;
.Add indexes concurrently on large tables, then attach them with ALTER TABLE … ADD CONSTRAINT … USING INDEX …;
.
Use surrogate integer keys, keep key width narrow, and add the constraint early in the table’s life cycle to avoid future data-cleaning work.
.
Yes, it requires an ACCESS EXCLUSIVE lock while the unique index builds, blocking writes. Use the concurrent-index workflow to minimize downtime.
Yes: DROP the existing constraint, adjust data, then ADD a new PRIMARY KEY. Be sure to update dependent foreign keys.
No, but auto-incrementing columns simplify key generation. You may also use UUIDs or composite keys when business logic demands.