You can use LAST_INSERT_ID().
Quoted from docs:
With no argument,
LAST_INSERT_ID() returns a
BIGINT UNSIGNED (64-bit) value representing the first automatically generated value successfully inserted for an
AUTO_INCREMENT column as a result of the most recently executed
INSERT statement. The value of
LAST_INSERT_ID() remains unchanged if no rows are successfully inserted.
With an argument,
LAST_INSERT_ID() returns an unsigned integer.
You can find an extended example in this chapter:
126.96.36.199 How to Get the Unique ID for the Last Inserted Row
CREATE TABLE T
ID INT AUTO_INCREMENT PRIMARY KEY,
INSERT INTO T (FOO) VALUES (100);
INSERT INTO T (FOO) VALUES (200);
INSERT INTO T (FOO) VALUES (300);
SELECT * FROM T WHERE ID = LAST_INSERT_ID();
ID | FOO
-: | --:
3 | 300
Let me add the advice Akina has pointed out in comments:
There is a problem. LAST_INSERT_ID() scope is connection. If connection pool used or reconnection occured, zero will be returned. One of the solutions is to execute all queries within stored procedure.