Get the ID of a newly created record from a ColdFusion insert query using CFquery result attribute

When inserting a new row to a mySQL database table using <cfquery>, it is often necessary to find the ID of the new record so you can refer to it in subsequent queries or other code further down the page.

There are a few ways to do this, but I like this one best:



<cfquery name="insertRecord" datasource="#request.dsn#" result="insertResult">
INSERT INTO my_table
(
column_1,
column_2,
etc
)
VALUES
(
'#value1#',
'#value2#',
'etc'
)
</cfquery>

<cfset newID = insertResult.generated_Key>

Notice the "result" attribute of the cfquery tag, which will accept any variable name you want to use. Then, immediately following the query code, we simple get the 'generated_Key' node of the result value, and voila - we have the ID of the new record, ready for whatever is needed next.

(Note: This example is for mySQL - not sure how this plays out in MS SQL or other DB engines... your mileage may vary.)

Comments (Comment Moderation is enabled. Your comment will not appear until approved.)
Remember that it differs from DB engine (for some dumb reason)
# Author Raul Riera | 8/27/09 4:13 PM
Good point - I updated that post to say 'mySQL'
thanks
# Author Michael Evangelista | 8/27/09 4:34 PM
According to the documentation it's MySQL only:

result_name.GENERATED_KEY
MySQL only. The ID of an inserted row. MySQL 3 does not support this feature.
# Author Gabriel | 8/27/09 5:02 PM
Its the various different names as stated by the database -- the docs cover it further.

In CF9 its both those names and a generic one. The exact name of which I have forgotten.
# Author Sam Farmer | 8/27/09 5:26 PM
In MS-SQL 2005 (and I guess 2000) it's IDENTITYCOL :
<cfset newID = insertResult.identitycol>
# Author Marius Milosav | 8/27/09 6:21 PM
blogcfc 5.9.1.002 by raymond camden
contact michael evangelista