MySQL Auto_Increment

MySQL Auto_Increment is used to generate a unique number when a new record is added to a table.

MySQL Auto_Increment

MySQL Auto_Increment

     

MySQL Auto_Increment is used to generate a unique number when a new record is added to a table. The Unique number must be Primary key field that is created automatically every time a new record is inserted in a table.

Understand with Example

The Tutorial illustrate an example from 'MySQL Auto_Increment'. To understand the example we create a table 'animals' that has the required field names like id and name whose datatypes are Medium INT and CHAR respectively specified. The id column is used as Primary Key that is used to identify the records uniquely in a table. The Primary Key 'Id' has auto_increment property that can add unique number when a new record is added to a table.

 

 

Query

 

CREATE TABLE animals (
      id MEDIUMINT NOT NULL AUTO_INCREMENT,
      name CHAR(30) NOT NULL,
      PRIMARY KEY (id)
  );

 

Query

 

INSERT INTO animals (name) VALUES
     ('dog'),('cat'),('penguin'),
     ('lax'),('whale'),('ostrich');

 

Query

 

SELECT * FROM animals;

 

Output

 

+----+--------------------------------+
| id | name                           |
+----+--------------------------------+
| 1  | dog                            |
| 2  | cat                            |
| 3  | penguin                        |
| 4  | lax                            |
| 5  | whale                          |
| 6  | ostrich                        |
+----+--------------------------------+