Home > Database > Mysql Tutorial > body text

How to write mysql primary key auto-increment

下次还敢
Release: 2024-04-22 20:03:13
Original
946 people have browsed it

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 write mysql primary key auto-increment

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>
Copy after login

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>
Copy after login

Notes:

  • Make sure the data type of the primary key column matches the type of value you want to automatically increment ( For example, for a numeric primary key, use INT; for a string primary key, use VARCHAR).
  • The AUTO_INCREMENT attribute can only be set for a single column.
  • When a new row is inserted, the next available value is automatically generated and inserted into the primary key column.
  • If there is already data in the table, please ensure that the primary key value is unique before enabling 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!

Related labels:
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!