JIYIK CN >

Current Location:Home > Learning > DATABASE > MySQL >

Update the primary key in a MySQL table

Author:JIYIK Last Updated:2025/04/22 Views:

This article explains how to update the primary key in a MySQL table. We will use the ALTER command to make any changes to the primary key.


Update the primary key in a MySQL table

We can update the primary key in a MySQL table in multiple scenarios. Let's look at each of them below.

  1. Drop the existing primary key and create a new one using different columns.
  2. Updates the number of columns involved in constructing the primary key.
  3. Change the data type of the primary key.

We can change the primary key using the ALTER command which we will actually demonstrate later in this tutorial.


Drop existing primary key and create new primary key using different columns in MySQL

Suppose we have a users table in the test database whose primary key is the id attribute. For some reason, we want to delete it and construct a new primary key using the USERNAME column.

Create the user table:

#create a table named 'users' in 'test' database
CREATE TABLE `test`.`users` (
  `ID` INT NOT NULL AUTO_INCREMENT,
  `USERNAME` VARCHAR(45) NOT NULL,
  `EMAIL` VARCHAR(45) NOT NULL,
  PRIMARY KEY (`ID`));

Use the following statement to check the table definition.

SHOW CREATE TABLE test.users;

It will display the following output; your results may vary if you use a different table.

Output:

update primary key in mysql tables - table definition part one

To update the primary key from ID to the USERNAME field, we must first remove AUTO_INCREMENT from the ID attribute ; otherwise, it will generate an error.

Remove AUTO_INCREMENT for the ID field :

# Disable foreign key check
SET FOREIGN_KEY_CHECKS=0;
# Modify the `ID` attribute
ALTER TABLE test.users MODIFY COLUMN ID INT NOT NULL;
# Enable foreign key check
SET FOREIGN_KEY_CHECKS=1;

Use SHOW CREATE TABLE test.users; to confirm that AUTO_INCREMENT has been removed.

Output:

update primary key in mysql tables - table definition part two

Update the primary key:

ALTER TABLE test.users DROP PRIMARY KEY, ADD PRIMARY KEY(USERNAME);

Use SHOW CREATE TABLE test.users;again to ensure that the primary key is USERNAME.

Output:

update primary key in mysql tables - table definition part three


Update the number of columns involved in constructing the primary key in MySQL

We are continuing with the users table we created in the previous section. The primary key is the USERNAME column, which can be easily checked using the following query.

SHOW CREATE TABLE test.users;

We use the ALTER command to update the primary key which will now consist of two columns, ID and USERNAME.

ALTER TABLE test.users DROP PRIMARY KEY, ADD PRIMARY KEY(ID, USERNAME);

We can use the following query to confirm the updated primary key.

SHOW CREATE TABLE test.users;

Output:

update primary key in mysql tables - table definition part four


Updating MySQL primary key by changing data type

Here we create another table, named user, with the primary key being the ID field of type INT.

CREATE TABLE `test`.`user` (
  `ID` INT NOT NULL AUTO_INCREMENT,
  `USERNAME` VARCHAR(45) NOT NULL,
  `EMAIL` VARCHAR(45) NOT NULL,
  PRIMARY KEY (`ID`));

We can update the data type of an existing primary key from INT to BIGINT using the following query.

SET FOREIGN_KEY_CHECKS=0;
ALTER TABLE test.users MODIFY COLUMN ID BIGINT NOT NULL AUTO_INCREMENT;
SET FOREIGN_KEY_CHECKS=1;

Confirm the changes using the query given below.

SHOW CREATE TABLE test.user;

Output:

update primary key in mysql tables - table definition part five

Updating the primary key in a MySQL table before establishing relations in the database is not difficult, but it is highly discouraged after establishing relations in the database for the following basic reasons.

  1. If you want to change the primary key in a running database, you may have chosen the incorrect field for the primary key. So be careful when choosing a field as the primary key.
  2. You will need to delete the record whose primary key you are trying to change. You may have to lose all relationships for that particular record.

    If you change the primary key, you must add that record and recreate the relationship.

  3. If you change the primary key from one column to three columns, the new primary key (composed of three columns) must be used as a foreign key in all other related tables. Keep in mind that this affects storage, performance, and design.
  4. Unless you are rebuilding the database during a MIGRATION or FILE RE-ORGANIZATION, it is highly discouraged to make any changes to the primary keys in the database. However, you must be extra careful because these primary keys may be used as foreign keys in other tables.

For reprinting, please send an email to 1244347461@qq.com for approval. After obtaining the author's consent, kindly include the source as a link.

Article URL:

Related Articles

Changing max_allowed_packet Size in MySQL Server

Publish Date:2025/04/22 Views:192 Category:MySQL

This article explains how to change the max_allowed_packet size in MySQL server. To understand this, we will use two operating systems, Windows 10 and Linux (Ubuntu). Changing max_allowed_packet Size in MySQL Server If we try to upload a fi

Zerofill usage, advantages and alternatives in MySQL

Publish Date:2025/04/22 Views:195 Category:MySQL

In this article we will understand the uses, advantages and alternatives of ZEROFILL attribute in MySQL. Use and benefits of the ZEROFILL attribute in MySQL The benefit of using the ZEROFILL attribute is that it has nothing to do with input

Compare only MySQL timestamp dates to date parameters

Publish Date:2025/04/22 Views:64 Category:MySQL

In this article we will use the DATE() , CAST() , and CONVERT() functions to compare MySQL timestamp dates with only the date parameter. DATE() vs. CAST() vs. CONVERT() in MySQL Below is a brief description of each function. You can also fi

Calculating Percentages in MySQL

Publish Date:2025/04/22 Views:66 Category:MySQL

We will use one or more columns to calculate percentages in MySQL. There are different ways to do this, and for each method we will use an example table. Calculate percentage using a column in MySQL We have a table called sales where ID, Re

Selecting multiple values using WHERE in MySQL

Publish Date:2025/04/22 Views:185 Category:MySQL

This article is about using MySQL query to get data from a specific table or relation that satisfies a specific condition. To do this, the WHERE clause is used in the SQL query. WHERE clause in SQL query WHERE The clause specifies the condi

Changing the connection timeout in MySQL

Publish Date:2025/04/22 Views:59 Category:MySQL

We are learning how to change the connection timeout in MySQL using Linux (Ubuntu 20.04) and Windows operating systems. Changing the connection timeout in MySQL Sometimes you keep losing connection to the MySQL server because the connect_ti

MySQL fix Data Is Truncated for a Column error

Publish Date:2025/04/22 Views:101 Category:MySQL

This article describes possible causes and solutions for the MySQL error Data is truncated for a column . Fix data truncated due to column error in MySQL Here, we will discuss the possible causes and solutions to eliminate MySQL data trunca

MySQL Error Server PID File Could Not Be Found Solution

Publish Date:2025/04/22 Views:192 Category:MySQL

In this article, we will study about the Error! Error Server PID File Could Not Be Found! in MySQL and its solution with full explanation. MySQL PID file The file that contains the process identification number or process ID of a running My

Get the last inserted ID using PHP MySQLi function

Publish Date:2025/04/22 Views:99 Category:MySQL

This article briefly introduces the PHP mysqli() function and demonstrates how to use it to get the last inserted ID from a MySQL database. PHP mysqli() Function It is an extended version of the MySQL driver called mysqli and is typically u

Scan to Read All Tech Tutorials

Social Media
  • https://www.github.com/onmpw
  • qq:1244347461

Recommended

Tags

Scan the Code
Easier Access Tutorial