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;
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!