In MySQL, both SERIAL and AUTO_INCRMENT are used to define a sequence as the default value of a field. But they are technically different.
All numeric data types except BIT and DECIMAL support the AUTO_INCRMENT attribute. There can be only one AUTO_INCRMENT field per table, and sequences generated by an AUTO_INCRMENT field in one table cannot be used in any other table.
This property requires a UNIQUE index on the field to ensure that the sequence has no duplicates. By default, the sequence starts at 1 and is incremented by 1 for each insertion.
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_INCRMENT.
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 short for NOT NULL AUTO_INCRMENT UNIQUE KEY. The SERIAL DEFAULT VALUE keyword is supported for integer numeric types such as TINYINT, SMALLINT, MEDIUMINT, INT, and BIGINT.
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)
The above is the detailed content of In MySQL, what is the difference between SERIAL and AUTO_INCRMENT?. For more information, please follow other related articles on the PHP Chinese website!