• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 942
  • 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
Get expert help—faster!

Need expert help—fast? Use the Help Bell for personalized assistance getting answers to your important questions.

 
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: Port Scanner

Check which ports are open to the outside world. Helps make sure that your firewall rules are working as intended.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

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