ADD PRIMARY KEY creates or changes the table’s primary-key constraint, enforcing unique, non-NULL values and building a supporting index.
Primary keys guarantee row uniqueness, enable fast lookups through an automatically created index, and allow other tables to reference the row with foreign-key constraints.
Run ALTER TABLE <table> ADD PRIMARY KEY (col1[, col2…]);
.MySQL first checks that all listed columns are NOT NULL and unique, then builds the index.
ALTER TABLE Customers ADD PRIMARY KEY (id);
The statement fails.Clean data with UPDATE
or DELETE
, or create a new surrogate key column and populate it before retrying.
List multiple columns in the same order you expect to query them.
ALTER TABLE OrderItems ADD PRIMARY KEY (order_id, product_id);
Yes—define it inside CREATE TABLE
.
CREATE TABLE Products (
id INT AUTO_INCREMENT,
name VARCHAR(100) NOT NULL,
price DECIMAL(10,2) NOT NULL,
stock INT DEFAULT 0,
PRIMARY KEY (id)
);
Use immutable, numeric columns where possible, avoid business-logic columns that might change, and keep the key short to improve index performance.
.
Both enforce uniqueness, but PRIMARY KEY also makes columns implicitly NOT NULL and permits only one per table.
No. A table supports exactly one PRIMARY KEY constraint, although it can cover multiple columns.
Run ALTER TABLE table_name DROP PRIMARY KEY;
. Add a new key in the same statement if needed.