Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Last id value in a table. SQL Server

Is there a way to know the last nth id field of a table, without scanning it completely? (just go to the end of table and get id value)

table
id   fieldvalue
1    2323
2    4645
3    556
...  ...
100000000  1232

So for example here n = 100000000 100 Million

--------------EDIT----- So which one of the queries proposed would be more efficient?

like image 515
edgarmtze Avatar asked Feb 25 '11 04:02

edgarmtze


2 Answers

SELECT MAX(id) FROM <tablename>
like image 156
rayman86 Avatar answered Nov 02 '22 20:11

rayman86


Assuming ID is the IDENTITY for the table, you could use SELECT IDENT_CURRENT('TABLE NAME').

See here for more info.

One thing to note about this approach: If you have INSERTs that fail but increment the IDENTITY counter, then you will get back a result that is higher than the result returned by SELECT MAX(id) FROM <tablename>

like image 30
rsbarro Avatar answered Nov 02 '22 20:11

rsbarro