In this tutorial, we will learn how to fix MySQL issue “MySQL LAST_INSERT_ID() returning 0”.

Are you wondering why LAST_INSERT_ID() returned 0? We shall investigate the cause and fix this issue.

Fixing MySQL LAST_INSERT_ID() returning 0

MySQL LAST_INSERT_ID() returns a non-negative id of the last inserted record when you have column with AUTO_INCREMENT attribute and the column is added to index.

We shall take an example table and investigate the process to solve the issue.

Consider the following students table.

MySQL - Solve LAST_INSERT_ID returns 0

Now we shall add a column with AUTO_INCREMENT attribute.

ADVERTISEMENT
MySQL add column with AUTO_INCREMENT PRIMARY KEY

Try inserting a row to students table.

MySQL - Insert record into table

Now as there is an AUTO_INCREMENT column that is added to INDEX, lets try the LAST_INSERT_ID() function.

MySQL LAST_INSERT_ID() function solved