smartyfy.mrindigi.com

Databases & SQL Master Course — 093. Dates Times and Storage Choices

Lesson 093 Dates Times and Storage Choices

Prerequisites and objectives

You can compare text and preserve representation deliberately. You will distinguish an instant from a calendar date, compare SQLite’s common time-storage choices, normalize explicit-offset timestamps for calculation, and explain why raw text order is unsafe when offsets or formats differ.

Create the practice fixture

Use a fresh SQLite database. Three source timestamps include explicit numeric offsets. A separate task has a calendar due date with no instant-of-day meaning. The examples use second precision and label normalized datetime output as UTC even though SQLite’s returned text does not append a timezone suffix automatically.

CREATE TABLE timestamp_inputs (event_id INTEGER PRIMARY KEY,source_text TEXT NOT NULL);
INSERT INTO timestamp_inputs VALUES
 (1,'2026-10-10 09:00:00-04:00'),
 (2,'2026-10-10 12:00:00+00:00'),
 (3,'2026-10-11 00:30:00+02:00');
CREATE TABLE calendar_tasks (task_id INTEGER PRIMARY KEY,due_day TEXT NOT NULL);
INSERT INTO calendar_tasks VALUES (1,'2026-10-11');

Choose the meaning before the type

An instant is a point on a timeline. A calendar date identifies a civil day, such as a delivery date or birthday, without necessarily selecting one universal instant. A local wall-clock appointment adds a time of day and may need a named time zone plus ambiguity rules. These are different domains despite often arriving as strings.

SQLite has no dedicated built-in date storage class. Applications commonly use consistently formatted text, integer Unix timestamps, or real Julian-day numbers. The choice should specify timezone interpretation, units, precision, valid range, and missing-value policy. Declaring a column DATE in an ordinary table does not automatically enforce all of those rules.

Compare representations of the same instant

SQLite’s date functions interpret the explicit offsets in this fixture and normalize the result to UTC. unixepoch returns seconds since the Unix epoch for these whole-second inputs. A numeric representation is convenient for elapsed-time arithmetic, while a canonical UTC text representation can be readable and sortable when its format is consistent.

SELECT event_id,datetime(source_text),unixepoch(source_text) FROM timestamp_inputs ORDER BY event_id;
Normalized instants; the numeric column is Unix seconds
Event UTC datetime Unix seconds
1 2026-10-10 13:00:00 1791637200
2 2026-10-10 12:00:00 1791633600
3 2026-10-10 22:30:00 1791671400

Event one’s local nine o’clock at minus four hours is thirteen o’clock UTC. Event three’s local date is October eleventh, but its UTC date is October tenth. A reporting day therefore depends on which calendar and timezone the question intends.

Event 1 at 09:00 minus four hours normalizes to 13:00 UTC; event 2 at 12:00 plus zero normalizes to 12:00 UTC. Raw text order reverses their actual chronology.
An instant and a calendar date need different storage contracts. Open full-size diagram

Do not sort mixed representations blindly

Event one’s raw text begins with nine o’clock and event two’s with twelve, so lexicographic order puts one before two. Their actual UTC instants have the opposite order. Text sorting matches chronology only under a disciplined canonical representation with compatible timezone and precision conventions.

Likewise, an integer timestamp is meaningless without units. Seconds, milliseconds, and microseconds differ by large factors. Use explicit unixepoch interpretation when converting a seconds value back to datetime. Avoid magnitude guessing when the schema already knows the representation.

Preserve source context when useful

A canonical instant may lose the original offset spelling or zone context. If an audit or user interface needs to reproduce that source representation, retain it separately with a clear role. Do not maintain two independently editable authoritative timestamps without a consistency policy.

A calendar-only due date should remain a calendar fact if that is the requirement. Assigning midnight UTC can shift its displayed day for users in other zones and invent a time that was never intended. A separate business rule can later define a cutoff instant in an appropriate named zone.

Plan precision and validation

Whole-second Unix integers cannot preserve subsecond distinctions. Floating-point Julian days have finite precision. Text can represent a chosen fractional precision, but readers and functions must agree on that contract. Select enough precision for the domain without claiming exactness beyond the representation or function behavior.

Date-function acceptance is not a complete validation policy for source data. Test malformed strings, out-of-range values, mixed formats, and timezone assumptions. The following lesson examines modifiers and boundary cases; the next separates numeric offsets from named-zone rules and daylight-saving behavior.

Four worked exercises

Exercise 1

Prove that two different offset spellings can identify the same instant.

Worked solution
SELECT unixepoch('2026-10-10 09:00:00-04:00')=unixepoch('2026-10-10 13:00:00Z');

The equality result is one. The wall-clock labels differ, but the explicit offsets resolve them to the same instant. Comparing source strings directly would not establish that equivalence.

Exercise 2

Compare raw-text order with normalized chronological order for events one and two.

Worked solution
SELECT event_id FROM timestamp_inputs WHERE event_id IN (1,2) ORDER BY source_text;
SELECT event_id FROM timestamp_inputs WHERE event_id IN (1,2) ORDER BY unixepoch(source_text),event_id;

The orders reverse. This is a concrete counterexample to sorting arbitrary offset-bearing text as though it were one canonical UTC representation.

Exercise 3

Convert a known Unix-seconds value back to a UTC datetime.

Worked solution
SELECT datetime(1791633600,'unixepoch');

The explicit modifier tells SQLite how to interpret the number. Omitting representation metadata or confusing milliseconds with seconds would change the result dramatically. A schema should make the unit clear in its documentation and naming.

Exercise 4

Contrast an instant’s UTC date with the separate task’s calendar due date.

Worked solution
SELECT date(source_text) FROM timestamp_inputs WHERE event_id=3;
SELECT due_day FROM calendar_tasks WHERE task_id=1;

The timestamp normalizes to October tenth UTC, while the task remains due on the eleventh as a calendar fact. They answer different questions; one should not be overwritten merely to make the displayed dates agree.

Knowledge check

Question 1

What must be decided before choosing a storage representation?

  1. Only the column’s display width
  2. Whether the value means an instant, date, or local schedule
  3. Only whether the table has an index
  4. Only the spelling accepted by the current parser
Answer and explanation

B. The domain meaning determines the required metadata and operations.

Question 2

Why does raw timestamp sorting fail in the example?

  1. Text can never represent dates
  2. ORDER BY sorts offsets numerically before comparing local labels
  3. The strings use different offsets
  4. Epoch values preserve the original local-clock ordering
Answer and explanation

C. Mixed offset spellings can order differently from the instants they represent.

Question 3

What unit does the demonstrated unixepoch output use?

  1. Seconds
  2. Milliseconds by default in these calls
  3. Calendar months
  4. Julian days
Answer and explanation

A. The examples use whole-second Unix values with explicit interpretation.

Question 4

Why avoid turning every due date into midnight UTC?

  1. Every local midnight is necessarily the same instant as UTC midnight
  2. It invents an instant and can shift the displayed civil date
  3. A calendar date must be converted to epoch seconds to compare it
  4. The parser refuses date-only strings
Answer and explanation

B. A calendar requirement should not acquire unintended timezone semantics.

Question 5

What can canonical UTC storage fail to preserve by itself?

  1. The normalized instant at its chosen precision
  2. A sortable consistent representation
  3. A basis for elapsed-time comparison
  4. The original source offset or named-zone context
Answer and explanation

D. Source presentation and scheduling context may require separate fields.

Pitfalls and summary

Do not mix date-only facts, local schedules, and instants under one undocumented timestamp label. Declare representation, timezone, units, and precision; normalize before comparing mixed inputs. Preserve source context when needed, and avoid pretending that a declared type alone validates the whole temporal contract.

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