EN
MySQL - Create table with AUTO_INCREMENT field
0
points
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 thePRIMARY 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:
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: