MySQL
keyboard_arrow_down 295 guides
chevron_leftKey Cookbooks
check_circle
Mark as learned thumb_up
5
thumb_down
1
chat_bubble_outline
0
Comment auto_stories Bi-column layout
settings
Changing the primary key in MySQL
schedule Aug 12, 2023
Last updated local_offer
Tags MySQL
Master the mathematics behind data science with 100+ top-tier guides
Start your free 7-days trial now!
Start your free 7-days trial now!
In order to change the primary key for a particular table in MySQL, you must first remove the current primary key and then add the new primary key.
Syntax
To remove the current primary key and then add a new one:
ALTER TABLE table_name DROP PRIMARY KEY, ADD PRIMARY KEY (column_name);
Example
Given a table called info
with the column name
as the primary key:
DESCRIBE info;
+-------+-------------+------+-----+---------+-------+| Field | Type | Null | Key | Default | Extra |+-------+-------------+------+-----+---------+-------+| name | varchar(20) | NO | PRI | NULL | || age | int | YES | | NULL | || hobby | varchar(20) | YES | | NULL | |+-------+-------------+------+-----+---------+-------+
To set the column age
as the new primary key:
ALTER TABLE info DROP PRIMARY KEY, ADD PRIMARY KEY (age);
Here we first drop the current primary key and then in the latter half of the statement we newly set the primary key on the age
column.
To check the primary key is now updated:
DESCRIBE info;
+-------+-------------+------+-----+---------+-------+| Field | Type | Null | Key | Default | Extra |+-------+-------------+------+-----+---------+-------+| name | varchar(20) | NO | | NULL | || age | int | NO | PRI | NULL | || hobby | varchar(20) | YES | | NULL | |+-------+-------------+------+-----+---------+-------+
Published by Arthur Yanagisawa
Edited by 0 others
Did you find this page useful?
thumb_up
thumb_down
Comment
Citation
Ask a question or leave a feedback...
thumb_up
5
thumb_down
1
chat_bubble_outline
0
settings
Enjoy our search
Hit / to insta-search docs and recipes!