I have a table user
. It has columns id
and email
.
USER TABLE
id | email
1 | [email protected]
2 | [email protected]
The id
is a PRIMARY KEY AUTO_INCREMENT
and the email
is an UNIQUE KEY
.
When I insert a new row in the table and there is a DUPLICATE KEY
exception thrown. I want to fetch the id
on which the DUPLICATE KEY
exception was thrown.
Right now I am doing this -
BEGIN
DECLARE EXIT HANDLER FOR 1062
BEGIN
SELECT id
INTO id
FROM user
WHERE email = '[email protected]';
END;
INSERT INTO user
(email)
VALUES
('[email protected]');
SELECT LAST_INSERT_ID() INTO id;
END;
I want to know if there is a better way to do this. That is to avoid scanning the table again to get the id for which it had already scanned to check the uniqueness of the email.