Course contentsShow
← Databases & SQL
Lesson 156 of 1,9532. Querying and Data RetrievalFree lesson

Version-Based Record Filtering

Retrieve specific versions of mutable records within an entity-versioning system.

In this lesson, you will learn how to accurately isolate specific snapshots of data within tables that track historical changes rather than overwriting existing records.

The Problem: Mutable Data in Immutable Storage

In many database designs, we don't UPDATE a record when information changes. Instead, we insert a brand new row with a incremented version number, keeping the old record for historical audit purposes. This is common in document management or complex configuration systems. If you simply run SELECT * FROM products WHERE name = 'Widget', you might get five different versions of the same product, which causes duplication errors in your application.

The Strategy: Filtering for the "Active" or "Target" Version

To retrieve the exact record you need, you must filter by two distinct criteria: the unique identifier (the logical ID) and the specific version criteria.

There are two common ways to do this:

1. Retrieving the Latest Version

If you want the most recent state of an entity, you often join the table against a subquery that identifies the maximum version number per record:

SELECT p.*
FROM products p
JOIN (
    SELECT id, MAX(version_number) as max_v
    FROM products
    GROUP BY id
) latest ON p.id = latest.id AND p.version_number = latest.max_v;

2. Retrieving a Historical Version

If you need to see what a record looked like at a specific point in time or a specific version state, you simply add an equality constraint:

SELECT * 
FROM products 
WHERE id = 501 
  AND version_number = 3;

Why This Matters

When your data stores history as a series of rows, "the record" is no longer defined by a primary key alone. It is defined by the combination of a logical_id and a version_identifier. By consistently applying these filters, you avoid the "duplicate record" trap and ensure your queries return exactly one valid state of the data, rather than a list of every edit made since the record was created.

Key Takeaway: When using versioning, a unique record is defined by the combination of its identity and its version number; you must filter by both to avoid retrieving multiple historical snapshots of the same entity.