• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 301
  • Last Modified:

Retrieve the last 5 records added in MS SQL Database


Probably a simple question, but how could I retrieve the last 5 records added to a table? (assuming there is no id field to work with)

I know MS SQL supports a 'TOP' function to return the top # of results you specify.. so is there anyway to return the last 5 records efficiently?

1 Solution
Is there a data/time field that you could sort on?

If you do, sort it by desc and pick up the top 5. Otherwise, I am not familiar with any other way.

:) SD
Saqib KhanSenior DeveloperCommented:
Can You Do a Order By on a Field?

Order By [Field_Name] Desc
jacowheeAuthor Commented:
Sorry, I am trying to do this based on not using any field for sorting, just trying to collect the last five.

There is a dateadded field that I would have liked to use, but it doesn't have updated data (need to find a bug preventing it from updating) I was just looking for a quick fix.

Thanks for the comments.

          As adilkhan mention you can use your Primarykey and DESC order to find last five records.

SQL = "Select * from table ORDER BY PrimaryKeyID DESC;"

SET Rs = Conn.Execute(SQL)

if not rs.eof then
        do until rs.eof
               Count = Count + 1
                  'Display your last five records information here.
                 if Cint(Count) =  5 then
                            exit do
                 end if
End if

Hope this would be helpful.
Just a thought! Whats the difference between ...

> Order By [Field_Name] Desc


>Is there a data/time field that you could sort on?
> If you do, sort it by desc and pick up the top 5.

Anyway, I am glad it all worked out.
:) SD
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

Hire Technology Freelancers with Gigs

Work with freelancers specializing in everything from database administration to programming, who have proven themselves as experts in their field. Hire the best, collaborate easily, pay securely, and get projects done right.

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