What is the difference between SERIAL and AUTO_INCREMENT in mysql

Mysql

Mysql Problem Overview


I have come across two ways to increment the ids in mysql automatically.

One is SERIAL and other is AUTOINCREMENT.

So Suppose i want to create a table myfriends. I can create it in two ways like:

mysql> create table myfriends(id int primary key auto_increment,frnd_name varchar(50) not null);
mysql> create table myfriends(id serial primary key,frnd_name varchar(50) not null);

What is difference between the two ?

OR

Do anyone way has advantages over other ?

Please Help.

Mysql Solutions


Solution 1 - Mysql

As per the docs

> SERIAL is an alias for BIGINT UNSIGNED NOT NULL AUTO_INCREMENT UNIQUE.

So, be careful when creating a reference to a SERIAL PK, since that reference column has to be of this exact type.

Solution 2 - Mysql

AUTO_INCREMENT is an attribute of a specific column of any numeric type (int or float), both signed and unsigned. When rows are inserted it automatically assigns sequential numbers, so you don't have to (e.g. by using LAST_INSERT_ID()). See http://dev.mysql.com/doc/refman/5.0/en/example-auto-increment.html

SERIAL is an alias that combines column type casting (BIGINT specifically), AUTO_INCREMENT, UNSIGNED and other attributes for a specific column (see quote from docs below). See https://dev.mysql.com/doc/refman/8.0/en/numeric-type-syntax.html

> SERIAL is an alias for BIGINT UNSIGNED NOT NULL AUTO_INCREMENT UNIQUE. > > SERIAL DEFAULT VALUE in the definition of an integer column is an alias for NOT NULL AUTO_INCREMENT UNIQUE.

Solution 3 - Mysql

From mysql doc

> SERIAL is an alias for BIGINT UNSIGNED NOT NULL AUTO_INCREMENT UNIQUE. > > SERIAL DEFAULT VALUE in the definition of an integer column is an > alias for NOT NULL AUTO_INCREMENT UNIQUE.

If no value is specified for the AUTO_INCREMENT column, MySQL assigned sequence numbers automatically. You can also explicitly assign NULL or 0 to the column to generate sequence numbers. MySQL doesn't automatically decrease the autoincrement value when you delete a row. Reasons are:

  • Danger of broken data integrity (imagine multiple users perform deletes or inserts...doubled entries may occur or worse)
  • Errors may occur when you use master slave replication or transactions

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser2737223View Question on Stackoverflow
Solution 1 - MysqlFilipe SilvaView Answer on Stackoverflow
Solution 2 - MysqlzamnutsView Answer on Stackoverflow
Solution 3 - MysqlDamodaranView Answer on Stackoverflow