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

How to Automatically Add an Auto-Increment Primary Key to an Existing Database Table?

Mary-Kate Olsen
Release: 2024-12-01 19:15:12
Original
810 people have browsed it

How to Automatically Add an Auto-Increment Primary Key to an Existing Database Table?

Automatically Inserting Auto-Increment Primary Key and Values into Existing Table

Encountering tables without primary keys or auto-increment columns is a common scenario in database management. To add a primary key column and assign unique identifiers to existing rows, a specific approach is required.

To achieve this, executing an ALTER TABLE statement with the desired column specifications is recommended. For instance, the following statement adds an auto-increment primary key column named "id" to an existing table:

ALTER TABLE tbl ADD id INT PRIMARY KEY AUTO_INCREMENT;
Copy after login

Upon execution, this statement creates the "id" column and automatically populates it with auto-increment values for each row in the table, starting with 1. This effectively adds a unique identifier to each row without the need for manual intervention.

The above is the detailed content of How to Automatically Add an Auto-Increment Primary Key to an Existing Database Table?. 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