title: Get the id of a row when UNIQUE KEY is violated
body: <p>I have a table <code>user</code>. It has columns <code>id</code> and <code>email</code>.</p>
  
  <p>USER TABLE</p>
  
  <pre><code>id | email
  1  | xxx@gmail.com
  2  | yyy@gmail.com
  </code></pre>
  
  <p>The <code>id</code> is a <code>PRIMARY KEY AUTO_INCREMENT</code> and the <code>email</code> is an <code>UNIQUE KEY</code>.
  When I insert a new row in the table and there is a <code>DUPLICATE KEY</code> exception thrown. I want to fetch the <code>id</code> on which the <code>DUPLICATE KEY</code> exception was thrown.</p>
  
  <p>Right now I am doing this - </p>
  
  <pre><code>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;
  </code></pre>
  
  <p>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. </p>