In SQL Server 2008 and higher what is the best/safest/most correct way
1. SELECT MAX(Id) FROM Table
And if you mean select the ID of the last record inserted, its
SELECT @@IDENTITY FROM table
SELECT LAST(row_name) FROM table_name
You can try:
SELECT id FROM your_table WHERE id = (SELECT MAX(id) FROM your_table)
Where id
is a primary key of the your_table
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
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.