Home > Database > Mysql Tutorial > How to Add an Auto-Increment ID to a Table with an Existing Primary Key?

How to Add an Auto-Increment ID to a Table with an Existing Primary Key?

Patricia Arquette
Release: 2025-01-01 14:01:11
Original
870 people have browsed it

How to Add an Auto-Increment ID to a Table with an Existing Primary Key?

How to Add an Auto-Increment ID to an Existing Table

When maintaining a database, it may become necessary to add an auto-increment column to an existing table. However, this task can present challenges when there is already a primary key defined.

Original Issue:

A developer experienced an error when attempting to add an auto-increment ID to a table named "users" using the following syntax:

ALTER TABLE users
ADD id int NOT NULL AUTO_INCREMENT
Copy after login

The error encountered was:

#1075 - Incorrect table definition; there can be only one auto column and it must be defined as a key
Copy after login

Solution:

To successfully add an auto-increment ID to a table with an existing primary key, use the following syntax:

ALTER TABLE `users` ADD `id` INT NOT NULL AUTO_INCREMENT;
Copy after login

This modified syntax correctly defines the auto-increment column as the primary key, resolving the error.

The above is the detailed content of How to Add an Auto-Increment ID to a Table with an Existing Primary Key?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template