HiveBrain v1.2.0
Get Started
← Back to all entries
patternsqlMinor

Can a single SQL Server instance issue the same SYSDATETIME twice?

Submitted by: @import:stackexchange-dba··
0
Viewed 0 times
canthesametwicesqlsysdatetimeissueinstancesingleserver

Problem

I am contemplating using a datetime2(7) as a clustered index.

If I were to always populate that column using SYSDATETIME is it possible for the same instance to issue the same value twice (assuming we don't do something like set the system clock back)?

Alternatively, what is a cohesive strategy for ensuring uniqueness on such a column, even if it that comes at a cost of time precision?

For my use, I really only care about the seconds, but I will be doing a lot of range queries on this column so the CI seems appropriate.

Solution

Yes. The resolution of the Windows clock is decent, but not perfect. You should use another field, such as an INT IDENTITY, to ensure uniqueness. But go ahead and cluster on the date first, if it suits your needs.

Alternatively, you could use a DATETIME PK, but supervise inserts with a stored procedure that verifies the uniqueness of the incoming date, and pauses if necessary. I can whip up an example if you'd like.

Edit:

Another option, borrowing from ypercube's comment, would be a non-unique clustered index on the date field, and a unique non-clustered primary key on the ID field. This would keep your other indices smaller, as they would point to the narrow ID column, but would also entail two hops to get to actual data.

Context

StackExchange Database Administrators Q#51691, answer score: 2

Revisions (0)

No revisions yet.