I have a table user
. It has columns id
and email
.
USER TABLE
id | email
1 | xxx@gmail.com
2 | yyy@gmail.com
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 = 'xxx@gmail.com';
END;
INSERT INTO user
(email)
VALUES
('xxx@gmail.com');
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.