How to efficiently version records in an SQL database

后端 未结 4 1926
日久生厌
日久生厌 2021-02-10 14:41

In at least one application, I have the need to keep old versions of records in a relational database. When something should be updated, instead a new copy would be added and th

4条回答
  •  旧时难觅i
    2021-02-10 15:35

    I Know that this is an old post, But I wanted to reply not only to provide solution but also to exchange my ideas with you and also to discuss the most efficient solution for this important issue of versioning.

    My idea is,

    Create a table that contains 5 main versioning fields

    • Serial (Incremental number) is the real identifier and used for joins
    • ID (Self-Foreign key) is equal to the (Serial) Field value when the record is created
    • ValidFrom (Data from which the record became active)
    • ValidTo (Data to which the record became inactive) => Will be null for a current version
    • IsCurrent (Flag indicating that record is active)

    When updating a record

    • Update the field to set (ValidTo) to be NOW datetime and set (IsCurrent) to false

    • Insert a new record by increment the (Serial) Field and keeping the very same Field (ID) of the updated record, (ValidFrom) will be NOW and (ValidTo) will be null and IsCurrent will have false.

    When Deleting record

    ValidTo will be set to NOW time IsCurrent set to false

    by this way you will not have problems with joins as joining tables with field ID will show you all record history.

    IF you have FKs to a parent table , You probably want to remove the value of the FK field.

提交回复
热议问题