Databases & SQL Master Course — 079. Temporal and Historical Modeling
Lesson 079 Temporal and Historical Modeling
Prerequisites and objectives
You understand current-state tables and the difference between a cache and a historical fact. You will model effective intervals, query an as-of value, test boundary behavior, and distinguish business-effective time from the time the database learned a fact. The examples use controlled date strings and one fictional currency.
Create the practice fixture
Use a fresh disposable SQLite database. Product P1 costs 500 cents from January first until February first, then 600 cents from February first onward. valid_to is exclusive; NULL means there is no recorded end. The CHECK orders endpoints but does not validate every possible date string or prevent overlaps across rows.
CREATE TABLE price_history (
version_id INTEGER PRIMARY KEY,
product_code TEXT NOT NULL,
valid_from TEXT NOT NULL,
valid_to TEXT,
price_cents INTEGER NOT NULL CHECK(price_cents>=0),
CHECK(valid_to IS NULL OR valid_to>valid_from)
);
INSERT INTO price_history VALUES
(1,'P1','2026-01-01','2026-02-01',500),
(2,'P1','2026-02-01',NULL,600);
Choose the question history must answer
A current-state row answers what is true now. An effective-dated row answers what value applies at a stated business time. An event records an occurrence, such as a price-change instruction. A snapshot records an observed or agreed value at a particular point. These approaches can coexist, but they are not interchangeable.
Here the requirement is to answer the applicable catalog price on a calendar day. It is not to reconstruct the price originally printed on a completed order, which should retain its own agreed-price fact. Nor does this simple model tell us what the database believed about January at different later recording times.
Use half-open intervals
The interval includes valid_from and excludes valid_to. A value exactly on February first belongs to the second interval only. This convention lets adjacent intervals meet without double-counting their shared boundary. Avoid BETWEEN for this membership test because BETWEEN includes both endpoints.
SELECT version_id,price_cents FROM price_history WHERE product_code='P1' AND valid_from<='2026-01-31' AND (valid_to IS NULL OR '2026-01-31'<valid_to) ORDER BY version_id;
SELECT version_id,price_cents FROM price_history WHERE product_code='P1' AND valid_from<='2026-02-01' AND (valid_to IS NULL OR '2026-02-01'<valid_to) ORDER BY version_id;
The two queries return different versions at the exact change boundary. A well-formed effective history should return at most one version for this question. Zero rows can mean the date predates coverage or lies in a gap; several rows can mean overlapping history. Neither outcome should be silently repaired by taking the first row.

Separate row validity from interval consistency
The endpoint CHECK prevents an individual interval ending before or at its start. It does not compare that interval with other rows. Two individually valid intervals can overlap. Detecting or preventing overlaps requires cross-row reasoning and a coordinated write strategy; a simple primary key on version_id does not solve it.
Likewise, one open-ended interval per product is not the whole problem. A closed interval can overlap another closed interval, and a future closed interval can overlap an existing open one. Review the full interval set under the stated time semantics.
Record corrections honestly
Suppose a price effective January first is entered on January fifth. Effective time and recording time differ. If an audit must answer what the system knew on January third, an effective-date-only table is insufficient. Bitemporal designs distinguish those timelines, but they require additional schema and query rules beyond this lesson.
Do not overwrite historical rows casually when correcting mistakes. Decide whether a correction replaces an erroneous assertion, appends a revised version, or preserves an audit trail. The right policy depends on the application’s historical questions and retention obligations, not merely on which UPDATE is shortest.
Review representation limits
The controlled YYYY-MM-DD strings compare chronologically because they share one fixed representation. Mixed date formats would break that assumption. Intraday instants require explicit time-zone and precision decisions, covered later. A calendar-effective price date should not be converted into an arbitrary midnight instant without understanding the business zone.
Write tests before the first interval, at each start, immediately before each end, at the shared boundary, and after the last closed interval. Include gaps and overlaps deliberately. These cases expose errors that ordinary middle-of-period queries often hide.
Four worked exercises
Exercise 1
Query a day before the recorded history begins.
Worked solution
SELECT version_id,price_cents FROM price_history WHERE product_code='P1' AND valid_from<='2025-12-31' AND (valid_to IS NULL OR '2025-12-31'<valid_to) ORDER BY version_id;
No row applies. The model has no recorded price for that date. Returning zero cents or today’s price would invent an answer unless the domain explicitly defines such a fallback.
Exercise 2
Try adding an interval whose end equals its start.
Worked solution
BEGIN;
INSERT INTO price_history VALUES (3,'P2','2026-03-01','2026-03-01',700);
ROLLBACK;
The row is rejected because its half-open interval would be empty. The example’s policy requires positive interval length. This local endpoint rule is separate from overlap checks between different rows.
Exercise 3
Insert an overlapping interval in rehearsal and identify every overlapping pair.
Worked solution
BEGIN;
INSERT INTO price_history VALUES (3,'P1','2026-01-15','2026-02-15',550);
SELECT a.version_id,b.version_id FROM price_history AS a JOIN price_history AS b ON a.product_code=b.product_code AND a.version_id<b.version_id AND (b.valid_to IS NULL OR a.valid_from<b.valid_to) AND (a.valid_to IS NULL OR b.valid_from<a.valid_to) ORDER BY a.version_id,b.version_id;
ROLLBACK;
Version three overlaps both existing versions. The insertion succeeds because no cross-row overlap constraint was declared. The diagnostic proves a model gap; it should inform an enforcement design rather than justify accepting ambiguous as-of results.
Exercise 4
Check that the original adjacent intervals do not overlap.
Worked solution
SELECT a.version_id,b.version_id FROM price_history AS a JOIN price_history AS b ON a.product_code=b.product_code AND a.version_id<b.version_id AND (b.valid_to IS NULL OR a.valid_from<b.valid_to) AND (a.valid_to IS NULL OR b.valid_from<a.valid_to) ORDER BY a.version_id,b.version_id;
SELECT version_id,price_cents FROM price_history WHERE product_code='P1' AND valid_from<='2026-03-01' AND (valid_to IS NULL OR '2026-03-01'<valid_to) ORDER BY version_id;
The strict boundary comparisons treat the shared February first endpoint correctly. The open second interval also covers March first. NULL end means unbounded in this declared model, not an unknown arbitrary ending date.
Knowledge check
Question 1
Which version applies on February first?
- Both versions because BETWEEN is inclusive
- Version two at 600 cents
- Version one at 500 cents
- No version because boundaries are excluded
Answer and explanation
B. The start is included and the previous interval’s end is excluded.
Question 2
What does the row CHECK fail to prevent?
- An end before its own start
- An empty interval under this policy
- A negative price
- Overlaps with other history rows
Answer and explanation
D. Cross-row consistency requires more than a row-local expression.
Question 3
What is recording time?
- Always the same as its effective start
- When the system learned or recorded the assertion
- The exclusive end of every interval
- The scheduled expiration time of a business rule
Answer and explanation
B. Business-effective time and system knowledge time can differ.
Question 4
What should zero as-of matches mean initially?
- The price must be zero
- Use the newest row automatically
- No recorded applicable value under this model
- The query must have a syntax error
Answer and explanation
C. A fallback needs its own explicit domain rule.
Question 5
Why avoid inclusive BETWEEN here?
- It would match both adjacent versions at their shared boundary
- It cannot compare text in SQLite
- It always ignores NULL starts
- It compares only the start boundary and ignores the end
Answer and explanation
A. Half-open interval membership needs a strict comparison against the end.
Pitfalls and summary
Do not confuse current, effective, recorded, and agreed-at-event values. Declare interval boundaries and missing-end meaning, test coverage and overlaps, and preserve the history your users actually need. A version identifier distinguishes rows; it does not by itself make their temporal meaning coherent.
SQLite behavior and references
Examples were checked with SQLite 3.53.1 on 10 October 2026. Use a SQLite SQL editor; Python is not a prerequisite. Verify dialect-specific functions, comparison rules, and numeric behavior before moving the examples to another engine.
Primary references
- SQLite expressions: Comparison, NULL, and BETWEEN semantics
- SQLite date and time functions: Supported date representations and modifiers