I would like to use a SELECT statement that would get the most recently added item to a MySQL database. How would I do this? What type of MySQL column in my table would I use to track what has been most recently added?
First of all, Vinay's suggestion will not work, since more recent versions of MySQL will fill in "holes" in the auto-increment order. For example, if you delete entry 25 of 30, then the next inserted entry will be given ID 25 to fill in the hole that was left by the deleted item. In this case, entry 30 would be incorrectly identified as the most recent entry.
a00's suggestion to use a TIMESTAMP column is closer to what you need. In MySQL, a column of type TIMESTAMP will be assigned the current date and time (in the format "YYYYMMDDHHMMSS") both when the entry is inserted and whenever one of the other columns is updated, as long as you don't specify a value for the TIMESTAMP column yourself.
You can use such a column to select the most recently inserted or updated entries using the following SELECT query:
SELECT * FROM tblName ORDER BY timeStampColName DESC LIMIT 1
You can change the limit if, for example, you want the five most recently inserted or updated entries.
Unfortunately, this is no good either because you asked for the most recently added item, and the timestamp column method will also see updated entries as "new".
What I'd suggest is to use a column of type DATE and assign it a value of CURDATE() when you insert a new item. Then you can use the above query (using your date column in place of the timestamp column) to pick the most recently added entry or entries.
Bookmarks