Q:

How to select last insert id without collision

I have a table:
CREATE TABLE MyTable (
  UserID BIGINT NOT NULL AUTO_INCREMENT,
  Name VARCHAR(50) NOT NULL,
  PRIMARY KEY (UserID));

Now I need to insert value and get last insert key for that value. Right now I do it like this:
using (MySqlConnection connection = new MySqlConnection(CONNECTION_STRING))
{
    connection.Open();
    string query = $"INSERT INTO MyTable VALUES('Bob');\n" +
                   $"SELECT last_insert_id();";

    MySqlCommand command = new MySqlCommand(query, connection);
    var dataReader = command.ExecuteReaderAsync();
    await dataReader;

    long id = -1;
    while (dataReader.Result.Read())
    {
        string idString = (dataReader.Result as IDataRecord)[0].ToString();
        id = long.Parse(idString);
    }

    return id;
}

But what if there will be to many queries in one time? Is it possible that 2 simultaneous commands execute INSERT query and then both return the same value via last_insert_id()? How can I make sure that last_insert_id() will return value corresponding to its INSERT inside one command?

A:

No, last_insert_id is maintained on a per-connection basis, so if two connections are running at the same time, one won't get the other's inserted value.

