Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Easy mysql question regarding primary keys and an insert

In mysql, how do I get the primary key used for an insert operation, when it is autoincrementing.

Basically, i want the new autoincremented value to be returned when the statement completes.

Thanks!

like image 631
MPX Avatar asked Oct 03 '08 00:10

MPX


People also ask

Why is it necessary to insert a primary key in a table?

A primary key is a field or set of fields with values that are unique throughout a table. Values of the key can be used to refer to entire records, because each record has a different value for the key.

Can we have two primary keys in a table in MySQL?

A table can have only ONE primary key; and in the table, this primary key can consist of single or multiple columns (fields).

Which is faster primary key and foreign key?

A primary key ensures unique row identification. This results in faster sorting, searching, and querying operations. A foreign key creates a link between two tables. It maintains referential integrity between the referencing column(s) and the referenced column(s).

What clause should be used to add a primary key to a table?

Include PRIMARY KEY in the ADD clause with the ALTER TABLE statement to add a primary key to a table definition. Before adding the primary key, you must ensure that the columns in the primary key column list are defined as NOT NULL. A primary key is a unique index and can be created only on not nullable columns.


1 Answers

Your clarification comment says that you're interested in making sure that LAST_INSERT_ID() doesn't give the wrong result if another concurrent INSERT happens. Rest assured that it is safe to use LAST_INSERT_ID() regardless of other concurrent activity. LAST_INSERT_ID() returns only the most recent ID generated during the current session.

You can try it yourself:

  1. Open two shell windows, run mysql client in each and connect to database.
  2. Shell 1: INSERT into a table with an AUTO_INCREMENT key.
  3. Shell 1: SELECT LAST_INSERT_ID(), see result.
  4. Shell 2: INSERT into the same table.
  5. Shell 2: SELECT LAST_INSERT_ID(), see result different from shell 1.
  6. Shell 1: SELECT LAST_INSERT_ID() again, see a repeat of earlier result.

If you think about it, this is the only way that makes sense. All databases that support auto-incrementing key mechanisms must act this way. If the result depends on a race condition with other clients possibly INSERTing concurrently, then there would be no dependable way to get the last inserted ID value in your current session.

like image 150
Bill Karwin Avatar answered Nov 04 '22 12:11

Bill Karwin