SQL Best Practices - Ok to rely on auto increment field to sort rows chronologically?

后端 未结 7 1402
面向向阳花
面向向阳花 2021-01-01 18:52

I\'m working with a client who wants to add timestamps to a bunch of tables so that they may sort the records in those tables chronologically. All of the tables also have a

7条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-01-01 19:36

    You asked for "best practices", rather than "not terrible practices" so: no, you should not rely on an autoincremented primary key to establish chronology. One day you're going to introduce a change to the db design and that will break. I've seen it happen.

    A datetime column whose default value is GETDATE() has very little overhead (about as much as an integer) and (better still) tells you not just sequence but actual date and time, which often turns out to be priceless. Even maintaining an index on the column is relatively cheap.

    These days, I always put a CreateDate column data objects connected to real world events (such as account creation).

    Edited to add:

    If exact chronology is crucial to your application, you can't rely on either auto-increment or timestamps (since there can always be identical timestamps, no matter how high the resolution). You'll probably have to make something application-specific instead.

提交回复
热议问题