In SQL Server 2008 and higher what is the best/safest/most correct way
This question is related to
sql
sql-server
sql-server-2008
1. SELECT MAX(Id) FROM Table
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
And if you mean select the ID of the last record inserted, its
SELECT @@IDENTITY FROM table
I think this one will also work:
SELECT * FROM ORDER BY id DESC LIMIT 0 , 1
SELECT IDENT_CURRENT('Table')
You can use one of these examples:
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).
SELECT LAST(row_name) FROM table_name
One more way -
select * from <table> where id=(select max(id) from <table>)
Also you can check on this link -
Source: Stackoverflow.com