views:

39

answers:

1

Could someone guide me on this. I am using EntityFramwork4 , I want to get the ID of the last row of a table. Could someone having experience using this tell me , how can i get the last id from a database table.

A: 

Relational databases have no intrinsic order. There is no such thing as "the last row." Even if there were, multiuser concurrency would make this meaningless.

Max(id) probably doesn't solve your issue due to concurrency. But since you haven't told us what the real problem you're trying to solve is, it's hard to be sure.

Craig Stuntz
"Relational databases have no intrinsic order" - Tables in SQL Server do if they have a clustered index defined.
Mitch Wheat
@Mitch, I know, but that's an implementation detail. The general case is still as I stated it. Also, it's not actually what @Kltis wants, I think. He's really looking for *his* last record, not *the* last record. Using `Max(id)` is a very bad idea. In addition to being likely wrong, it can be slow even when it does work.
Craig Stuntz
@Craig: " it can be slow " - sure anything can be slow. Depends on size of table, indexes, Server RAM etc...
Mitch Wheat
@Craig: You said "Relational databases have no intrinsic order" - that implies an implementation. We don't normally talk about Theoretical Relational databases.
Mitch Wheat
@Mitch: That there *might* be a clustered index does not necessarily imply that the "last" record in that index is either the "last" record the user inserted or the "last" record in the order he expects. I **suspect** he's looking for something along the lines of `SCOPE_IDENTITY`, but it's really hard to tell based on the minimal information in the question. It is doing @Kltis no favors to give answers to the wrong question. In other words: If he's really looking for `SCOPE_IDENTITY`, then using `.Max()` is the *wrong* way to do it.
Craig Stuntz
@Craig Stuntz : the poster states " I want to get the ID of the last row of a table" - that implies they want the highest ID, not the Id of the last inserted record.
Mitch Wheat
@Mitch: I can read. Misusing `Max` for `SCOPE_IDENTITY` is a *classic* mistake. Until he says why he wants the "last" record, there's not an answer I can be confident about.
Craig Stuntz
@Craig Stuntz: nevermind.
Mitch Wheat