MySQL: getting the AUTO_INCREMENT value after adding a record

Applies to: MySQL as discussed in 2005; the Clarion version was not named.

Problem

Clarion's auto-number takes the next value by reading the biggest value in the table. MySQL assigns the value from an internal counter when the record is physically added, and the two are not necessarily the same. The poster needed the real value because the same procedure updates two other related tables.

Solution

  1. The MySQL function is LAST_INSERT_ID(). The poster understood that it needs an insert in the same session, and otherwise returns zero.
  2. A poster showed his file manager's approach: add the record, read LAST_INSERT_ID(), then fetch the record to get the whole record buffer:
Add(Self.File)
If Errorcode()
  Message(FileError())
  ReturnValue = Level:Fatal
  Exit
End
Self.File{Prop:Sql}='Select Last_Insert_Id()'
Next(Self.File)
Self.Fetch(AutoKey)
  1. He derived the PrimeAutoInc method to do this. Others do the same in a form, or override the Save button to add the record and retrieve it before child inserts are enabled.

Caveats

  • The result of PROP:SQL is fed into the record buffer, so the auto-increment field must be the very first field of the record structure for the value to land in the right field.
  • The original poster said he would try it; the thread does not report the outcome.
  • The same session must do the insert and the LAST_INSERT_ID() call.

Today (2026)

Not re-tested. LAST_INSERT_ID() is a MySQL feature and likely still behaves this way; check how your current driver handles server-generated keys before copying the pattern.

Sources: Rainer W. (Nov 2005, the question), Geoff B., Bjarne H. (Nov 2005) in softvelocity.clarion.databasedrivers.