tags:

views:

4436

answers:

4

What is the most efficient way to read the last row with SQL? The table is indexed on a unique key--the "bottom" key values represent the last row.

Edit: This is for SQL Server.

Thank you

rp

+1  A: 

You'll need some sort of uniquely identifying column in your table, like an auto-filling primary key or a datetime column (preferably the primary key). Then you can do this:

SELECT * FROM table_name ORDER BY unique_column DESC LIMIT 1

The ORDER BY column tells it to rearange the results according to that column's data, and the DESC tells it to reverse the results (thus putting the last one first). After that, the LIMIT 1 tells it to only pass back one row.

wbowers
MSSQL does not use LIMIT
Vinko Vrsalovic
Wow, harsh, the original question didn't even say SQL Server specifically. The above solution is perfectly legitimate even though SQL Server uses different words to describe the same concept. +1
Greg Hewgill
+3  A: 
select whatever,columns,you,want from mytable
 where mykey=(select max(mykey) from mytable);
Adam Pierce
+17  A: 

If you're using MS SQL, you can try:

SELECT TOP 1 * FROM table_Name ORDER BY unique_column DESC
Darksider
A: 

In order to retrieve the last row of a table for MS SQL database 2005, You can use the following query:

select top 1 column_name from table_name order by column_name desc;

// Note: To get the first row of the table for MS SQL database 2005, You can use the following query:

select top 1 column_name from table_name;