views:

233

answers:

3

I need to be able to determine the order which rows have been inserted into a table (there are no updates). Can I use an identity column to do this? I know that there may be gaps, but are the values guaranteed to be increasing by insertion order?

+1  A: 

Yes. Any gaps caused by deletions will not be reused

Ed Harper
+5  A: 

Largely yes, as long as you don't ever reset it or insert rows with bulk copy, or use IDENTITY_INSERT. And of course assuming that you don't overflow the data-type (which could be impressive).

Marc Gravell
A: 

As discussed by Marc, yes you can with provisos

What you should do however to definitively fix the problem is add a column

dteInserted datetime not null default getdate()

Then you just select ordered by this.

Myself I automatically add such a column onto any 'data' table in any database I'm designing. Storage is cheap nowadays and timestamping the insertion date on a row is always useful at some point.

Cruachan
The trouble here is that if you insert rows fast enough (which we do in an import), you get duplicate datetimes since the granularity of a datetime is not small enough on SQL Server.
Jon
Hmm, good point, I'd rather been focusing on the idea that you'd be inserting through normal transactional database operations. OK, the answer then in that case is that identity is in order, but you should still include the timestamp because that will allow you to detect any issues....
Cruachan
... arising such as identity insets or resets or whatever that would invalidate the assumption.
Cruachan