Go Premium for a chance to win a PS4. Enter to Win

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 936
  • Last Modified:

Sql Server 2008 Express R2 select max id

I am using select max id in a query (SELECT MAX(id) FROM table), but it gives me the impression that sometimes the value returned is not the last id. What better way to get the last record.
0
rflorencio
Asked:
rflorencio
4 Solutions
 
Patrick MatthewsCommented:
Depending on how that id value is generated, the maximum value is not necessarily the last value added to the table.  (If you are using that as an identity column, then you would typically expect the max and the "last" value to be the same.)

Your query will always return the maximum value in that column at runtime.

Now, depending on how that id value is determined, and how frequently values are added to the column, that query result may get "out of date" very quickly...
0
 
Robby SwartenbroekxMSP engineerCommented:
If it is the key column of the table, it is better to configure it as an automaticaly incremental generated number.
0
 
Eugene ZCommented:
SELECT MAX(id) FROM table is normally returns max  value
What made  you think it is incorrect?
\-----what is ID datatype in your table?


---

if id is identity int column


you can  use SCOPE_IDENTITY()
Returns the last identity value inserted into an identity column in the same scope. A scope is a module: a stored procedure, trigger, function, or batch. Therefore, two statements are in the same scope if they are in the same stored procedure, function, or batch.
0
Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
rshqCommented:
Hi

  Maybe type of Id is problem.
  For example if  type of Id is int or nvarchar sort order is different.
0
 
nishant joshiTechnology Development ConsultantCommented:
Rows in tables are sorted in order of key on which you have created clustered index.Clustered index puts data in sorted.

so max function will never give you last row.if your key is identity or always incremental then only max will give you last record.


Thanks,
Nishant
0

Featured Post

Free Tool: ZipGrep

ZipGrep is a utility that can list and search zip (.war, .ear, .jar, etc) archives for text patterns, without the need to extract the archive's contents.

One of a set of tools we're offering as a way to say thank you for being a part of the community.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now