Full answer
sql
CREATE TABLE addresses (customer_id INTEGER, city TEXT, valid_from TEXT NOT NULL, valid_to TEXT);
CREATE UNIQUE INDEX one_current ON addresses(customer_id) WHERE valid_to IS NULL;
INSERT INTO addresses VALUES (1, 'Madrid', '2025-01-01', NULL);
BEGIN;
UPDATE addresses SET valid_to = '2026-03-01' WHERE customer_id = 1 AND valid_to IS NULL;
INSERT INTO addresses VALUES (1, 'Lisbon', '2026-03-01', NULL);
COMMIT;
SELECT city FROM addresses WHERE customer_id = 1 AND valid_from <= '2026-02-15' AND (valid_to IS NULL OR valid_to > '2026-02-15');| city |
|---|
| Madrid |
Changing an address closes the current row and inserts a new one, ideally in one transaction. The partial unique index rejects a second open row for the same customer.
"Where did this customer live on 15 February?" becomes a range query: valid_from <= d AND (valid_to IS NULL OR valid_to > d). Half-open ranges, where valid_to is exclusive, avoid double-counting on the switch day.
Alternatives include an audit log table filled by triggers (good for "who changed what", weaker for as-of queries) and PostgreSQL range types with an exclusion constraint that forbids overlapping periods (not run here).
sql
CREATE TABLE addresses (customer_id INTEGER, city TEXT, valid_from TEXT NOT NULL, valid_to TEXT);
CREATE UNIQUE INDEX one_current ON addresses(customer_id) WHERE valid_to IS NULL;
INSERT INTO addresses VALUES (1, 'Madrid', '2025-01-01', NULL);
BEGIN;
UPDATE addresses SET valid_to = '2026-03-01' WHERE customer_id = 1 AND valid_to IS NULL;
INSERT INTO addresses VALUES (1, 'Lisbon', '2026-03-01', NULL);
COMMIT;
SELECT city FROM addresses WHERE customer_id = 1 AND valid_from <= '2026-02-15' AND (valid_to IS NULL OR valid_to > '2026-02-15');Checked on SQLite 3.46.1, run twice with identical output.
Key points
- Store history rows with valid_from and valid_to
- Current row has valid_to IS NULL
- A partial unique index allows one current row
- Use half-open ranges for as-of queries
Common mistakes
- Overwriting the address and losing history
- Inclusive end dates that overlap on the change day
Follow-ups
- How would you prevent overlapping periods?
- How does an audit log differ from a history table?
Tips
- Mention the Type 2 SCD name