Set AUTO_INCREMENT in a table while creating it in MySQL?



Let us first create a table. We have used AUTO_INCREMENT while creating the table to set auto increment for StudentId −

mysql> create table DemoTable
   -> (
   -> StudentId int NOT NULL AUTO_INCREMENT,
   -> StudentFirstName varchar(100),
   -> StudentLastName varchar(100),
   -> StudentAge int,
   -> StudentCountryName varchar(100),
   -> PRIMARY KEY(StudentId)
   -> )AUTO_INCREMENT=30;
Query OK, 0 rows affected (0.69 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable(StudentFirstName,StudentLastName,StudentAge,StudentCountryName) values('John','Smith',21,'US');
Query OK, 1 row affected (0.17 sec)

mysql> insert into DemoTable(StudentFirstName,StudentLastName,StudentAge,StudentCountryName) values('Chris','Brown',20,'AUS');
Query OK, 1 row affected (0.19 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable;

Output

+-----------+------------------+-----------------+------------+--------------------+
| StudentId | StudentFirstName | StudentLastName | StudentAge | StudentCountryName |
+-----------+------------------+-----------------+------------+--------------------+
| 30        | John             | Smith           | 21         | US                 |
| 31        | Chris            | Brown           | 20         | AUS                |
+-----------+------------------+-----------------+------------+--------------------+
2 rows in set (0.00 sec)

Advertisements