<p>We have a requirement in project to store all the revisions(Change History) for the entities in the database. Currently we have 2 designed proposals for this:</p>

<p>e.g. for "Employee" Entity</p>

<p><strong>Design 1:</strong></p>

<pre><code>-- Holds Employee Entity
"Employees (EmployeeId, FirstName, LastName, DepartmentId, .., ..)"

-- Holds the Employee Revisions in Xml. The RevisionXML will contain
-- all data of that particular EmployeeId
"EmployeeHistories (EmployeeId, DateModified, RevisionXML)"
</code></pre>

<p><strong>Design 2:</strong></p>

<pre><code>-- Holds Employee Entity
"Employees (EmployeeId, FirstName, LastName, DepartmentId, .., ..)"

-- In this approach we have basically duplicated all the fields on Employees 
-- in the EmployeeHistories and storing the revision data.
"EmployeeHistories (EmployeeId, RevisionId, DateModified, FirstName, 
      LastName, DepartmentId, .., ..)"
</code></pre>

<p>Is there any other way of doing this thing? </p>

<p>The problem with the "Design 1" is that we have to parse XML each time when you need to access data. This will slow the process and also add some limitations like we cannot add joins on the revisions data fields.</p>

<p>And the problem with the "Design 2" is that we have to duplicate each and every field on all entities (We have around 70-80 entities for which we want to maintain revisions).</p>

[{'answer_id': 39296, 'author': 'Matthew Watson', 'author_id': 3839, 'author_profile': 'https://Stackoverflow.com/users/3839', 'pm_score': 3, 'selected': False, 'text': '<p>The way that I\'ve seen this done in the past is have</p>\n\n<pre><code>Employees (EmployeeId, DateModified, &lt; Employee Fields &gt; , boolean isCurrent );\n</code></pre>\n\n<p>You never "update" on this table (except to change the valid of isCurrent), just insert new rows. For any given EmployeeId, only 1 row can have isCurrent == 1. </p>\n\n<p>The complexity of maintaining this can be hidden by views and "instead of" triggers (in oracle, I presume similar things other RDBMS), you can even go to materialized views if the tables are too big and can\'t be handled by indexes).</p>\n\n<p>This method is ok, but you can end up with some complex queries.</p>\n\n<p>Personally, I\'m pretty fond of your Design 2 way of doing it, which is how I\'ve done it in the past as well. Its simple to understand, simple to implement and simple to maintain. </p>\n\n<p>It also creates very little overhead for the database and application, especially when performing read queries, which is likely what you\'ll be doing 99% of the time. </p>\n\n<p>It would also be quite easy to automatic the creation of the history tables and triggers to maintain (assuming it would be done via triggers).</p>\n'}, {'answer_id': 39297, 'author': 'mattruma', 'author_id': 1768, 'author_profile': 'https://Stackoverflow.com/users/1768', 'pm_score': 1, 'selected': False, 'text': "<p>We have had similar requirements, and what we found was that often times the user just wants to <strong>see</strong> what has been changed, not necessarily roll back any changes.  </p>\n\n<p>I'm not sure what your use case is, but what we have done was create and Audit table that is automatically updated with changes to an business  entity, including the friendly name of any foreign key references and enumerations.  </p>\n\n<p>Whenever the user saves their changes we reload the old object, run a comparison, record the changes, and save the entity (all are done in a single database transaction in case there are any problems).  </p>\n\n<p>This seems to work very well for our users and saves us the headache of having a completely separate audit table with the same fields as our business entity.</p>\n"}, {'answer_id': 39300, 'author': 'Chris Roberts', 'author_id': 475, 'author_profile': 'https://Stackoverflow.com/users/475', 'pm_score': 6, 'selected': False, 'text': "<p>I think the key question to ask here is 'Who / What is going to be using the history'?</p>\n\n<p>If it's going to be mostly for reporting / human readable history, we've implemented this scheme in the past...</p>\n\n<p>Create a table called 'AuditTrail' or something that has the following fields...</p>\n\n<pre><code>[ID] [int] IDENTITY(1,1) NOT NULL,\n[UserID] [int] NULL,\n[EventDate] [datetime] NOT NULL,\n[TableName] [varchar](50) NOT NULL,\n[RecordID] [varchar](20) NOT NULL,\n[FieldName] [varchar](50) NULL,\n[OldValue] [varchar](5000) NULL,\n[NewValue] [varchar](5000) NULL\n</code></pre>\n\n<p>You can then add a 'LastUpdatedByUserID' column to all of your tables which should be set every time you do an update / insert on the table.</p>\n\n<p>You can then add a trigger to every table to catch any insert / update that happens and creates an entry in this table for each field that's changed.  Because the table is also being supplied with the 'LastUpdateByUserID' for each update / insert, you can access this value in the trigger and use it when adding to the audit table.</p>\n\n<p>We use the RecordID field to store the value of the key field of the table being updated.  If it's a combined key, we just do a string concatenation with a '~' between the fields.</p>\n\n<p>I'm sure this system may have drawbacks - for heavily updated databases the performance may be hit, but for my web-app, we get many more reads than writes and it seems to be performing pretty well.  We even wrote a little VB.NET utility to automatically write the triggers based on the table definitions.</p>\n\n<p>Just a thought!</p>\n"}, {'answer_id': 39303, 'author': 'Steve Moon', 'author_id': 3660, 'author_profile': 'https://Stackoverflow.com/users/3660', 'pm_score': 0, 'selected': False, 'text': '<p>It sounds like you want to track changes to specific entities over time, e.g. ID 3, "bob", "123 main street", then another ID 3, "bob" "234 elm st", and so on, in essence being able to puke out a revision history showing every address "bob" has been at.</p>\n\n<p>The best way to do this is to have an "is current" field on each record, and (probably) a timestamp or FK to a date/time table.</p>\n\n<p>Inserts have to then set the "is current" and also unset the "is current" on the previous "is current" record. Queries have to specify the "is current", unless you want all of the history.</p>\n\n<p>There are further tweaks to this if it\'s a very large table, or a large number of revisions are expected, but this is a fairly standard approach.</p>\n'}, {'answer_id': 39308, 'author': 'Mendelt', 'author_id': 3320, 'author_profile': 'https://Stackoverflow.com/users/3320', 'pm_score': 2, 'selected': False, 'text': '<p>If you want to do the first one you might want to use XML for the Employees table too. Most newer databases allow you to query into XML fields so this is not always a problem. And it might be simpler to have one way to access employee data regardless if it\'s the latest version or an earlier version.</p>\n\n<p>I would try the second approach though. You could simplify this by having just one Employees table with a DateModified field. The EmployeeId + DateModified would be the primary key and you can store a new revision by just adding a row. This way archiving older versions and restoring versions from archive is easier too.</p>\n\n<p>Another way to do this could be the <a href="http://www.danlinstedt.com/" rel="nofollow noreferrer">datavault model</a> by Dan Linstedt. I did a project for the Dutch statistics bureau that used this model and it works quite well. But I don\'t think it\'s directly useful for day to day database use. You might get some ideas from reading his papers though.</p>\n'}, {'answer_id': 39313, 'author': 'aku', 'author_id': 1196, 'author_profile': 'https://Stackoverflow.com/users/1196', 'pm_score': 3, 'selected': False, 'text': '<p>Ramesh, I was involved in development of system based on first approach.<br>\nIt turned out that storing revisions as XML is leading to a huge database growth and significantly slowing things down.<br>\nMy approach would be to have one table per entity:</p>\n\n<pre><code>Employee (Id, Name, ... , IsActive)  \n</code></pre>\n\n<p>where <strong>IsActive</strong> is a sign of the latest version</p>\n\n<p>If you want to associate some additional info with revisions you can create separate table\ncontaining that info and link it with entity tables using PK\\FK relation.</p>\n\n<p>This way you can store all version of employees in one table.\nPros of this approach:</p>\n\n<ul>\n<li>Simple data base structure</li>\n<li>No conflicts since table becomes append-only</li>\n<li>You can rollback to previous version by simply changing IsActive flag</li>\n<li>No need for joins to get object history</li>\n</ul>\n\n<p>Note that you should allow primary key to be non unique.</p>\n'}, {'answer_id': 39358, 'author': 'Kjetil Watnedal', 'author_id': 4116, 'author_profile': 'https://Stackoverflow.com/users/4116', 'pm_score': 4, 'selected': False, 'text': '<p>We have implemented a solution very similar to the solution that Chris Roberts suggests, and that works pretty well for us.</p>\n\n<p>Only difference is that we only store the new value. The old value is after all stored in the previous history row </p>\n\n<pre><code>[ID] [int] IDENTITY(1,1) NOT NULL,\n[UserID] [int] NULL,\n[EventDate] [datetime] NOT NULL,\n[TableName] [varchar](50) NOT NULL,\n[RecordID] [varchar](20) NOT NULL,\n[FieldName] [varchar](50) NULL,\n[NewValue] [varchar](5000) NULL\n</code></pre>\n\n<p>Lets say you have a table with 20 columns. This way you only have to store the exact column that has changed instead of having to store the entire row.</p>\n'}, {'answer_id': 39360, 'author': 'Simon Munro', 'author_id': 3893, 'author_profile': 'https://Stackoverflow.com/users/3893', 'pm_score': 6, 'selected': True, 'text': "<ol>\n<li>Do <strong>not</strong> put it all in one table with an IsCurrent discriminator attribute.  This just causes problems down the line, requires surrogate keys and all sorts of other problems.</li>\n<li>Design 2 does have problems with schema changes.  If you change the Employees table you have to change the EmployeeHistories table and all the related sprocs that go with it.  Potentially doubles you schema change effort.</li>\n<li>Design 1 works well and if done properly does not cost much in terms of a performance hit.  You could use an xml schema and even indexes to get over possible performance problems.  Your comment about parsing the xml is valid but you could easily create a view using xquery - which you can include in queries and join to.  Something like this...</li>\n</ol>\n\n\n\n<pre><code>CREATE VIEW EmployeeHistory\nAS\n, FirstName, , DepartmentId\n\nSELECT EmployeeId, RevisionXML.value('(/employee/FirstName)[1]', 'varchar(50)') AS FirstName,\n\n  RevisionXML.value('(/employee/LastName)[1]', 'varchar(100)') AS LastName,\n\n  RevisionXML.value('(/employee/DepartmentId)[1]', 'integer') AS DepartmentId,\n\nFROM EmployeeHistories \n</code></pre>\n"}, {'answer_id': 40412, 'author': 'Hank Gay', 'author_id': 4203, 'author_profile': 'https://Stackoverflow.com/users/4203', 'pm_score': 2, 'selected': False, 'text': "<p>If indeed an audit trail is all you need, I'd lean toward the audit table solution (complete with denormalized copies of the important column on other tables, e.g., <code>UserName</code>). Keep in mind, though, that bitter experience indicates that a single audit  table will be a huge bottleneck down the road; it's probably worth the effort to create individual audit tables for all your audited tables.</p>\n\n<p>If you need to track the actual historical (and/or future) versions, then the standard solution is to track the same entity with multiple rows using some combination of start, end, and duration values. You can use a view to make accessing current values convenient. If this is the approach you take, you can run into problems if your versioned data references mutable but unversioned data.</p>\n"}, {'answer_id': 126468, 'author': 'Mark Streatfield', 'author_id': 17489, 'author_profile': 'https://Stackoverflow.com/users/17489', 'pm_score': 5, 'selected': False, 'text': '<p>The <a href="http://database-programmer.blogspot.com/2008/07/history-tables.html" rel="noreferrer">History Tables</a> article in the <a href="http://database-programmer.blogspot.com/" rel="noreferrer">Database Programmer</a> blog might be useful - covers some of the points raised here and discusses the storage of deltas.</p>\n\n<p><strong>Edit</strong></p>\n\n<p>In the <a href="http://database-programmer.blogspot.com/2008/07/history-tables.html" rel="noreferrer">History Tables</a> essay, the author (<a href="http://database-programmer.blogspot.co.uk/p/about-author.html" rel="noreferrer">Kenneth Downs</a>), recommends maintaining a history table of at least seven columns:</p>\n\n<ol>\n<li>Timestamp of the change,</li>\n<li>User that made the change,</li>\n<li>A token to identify the record that was changed (where the history is maintained separately from the current state),</li>\n<li>Whether the change was an insert, update, or delete,</li>\n<li>The old value,</li>\n<li>The new value,</li>\n<li>The delta (for changes to numerical values).</li>\n</ol>\n\n<p>Columns which never change, or whose history is not required, should not be tracked in the history table to avoid bloat.  Storing the delta for numerical values can make subsequent queries easier, even though it can be derived from the old and new values.</p>\n\n<p>The history table must be secure, with non-system users prevented from inserting, updating or deleting rows.  Only periodic purging should be supported to reduce overall size (and if permitted by the use case).</p>\n'}, {'answer_id': 215308, 'author': 'gregmac', 'author_id': 7913, 'author_profile': 'https://Stackoverflow.com/users/7913', 'pm_score': 2, 'selected': False, 'text': '<p>How about:</p>\n\n<ul>\n<li>EmployeeID</li>\n<li>DateModified \n\n<ul>\n<li><em>and/or revision number, depending on how you want to track it</em></li>\n</ul></li>\n<li>ModifiedByUSerId\n\n<ul>\n<li><em>plus any other information you want to track</em></li>\n</ul></li>\n<li><em>Employee fields</em></li>\n</ul>\n\n<p>You make the primary key (EmployeeId, DateModified), and to get the "current" record(s) you just select MAX(DateModified) for each employeeid.  Storing an IsCurrent is a very bad idea, because first of all, it can be calculated, and secondly, it is far too easy for data to get out of sync. </p>\n\n<p>You can also make a view that lists only the latest records, and mostly use that while working in your app. The nice thing about this approach is that you don\'t have duplicates of data, and you don\'t have to gather data from two different places (current in Employees, and archived in EmployeesHistory) to get all the history or rollback, etc).</p>\n'}, {'answer_id': 402788, 'author': 'Henrik Gustafsson', 'author_id': 2010, 'author_profile': 'https://Stackoverflow.com/users/2010', 'pm_score': 2, 'selected': False, 'text': '<p>Revisions of data is an aspect of the \'<a href="http://en.wikipedia.org/wiki/Temporal_database#Valid_Time" rel="nofollow noreferrer">valid-time</a>\' concept of a Temporal Database. Much research has gone into this, and many patterns and guidelines have emerged. I wrote a lengthy reply with a bunch of references to <a href="https://stackoverflow.com/questions/310963/relational-schema-for-fowlers-temporal-expressions#312534">this</a> question for those interested.</p>\n'}, {'answer_id': 1042848, 'author': 'dariol', 'author_id': 3644960, 'author_profile': 'https://Stackoverflow.com/users/3644960', 'pm_score': 2, 'selected': False, 'text': '<p>If you want to rely on history data (for reporting reasons) you should use structure something like this:</p>\n\n<pre><code>// Holds Employee Entity\n"Employees (EmployeeId, FirstName, LastName, DepartmentId, .., ..)"\n\n// Holds the Employee revisions in rows.\n"EmployeeHistories (HistoryId, EmployeeId, DateModified, OldValue, NewValue, FieldName)"\n</code></pre>\n\n<p>Or global solution for application:</p>\n\n<pre><code>// Holds Employee Entity\n"Employees (EmployeeId, FirstName, LastName, DepartmentId, .., ..)"\n\n// Holds all entities revisions in rows.\n"EntityChanges (EntityName, EntityId, DateModified, OldValue, NewValue, FieldName)"\n</code></pre>\n\n<p>You can save your revisions also in XML, then you have only one record for one revision. This will be looks like:</p>\n\n<pre><code>// Holds Employee Entity\n"Employees (EmployeeId, FirstName, LastName, DepartmentId, .., ..)"\n\n// Holds all entities revisions in rows.\n"EntityChanges (EntityName, EntityId, DateModified, XMLChanges)"\n</code></pre>\n'}, {'answer_id': 3776519, 'author': 'ConcernedOfTunbridgeWells', 'author_id': 15401, 'author_profile': 'https://Stackoverflow.com/users/15401', 'pm_score': 4, 'selected': False, 'text': "<p>If you have to store history, make a shadow table with the same schema as the table you are tracking and a 'Revision Date' and 'Revision Type' column (e.g. 'delete', 'update').  Write (or generate - see below) a set of triggers to populate the audit table.</p>\n\n<p>It's fairly straightforward to make a tool that will read the system data dictionary for a table and generate a script that creates the shadow table and a set of triggers to populate it.</p>\n\n<p>Don't try to use XML for this, XML storage is a lot less efficient than the native database table storage that this type of trigger uses.</p>\n"}, {'answer_id': 17002243, 'author': 'Tomas', 'author_id': 684229, 'author_profile': 'https://Stackoverflow.com/users/684229', 'pm_score': 4, 'selected': False, 'text': "<p>Avoid Design 1; it is not very handy once you will need to for example rollback to old versions of the records - either automatically or &quot;manually&quot; using administrators console.</p>\n<p>I don't really see disadvantages of Design 2. I think the second, History table should contain all columns present in the first, Records table. E.g. in mysql you can easily create table with the same structure as another table (<code>create table X like Y</code>). And, when you are about to change structure of the Records table in your live database, you have to use <code>alter table</code> commands anyway - and there is no big effort in running these commands also for your History table.</p>\n<p>Notes</p>\n<ul>\n<li>Records table contains only lastest revision;</li>\n<li>History table contains all previous revisions of records in Records table;</li>\n<li>History table's primary key is a primary key of the Records table with added <code>RevisionId</code> column;</li>\n<li>Think about additional auxiliary fields like <code>ModifiedBy</code> - the user who created particular revision. You may also want to have a field <code>DeletedBy</code> to track who deleted particular revision.</li>\n<li>Think about what <code>DateModified</code> should mean - either it means where this particular revision was created, or it will mean when this particular revision was replaced by another one. The former requires the field to be in the Records table, and seems to be more intuitive at the first sight; the second solution however seems to be more practical for deleted records (date when this particular revision was deleted). If you go for the first solution, you would probably need a second field <code>DateDeleted</code> (only if you need it of course). Depends on you and what you actually want to record.</li>\n</ul>\n<p>Operations in Design 2 are very trivial:</p>\n<strong>Modify</strong>\n<ul>\n<li>copy the record from Records table to History table, give it new RevisionId (if it is not already present in Records table), handle DateModified (depends on how you interpret it, see notes above)</li>\n<li>go on with normal update of the record in Records table</li>\n</ul>\n<strong>Delete</strong>\n<ul>\n<li>do exactly the same as in the first step of Modify operation. Handle DateModified/DateDeleted accordingly, depending on the interpretation you have chosen.</li>\n</ul>\n<strong>Undelete (or rollback)</strong>\n<ul>\n<li>take highest (or some particular?) revision from History table and copy it to the Records table</li>\n</ul>\n<strong>List revision history for particular record</strong>\n<ul>\n<li>select from History table and Records table</li>\n<li>think what exactly you expect from this operation; it will probably determine what information you require from DateModified/DateDeleted fields (see notes above)</li>\n</ul>\n<p>If you go for Design 2, all SQL commands needed to do that will be very very easy, as well as maintenance! Maybe, it will be much much easier <strong>if you use the auxiliary columns (<code>RevisionId</code>, <code>DateModified</code>) also in the Records table - to keep both tables at exactly the same structure</strong> (except for unique keys)! This will allow for simple SQL commands, which will be tolerant to any data structure change:</p>\n<pre><code>insert into EmployeeHistory select * from Employe where ID = XX\n</code></pre>\n<p>Don't forget to use transactions!</p>\n<p><strong>As for the scaling</strong>, this solution is very efficient, since you don't transform any data from XML back and forth, just copying whole table rows - very simple queries, using indices - very efficient!</p>\n"}, {'answer_id': 17043060, 'author': 'Mehran', 'author_id': 866082, 'author_profile': 'https://Stackoverflow.com/users/866082', 'pm_score': 2, 'selected': False, 'text': '<p>I\'m going to share with you my design and it\'s different from your both designs in that it requires one table per each entity type. I found the best way to describe any database design is through ERD, here\'s mine:</p>\n\n<p><img src="https://i.stack.imgur.com/wADNp.png" alt="enter image description here"></p>\n\n<p>In this example we have an entity named <em>employee</em>. <em>user</em> table holds your users\' records and <em>entity</em> and <em>entity_revision</em> are two tables which hold revision history for all the entity types that you will have in your system. Here\'s how this design works:</p>\n\n<p><b>The two fields of <em>entity_id</em> and <em>revision_id</em></b></p>\n\n<p>Each entity in your system will have a unique entity id of its own. Your entity might go through revisions but its entity_id will remain the same. You need to keep this entity id in you employee table (as a foreign key). You should also store the type of your entity in the <em>entity</em> table (e.g. \'employee\'). Now as for the revision_id, as its name shows, it keep track of your entity revisions. The best way I found for this is to use the <em>employee_id</em> as your revision_id. This means you will have duplicate revision ids for different types of entities but this is no treat to me (I\'m not sure about your case). The only important note to make is that the combination of entity_id and revision_id should be unique.</p>\n\n<p>There\'s also a <em>state</em> field within <em>entity_revision</em> table which indicated the state of revision. It can have one of the three states: <code>latest</code>, <code>obsolete</code> or <code>deleted</code> (not relying on the date of revisions helps you a great deal to boost your queries).</p>\n\n<p>One last note on revision_id, I didn\'t create a foreign key connecting employee_id to revision_id because we don\'t want to alter entity_revision table for each entity type that we might add in future.</p>\n\n<p><strong>INSERTION</strong></p>\n\n<p>For each <em>employee</em> that you want to insert into database, you will also add a record to <em>entity</em> and <em>entity_revision</em>. These last two records will help you keep track of by whom and when a record has been inserted into database.</p>\n\n<p><strong>UPDATE</strong></p>\n\n<p>Each update for an existing employee record will be implemented as two inserts, one in employee table and one in entity_revision. The second one will help you to know by whom and when the record has been updated.</p>\n\n<p><strong>DELETION</strong></p>\n\n<p>For deleting an employee, a record is inserted into entity_revision stating the deletion and done.</p>\n\n<p>As you can see in this design no data is ever altered or removed from database and more importantly each entity type requires only one table. Personally I find this design really flexible and easy to work with. But I\'m not sure about you as your needs might be different.</p>\n\n<p><strong>[UPDATE]</strong></p>\n\n<p>Having supported partitions in the new MySQL versions, I believe my design also comes with one of the best performances too. One can partition <code>entity</code> table using <code>type</code> field while partition <code>entity_revision</code> using its <code>state</code> field. This will boost the <code>SELECT</code> queries by far while keep the design simple and clean.</p>\n'}]
['https://Stackoverflow.com/questions/39281', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/191/']