Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 General SQL Server Forums
 New to SQL Server Programming
 Retrieve the last record of a table

Author  Topic 

spider3
Starting Member

11 Posts

Posted - 2007-07-10 : 04:34:46
Hi!
I needto find the last record that has been inserted on a table.
If I perform a SELCT * FROM mytable , will I receive the data based on the inserted order (natural order)? In that case i'll simply need to check the last record of the results I got in my application to find the last inserted one?
(no I am not looking for an identity number ^^)

thank you

harsh_athalye
Master Smack Fu Yak Hacker

5581 Posts

Posted - 2007-07-10 : 04:39:00
You can't rely on the order in which the SELECT statement fetch records unless you specify ORDER BY. To determine First or Last record, you have specify column which can be used to specify order (e.g. inserted_date column).

Harsh Athalye
India.
"The IMPOSSIBLE is often UNTRIED"
Go to Top of Page

madhivanan
Premature Yak Congratulator

22864 Posts

Posted - 2007-07-10 : 06:37:43
If you use identity column or datetime as default value,then find maximum on that

Madhivanan

Failing to plan is Planning to fail
Go to Top of Page

Kristen
Test

22859 Posts

Posted - 2007-07-10 : 06:41:47
"I needto find the last record that has been inserted on a table"

SELECT TOP 1 * FROM mytable ORDER BY SomeColumn DESCENDING

[SomeColumn] needs to reflect the insertion order - e.g. IDENTITY or Date/Time

Relational Databases don't have any inherent order to the data - if another query has just run, selecting part of the data, that will influence the order that SQL Server "sees" the data in the next query.

So you need a column that defines the "insertion order"

"(no I am not looking for an identity number ^^)"

I reckon you probably are

Kristen
Go to Top of Page

LoztInSpace
Aged Yak Warrior

940 Posts

Posted - 2007-07-11 : 02:22:24
There should be a standard sticky topic for this question!
And another one for "how do I get my rows into columns".
Go to Top of Page

spider3
Starting Member

11 Posts

Posted - 2007-07-12 : 04:52:15
thank you for your suggestions - the previous system was based on dBase and there was a kind of natural order that was used to retrieve this value. Of course having an identity date/time insertion is more simple ^_^
Go to Top of Page

madhivanan
Premature Yak Congratulator

22864 Posts

Posted - 2007-07-12 : 05:02:08
Is there a meaning for ^_^?

Madhivanan

Failing to plan is Planning to fail
Go to Top of Page
   

- Advertisement -