Picture of Paul Silver

Paul Silver

Making websites for companies and helping advertise them

Retrieve the most recent record from a database

Sometimes you need to retrieve the most recently added field from a database, but you won't know what the ID number in the key field is. Here's some simple SQL to let you get the record, in Microsoft SQL and MySQL variations. It presumes you have a primary ID field (key field) with an auto-incrementing number in it. Just replace 'tablename' with the name of your table, and 'primaryidfield' with the name of your primary ID field and it will give you the most recent record.

MS SQL:

SELECT TOP 1 *
FROM tablename
ORDER BY primaryidfield DESC

MySQL:

SELECT *
FROM tablename
ORDER BY primaryidfield DESC
LIMIT 0,1

More code articles


Paul Silver. December 2004

© 2024 Paul Silver & Silver Web Services Ltd