Improve company productivity with a Business Account.Sign Up

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 947
  • 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
A proven path to a career in data science

At Springboard, we know how to get you a job in data science. With Springboard’s Data Science Career Track, you’ll master data science  with a curriculum built by industry experts. You’ll work on real projects, and get 1-on-1 mentorship from a data scientist.

 
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
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

What Kind of Coding Program is Right for You?

There are many ways to learn to code these days. From coding bootcamps like Flatiron School to online courses to totally free beginner resources. The best way to learn to code depends on many factors, but the most important one is you. See what course is best for you.

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