ADD PRIMARY KEY creates or enforces a unique, non-NULL identifier on one or more columns in a MariaDB table.
Primary keys guarantee row uniqueness, speed up lookups, and enable efficient joins. Adding one later helps legacy tables gain these advantages without rebuilding data.
Use ALTER TABLE followed by ADD PRIMARY KEY and a comma-separated list of columns in parentheses. You may optionally name the constraint.
Supply one column after ADD PRIMARY KEY. The column must already be NOT NULL or the statement will fail.
List multiple columns inside the parentheses. MariaDB treats the combined values as the unique identifier.
Yes. Place MODIFY or CHANGE clauses before ADD PRIMARY KEY within the same ALTER TABLE. This prevents extra table rebuilds.
ALTER TABLE is generally blocking. On large tables, use pt-online-schema-change or ALTER ONLINE if available to avoid downtime.
Yes—list multiple columns inside the parentheses after ADD PRIMARY KEY. The combined values must be unique and non-NULL.
MariaDB automatically creates a unique index backing the primary key, improving query performance on the specified columns.