In MySQL, what is the difference between SERIAL and AUTO_INCREMENT?

MySQLMySQLi Database

In MySQL, both SERIAL and AUTO_INCREMENT are used to define a sequence as a default value for a field. But they are technically different from each other.

The AUTO_INCREMENT attribute is supported by all numeric data types except for BIT and DECIMAL. There can only be one AUTO_INCREMENT field per table and the sequence generated by an AUTO_INCREMENT field in one table cannot be used in any other table. 

This attribute requires that a UNIQUE index exists on the field to ensure the sequence has no duplicates. The sequence would start by default from 1 and increment by 1 for every insert.

Example

mysql> Create Table Student(Student_id INT PRIMARY KEY NOT NULL AUTO_INCREMENT, Name Varchar(20));
Query OK, 0 rows affected (0.18 sec)

The query above declares Student_id AUTO_INCREMENT.

mysql> Insert Into Student(Name) values('RAM'),('SHYAM');
Query OK, 2 rows affected (0.06 sec)
Records: 2 Duplicates: 0 Warnings: 0

mysql> Select * from Student;
+------------+-------+
| Student_id | Name  |
+------------+-------+
|          1 | RAM   |
|          2 | SHYAM |
+------------+-------+
2 rows in set (0.00 sec)

mysql> Show Create Table Student\G
*************************** 1. row ***************************
      Table: Student
Create Table: CREATE TABLE `student` (
   `Student_id` int(11) NOT NULL AUTO_INCREMENT,
   `Name` varchar(20) DEFAULT NULL,
   PRIMARY KEY (`Student_id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=latin1
1 row in set (0.00 sec)

On the other hand, SERIAL DEFAULT VALUE is shorthand for NOT NULL AUTO_INCREMENT UNIQUE KEY. The interger numeric type like TINYINT, SMALLINT, MEDIUMINT, INT, and BIGINT supports the SERIAL DEFAULT VALUE keyword.

Example

mysql> Create Table Student_serial(Student_id SERIAL, Name VArchar(20));
Query OK, 0 rows affected (0.17 sec)

mysql> Insert into Student_serial(Name) values('RAM'),('SHYAM');
Query OK, 2 rows affected (0.12 sec)
Records: 2 Duplicates: 0 Warnings: 0

mysql> Select * from Student_serial;
+------------+-------+
| Student_id | Name |
+------------+-------+
|          1 | RAM   |
|          2 | SHYAM |
+------------+-------+
2 rows in set (0.00 sec)

mysql> Show Create Table Student_serial\G
*************************** 1. row ***************************
      Table: Student_serial
Create Table: CREATE TABLE `student_serial` (
   `Student_id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
   `Name` varchar(20) DEFAULT NULL,
   UNIQUE KEY `Student_id` (`Student_id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=latin1
1 row in set (0.00 sec)
raja
Published on 19-Feb-2018 16:49:50
Advertisements