ALTER TABLE … ADD PRIMARY KEY creates or replaces the unique row identifier constraint on an existing PostgreSQL table.
Sometimes you import data first and enforce constraints later. ALTER TABLE … ADD PRIMARY KEY lets you add or change the unique row identifier without recreating the table.
Use ALTER TABLE table_name ADD PRIMARY KEY (column_list);. It builds a unique b-tree index and marks the column list as the table’s primary key.
Run ALTER TABLE "Orders" ADD PRIMARY KEY (id);. PostgreSQL rejects duplicate ids automatically.
Yes. Combine multiple columns: ALTER TABLE "OrderItems" ADD PRIMARY KEY (order_id, product_id);. The pair now uniquely identifies each row.
Save time on big tables: CREATE UNIQUE INDEX idx_orders_id ON "Orders"(id); ALTER TABLE "Orders" ADD PRIMARY KEY USING INDEX idx_orders_id;.
ALTER TABLE … ADD PRIMARY KEY is blocking in vanilla Postgres. For large tables, consider creating the unique index concurrently, then attach it.
The command aborts with ERROR: could not create unique index. Clean up duplicates first with DELETE or SELECT DISTINCT INTO.
Always create primary keys on surrogate integer or UUID columns, keep them narrow, and name constraints clearly, e.g., orders_pkey.
Yes. PostgreSQL builds a unique b-tree index unless you attach an existing one with USING INDEX.
No, execute ALTER TABLE DROP CONSTRAINT … then ALTER TABLE ADD PRIMARY KEY, preferably in a single transaction.
Yes. PostgreSQL enforces both NOT NULL and UNIQUE on all primary key columns.