Languages
[Edit]
EN

MySQL - Create table with AUTO_INCREMENT field

0 points
Created by:
Lia-Perez
565

In this article, we would like to show you how to create table with AUTO_INCREMENT field in MySQL.

Quick solution:

CREATE TABLE `users` (
	`column1` DATATYPE AUTO_INCREMENT,
	`column2` DATATYPE,
	`columnN` DATATYPE,
	PRIMARY KEY (`column1`)
);

Note:

Go to the official documentation to see available DATA_TYPES.

Practical example

In this example, we create users table with auto-increment id column which is also the PRIMARY_KEY field.

Note:

AUTO INCREMENT field is often the PRIMARY KEY field.

Query:

CREATE TABLE `users` (
	`id` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
	`username` VARCHAR(50) NOT NULL,
	`group_id` INT(10),
	PRIMARY KEY (`id`)
);

Result:

MySQL - create table with AUTO_INCREMENT field result
MySQL - create table with AUTO_INCREMENT field result

Now, when we insert into the table, we don't need to specify the id column, it will be added automatically based on the previous number.

Query:

INSERT INTO `users`
    (`username`, `group_id`)
VALUES
    ('user1', 1),
    ('user2', 1),
    ('user3', 2),
	('user4', 2);

Result:

MySQL - INSERT INTO AUTO_INCREMENT field - result
MySQL - INSERT INTO AUTO_INCREMENT field - result

References

Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.

MySQL - Problems

MySQL - Create table with AUTO_INCREMENT field
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join