I am currently working on a problem that I have an inelegant solution for. I am storing multiple versions of one record in a table. A good example would be the versions of a document. I have multiple entries for one document. I have a column called Code that stores an ID unique to the document. Each row also has an Active field (boolean) that indicates that the record is either “Active” (the latest version) or “Inactive”. In this case, only the latest version can be active. I am doing this to ease querying the data (instead of taking the top one of each document).
My data might look like this:
Code Active VersionNo
ABYY 0 1
RRUP 0 1
RRUP 0 2
ABYY 0 2
ABYY 0 3
ABYY 1 4
RRUP 1 3
My issue is that when I delete a record, I want to make sure that the document has one record (the latest one) marked as active. Here are three scenarios:
- I delete version 4 of document ABYY – I want to make version 3 of that document Active.
- I delete version 3 of document ABYY – I want to ensure that version 4 is still marked Active.
- (the tricky one) I delete version 3 of document ABYY. Later I decide to delete version 4. – I want version 2 to be marked Active, which means you can’t just subtract 1 from the version number.
Instead of creating a complicated query based off of specific data, I would rather create a generic query that set the Active fields to 0 for all documents except the one with the highest version number, which it would set to 1 instead. In this way, I could re-use the same query as a “clean-up” script if I was unsure of the data for a particular document.
Right now I’m stuck on two queries and the second is a bit long. Here is what I do:
UPDATE documents
SET Active = 0
WHERE Code = 'ABYY';
UPDATE documents u
SET Active = 1
WHERE id = (SELECT TOP 1 id
FROM documents
WHERE Code = 'ABYY'
ORDER BY VersionNo DESC);
Could I possibly collapse these queries into one query (preferably simpler too)? I’m writing this for SQLite (latest version).
Try: