views:

64

answers:

5

In SQL Server 2008 and higher what is the best/safest/most correct way

  1. to retrieve the ID (based on autoincrementing primary key) out of the database table?
  2. to retrieve the value of the last row of some other column (like, SELECT TOP 1 FROM Table ORDER BY DESC)?
+1  A: 

One more way -

select * from <table> where  id=(select max(id) from <table>)

Also you can check on this link -

http://msdn.microsoft.com/en-us/library/ms175098.aspx

Sachin Shanbhag
that's one more way but I am not sure if it doesn't suffer from the same possible issues that SELECT TOP..does. Would be nice if someone with deeper SQL knowledge comments on both solutions how reliable they are in a high volume usage scenarios.
mare
A: 
1.  SELECT MAX(Id) FROM Table
Michael Pakhantsov
+1  A: 

And if you mean select the ID of the last record inserted, its

SELECT @@IDENTITY FROM table
w69rdy
+1  A: 
SELECT IDENT_CURRENT('Table')

You can one of this examole:

SELECT * FROM Table 
WHERE ID = (
    SELECT IDENT_CURRENT('Table'))

SELECT * FROM Table
WHERE ID = (
    SELECT MAX(ID) FROM Table)

SELECT TOP 1 * FROM Table
ORDER BY ID DESC

But the first one will be more efficient because no index scan is needed (if you have index on Id column).

The second one solution is equivalent to the third (both of them need to scan table to get max id)

gyromonotron
+1  A: 

Safest way will be to output or return the scope_identity() within the procedure inserting the row, and then retrieve the row based on that ID. Use of @@Identity is to be avoided since you can get the incorrect ID when triggers are in play.

Any technique of asking for the maximum value / top 1 suffers a race condition where 2 people adding at the same time, would then get the same ID back when they looked for the highest ID.

Andrew
I read this article http://msdn.microsoft.com/en-us/library/ms190315.aspx about @@identity and scope_identity and it seems your answer is the most appropriate one. I have two additional questions before accepting the answer - if there is no insert before and we request scope_identity(), will it return anything? And another, if I was to create business keys in my application and then store them into the table, and I want them do derive from identity, is it fine to query for scope_identity()?
mare
If you fail to insert anything scope_identity() will return null; once you have returned scope_identity() and have the identity field, you can use it in queries to return to that row for whatever purposes you decide.
Andrew