Link to home
Start Free TrialLog in
Avatar of jacowhee
jacowhee

asked on

Retrieve the last 5 records added in MS SQL Database

Hello,

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?

Thanks!
Avatar of sciber_dude
sciber_dude
Flag of United States of America image

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
ASKER CERTIFIED SOLUTION
Avatar of Saqib Khan
Saqib Khan
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of jacowhee
jacowhee

ASKER

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.
Hi,

          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
           rs.MoveNext
       LOOP
End if

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

> Order By [Field_Name] Desc

and

>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