Jump to content

Best Way To Retrieve Last Row


frustrated

Recommended Posts

Hello,

I'm trying to figure out what is the best or most optimzed way to go about the following situation. All I want to do is retrieve the last row inserted into a table. It happens that one of the fields in my table has a date field, so my plan was to do something like this.

[code]
$sql = "SELECT id, name, date FROM the_table ORDER BY date ASC LIMIT 1";
[/code]

So I think that's pretty self explanatory but I'm sure that's probably not the best way to go about to retrieving the last record.

Anyone have any feedback on this topic for me?
Link to comment
https://forums.phpfreaks.com/topic/3247-best-way-to-retrieve-last-row/
Share on other sites

[!--quoteo(post=339396:date=Jan 24 2006, 04:10 PM:name=frustrated)--][div class=\'quotetop\']QUOTE(frustrated @ Jan 24 2006, 04:10 PM) [snapback]339396[/snapback][/div][div class=\'quotemain\'][!--quotec--]
I'm trying to figure out what is the best or most optimzed way to go about the following situation. All I want to do is retrieve the last row inserted into a table. It happens that one of the fields in my table has a date field, so my plan was to do something like this.
[code]
$sql = "SELECT id, name, date FROM the_table ORDER BY date ASC LIMIT 1";
[/code]
[/quote]
If you want the last inserted row you probably should use descending order on date:
[code]
$sql = "SELECT id, name, date FROM the_table ORDER BY date DESC LIMIT 1";
[/code]
First, if you're just inserted this row, you can use LAST_INSERT_ID() to get that uid and do a quick lookup. Second, if this is not the case, you should be using the UID field to find the newest record -- just realize that this is _not_ a safe way to find the next uid, since this is not an ACID operation.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.