Menu▾

Add a primary key to an unkeyed orders table

This orders table was created without a primary key — every column is nullable and nothing stops a duplicate id from being inserted. id is meant to uniquely identify a row and is never null in the data that's already there.

Add a PRIMARY KEY constraint on orders.id. Don't create a new table — alter the existing one.

Schema

▸orders
idINT
customer_idINT
amountNUMERIC

Example input

Why

ALTER TABLE ... ADD CONSTRAINT ... PRIMARY KEY (id) does two things in one statement: it enforces NOT NULL on id (a primary key can never be null) and builds a unique index on it, which is how the constraint is actually enforced under the hood — the same index you'd get from CREATE UNIQUE INDEX. If any existing row already had a null or duplicate id, this statement would fail immediately rather than silently ignoring the bad rows, which is why it's safe to run against live data.

↑ Read the question

Keep going

Company names are trademarks of their respective owners, used here only to describe practice material. mahir_data is not affiliated with, endorsed by, or sponsored by any company named on this site. Terms.