Date Arithmetic: Advanced
Generating Date Spines and Filling Gaps
Spot date arithmetic needs: "last 30 days," "same day last year," "business days only," "fiscal quarter."
The interviewer at this depth rarely asks 'compute monthly revenue.' They ask 'design the platform that produces monthly revenue, where transactions can arrive out of order from three upstream systems, the company restructured its fiscal calendar mid-year, the regulator requires us to be able to reproduce any historical report exactly as it was originally produced, and the dashboard refreshes every fifteen minutes.' Each clause in that question hides a date-arithmetic decision that the platform team owns. Bitemporal models for the regulatory reproduction. Watermark policies for the out-of-order events. Versioned calendars for the fiscal restructure. Incremental refresh patterns for the fifteen-minute cadence.
The four platform-level date concerns
- business time vs system time. Required for audit reproducibility and regulated reporting.
- event-time vs processing-time watermarks; lateness tolerance is the contract with downstream.
- SCD-2 on dim_calendar so fiscal restructures preserve historical reproducibility.
- policy choice: republish, arrival-period, corrections, drop. Each fits a different workload.
- ▸"reproduce the report as it was on date X"
- ▸"the upstream sends events out of order; how do we handle it"
- ▸"the fiscal calendar changed mid-year; the old reports should still be correct"
- ▸"late arrivers in this hourly aggregate; what's the policy?"
- ▸"event time versus processing time; pick one and defend it"
- ▸"how do we audit a dashboard reading from last quarter"
The seam between event time and processing time
- Reporting numbers must match the business reality (transactions per calendar day they actually happened)
- Late arrivers need to update historical totals
- The consumer is finance, reconciling against external records
- Reports are restated as late data arrives
- Reporting numbers must be stable once published
- The consumer is operations, tracking system throughput
- Historical totals never change; the published number is the published number
- Audit and reconciliation must be reproducible to a point-in-time
Why these matter at platform scale
Calendar Tables and Holiday-Aware Math
Write date manipulation using the three core functions and handle dialect differences (DATEADD vs INTERVAL).
Bitemporal data modeling is the technique for reporting tables that must be reproducible. Every row carries two times: business_time (when the event happened in the business) and system_time (when the row was inserted into the warehouse). The model lets the platform answer two distinct questions: what is true about the business as of business time T (the as-of-business-time query), and what did the platform believe was true as of system time S (the as-of-system-time query).
The bitemporal table
The two reproducibility queries
- ▸As-of-business-time: 'what was true on date X' (uses is_current = TRUE)
- ▸As-of-system-time: 'what did the system believe on date X' (uses system_time bounds)
- ▸Both queries answer different questions on the same data
- ▸Audit reproduction uses the second; standard reporting uses the first
The audit use case
Maintaining the bitemporal table
Cost of bitemporal modeling
Timezone-Correct Cohorting at Scale
Pull date parts with EXTRACT, handle fiscal year offsets, and explain ISO week numbering.
Event-time vs processing-time watermarks
The lateness threshold
Handling late data
- high-volume telemetry; per-event accuracy less important than dashboard freshness.
- financial transactions; every event must be counted; historical totals restate.
- audit-requiring tables; main pipeline publishes stable, corrections reconcile daily.
- Per-event accuracy is less important than dashboard freshness
- The volume of late events is low (telemetry, click streams)
- Recomputing the aggregate is more expensive than the lost signal
- The consumer is operations or product, not finance
- Per-event accuracy is critical (financial transactions, regulated reporting)
- The volume of late events is high enough to affect totals materially
- The downstream consumer requires reconcilable totals
- The platform can afford the operational cost of republishing aggregates
Streaming engines and watermarks
Out-of-order events are not bugs in the source; they are a property of distributed systems. Multiple producers, network delays, retries, and clock skew all produce events that arrive after later-event-time events. The platform's policy is the contract with the consumer; making the policy explicit is the move.
Partition Pruning on Date Columns
Convert between UTC and local time, explain why comparing timestamps across zones requires explicit conversion.
The SCD-2 calendar table
How the fiscal restructure is recorded
- ▸New rows inserted with new effective_from
- ▸Old rows superseded by setting effective_to
- ▸Historical queries with report_date find old mapping
- ▸Current queries find new mapping
- ▸Same table serves both; the version filter selects
The composite key trick
Joining to the versioned calendar
The audit reproducibility property
- Simplest to maintain; one row per date
- Historical queries use the current fiscal mapping for old dates
- Reports run today against old dates produce different numbers than reports run last year
- No audit trail of fiscal changes; restructures are lost
- Multiple rows per date over time; effective ranges via from/to columns
- Historical queries use the fiscal mapping that was effective at the report date
- Reports run today against old dates produce the same numbers as the original reports
- Full audit trail of fiscal changes; restructures are preserved
Calendar versioning is rare in startups and common in enterprises. The platform team's decision to add versioning is a forward bet that fiscal changes will happen and audit reproducibility will matter. The bet pays off the first time the company restructures or the first time a regulator asks for a reproduction. State the trade-off when designing: 'versioning adds complexity in exchange for future-proofing against fiscal changes and audit requirements; the right call depends on company stage and regulatory exposure.'
Storing UTC vs Local: The Design Call
Create a date spine using recursive CTE or GENERATE_SERIES and LEFT JOIN to fill calendar gaps in sparse data.
Four policies for out-of-order events
- Historical totals are restated when late data arrives
- Right for financial reporting and reconciliation against external sources
- Consumers must handle restatement
- Downside: published numbers are not stable; cached dashboards drift
- Historical totals are immutable once published
- Right for operational metrics and SRE dashboards
- Consumers see stable historical numbers
- Downside: arrival-period totals include events that did not happen then; harder to reconcile
Implementing policy 1 with bitemporal data
Implementing policy 2 with append-only facts
The reconciliation pipeline (policy 3)
Closing call-back: the question from s0
> You are in a data engineering interview at a regulated fintech. The interviewer asks: 'Design the platform that produces monthly revenue, where transactions arrive out of order from three upstream sources, the fiscal calendar restructured in Q3, the regulator requires historical reproducibility, and the dashboard refreshes every fifteen minutes.'
superseded_at and clearing is_current. That is what lets you answer a regulator asking for the January report exactly as published on February 5, at a storage cost of roughly 1 plus the correction rate.effective_from and effective_to columns and pass a report_date into every join, because a fiscal restructure updated in place destroys historical reproducibility.Every data engineering question involves dates; most candidates fumble timezone math
- Category
- SQL
- Difficulty
- advanced
- Duration
- 25 minutes
- Challenges
- 0 hands-on challenges
Topics covered: Generating Date Spines and Filling Gaps, Calendar Tables and Holiday-Aware Math, Timezone-Correct Cohorting at Scale, Partition Pruning on Date Columns, Storing UTC vs Local: The Design Call
Lesson Sections
- Generating Date Spines and Filling Gaps (concepts: sqlDateVsTimestamp)
The four platform-level date concerns Four concerns recur across every platform-team conversation about dates. First: bitemporal modeling. Every row in a reporting table has two times: when the event happened in the business (business time) and when the system observed it (system time). Reports that confuse the two produce restated numbers without anyone noticing. Second: watermarking. Date-aware incremental pipelines decide how to handle data that arrives after the watermark; the choice between
- Calendar Tables and Holiday-Aware Math (concepts: sqlTimestampType)
The bitemporal table The two reproducibility queries Two query shapes operate on a bitemporal table. The as-of-business-time query asks: 'what was the transaction's correct value at business time T?' This is the standard reporting query, with corrections applied. The as-of-system-time query asks: 'what did the system believe was the transaction's value as of system time S?' This is the reproducibility query, used for audit and regulatory reporting. The two queries can produce different numbers f
- Timezone-Correct Cohorting at Scale (concepts: sqlExtract)
Date-aware incremental pipelines need a watermark: the boundary that separates 'data we have already processed' from 'data still to process.' The watermark is conceptually simple but operationally hard because the choice between event time and processing time watermarks determines how the platform handles late-arriving data. The platform decision is which time axis the watermark advances on, and how late the platform tolerates data being before it is dropped. Event-time vs processing-time waterm
- Partition Pruning on Date Columns (concepts: sqlComplexPatterns)
Fiscal calendars are not static. Companies restructure their fiscal years (Apple moved its fiscal year-end from June to September in the 1980s and again later; many retailers shift to 4-4-5 calendars as they grow). When the calendar changes, the historical reports under the old calendar are still valid for the period they cover; the new calendar applies only going forward. The naive approach (update the calendar table in place) breaks historical reproducibility. The right approach is a versioned
- Storing UTC vs Local: The Design Call (concepts: sqlRecursiveCte)
The most operationally difficult class of date-arithmetic problems in production: out-of-order events. A transaction with event_time = January 31 arrives in the warehouse on February 3; the January report has already published; the February pipeline is running. Where does the January 31 transaction land? Whose totals get restated? How does the platform handle the discrepancy? These are the failure modes the interviewer is reading the question for. Four policies for out-of-order events Policy one