How to Add a Primary Key in MySQL

Last updated July 25, 2026 · By the SaturnSQL team

Use ALTER TABLE ... ADD PRIMARY KEY (columns). To give a keyless table an auto-incrementing id, add the column and the key in one statement. InnoDB rebuilds the table, so expect it to take time on large tables.

ALTER TABLE events ADD PRIMARY KEY (id);

Add an AUTO_INCREMENT id

ALTER TABLE events
  ADD COLUMN id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY FIRST;

The ALTER fails with a duplicate-entry error if the chosen columns contain duplicates; find and remove them first.

Run this in SaturnSQL

SaturnSQL is a browser-based SQL editor for teams: shared query library, schema-aware autocomplete, and scheduled exports to Google Sheets and Slack.

Try it free

Related MySQL guides

© 2026 Panda Capital Oy Ab. All rights reserved.