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

Useful books
Cover of Transact-SQL Programming
Transact SQL Programming (inc MS SQL Server 7)
Amazon UK | USA
Cover of T-SQL Programming
Code Centric: T-SQL Programming
Amazon UK | USA
Cover of Guru's Guide to Transact SQL
The Guru's Guide to Transact SQL
Amazon UK | USA

Paul Silver. December 2004


Silver Web Services Ltd

© 2014 Paul Silver