Home >Database >Mysql Tutorial >How to write mysql primary key auto-increment
There are only two steps to configure primary key auto-increment in MySQL: 1. Specify the primary key and use the PRIMARY KEY keyword when creating the table; 2. Use the ALTER TABLE command to modify the primary key column and specify the AUTO_INCREMENT attribute to automatically increment the primary key. key value.
How to configure primary key auto-increment in MySQL
Configuring primary key auto-increment in MySQL is very simple. Here's how to do it:
Step 1: Specify the primary key when creating the table
When creating the table, use the PRIMARY KEY
keyword to specify the Column set as primary key:
<code class="sql">CREATE TABLE table_name ( id INT NOT NULL AUTO_INCREMENT, name VARCHAR(255) NOT NULL, age INT NOT NULL );</code>
Step 2: Specify the AUTO_INCREMENT
attribute
AUTO_INCREMENT
attribute instructs MySQL when inserting new Automatically increment the primary key value when rowing:
<code class="sql">ALTER TABLE table_name MODIFY COLUMN id INT NOT NULL AUTO_INCREMENT;</code>
Notes:
INT
; for a string primary key, use VARCHAR
). AUTO_INCREMENT
attribute can only be set for a single column. AUTO_INCREMENT
. The above is the detailed content of How to write mysql primary key auto-increment. For more information, please follow other related articles on the PHP Chinese website!