Last Insert ID in MySQL

LAST_INSERT_ID() function return the AUTO_INCREMENT id of the last row that has been inserted or updated in a table.

Here is an example.

DROP TABLE IF EXISTS tbOrdersHeader;
CREATE TABLE tbOrdersHeader(
OrderID INT unsigned NOT NULL AUTO_INCREMENT PRIMARY KEY,
OrderDate DATETIME NOT NULL);

DROP TABLE IF EXISTS tbOrdersDetail;
CREATE TABLE tbOrdersDetail(
OrderDetailID INT unsigned NOT NULL AUTO_INCREMENT PRIMARY KEY,
OrderID INT NOT NULL REFERENCES tbOrdersHeader(OrderID),
ProductID INT NOT NULL);

BEGIN;
INSERT INTO tbOrdersHeader (OrderDate) VALUES(‘2023-03-14’);
INSERT INTO tbOrdersDetail (OrderID, ProductID) VALUES(LAST_INSERT_ID(),10012);
COMMIT;

SELECT * FROM tbOrdersHeader;
SELECT * FROM tbOrdersDetail;

MySQL_Last_Insert_ID
Hope you find this article helpful.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s