Ravindra BagaleCourses & study guides Track your progress

9. Date and Time Queries for Analysts

9.1 How to Filter a Date Range the Safe Way (>= Start AND < Next)

Why. Monthly reports are wrong if the last day of the month is missing. This happens often with date-time text.

What. posted_at holds a date and a time. SQLite compares these values as text. The text '2026-09-30 15:30:00' is longer than '2026-09-30' and starts the same way, so it sorts after it. That is why BETWEEN '2026-09-01' AND '2026-09-30' leaves out every row on 30 September that has a time, even 00:00:00. The safe pattern is >= the first day AND < the first day of the next month. It works here because every posted_at value uses the same format, YYYY-MM-DD HH:MM:SS, on the same clock. If a table mixes formats or time zones, clean them into one format first.

How. Count September rows with BETWEEN and with the safe pattern, and compare the two counts.

Steps

  1. Run the first example, which uses BETWEEN.
  2. Run the second example, which uses >= and <.
  3. Compare the counts: the safe version finds one more row.
  4. Run the third example to see the row that BETWEEN missed.

Examples

Example 1 · dataset: northstar_bank

SELECT COUNT(*) AS rows_found
FROM transactions
WHERE posted_at BETWEEN '2026-09-01' AND '2026-09-30';

Output

rows_found
8

Meaning. BETWEEN finds 8 rows, but September really has 9.

Example 2 · dataset: northstar_bank

SELECT COUNT(*) AS rows_found
FROM transactions
WHERE posted_at >= '2026-09-01'
  AND posted_at <  '2026-10-01';

Output

rows_found
9

Meaning. The safe pattern finds all 9 September rows, including the last day.

Example 3 · dataset: northstar_bank

SELECT txn_id, posted_at, amount
FROM transactions
WHERE posted_at >= '2026-09-30'
  AND posted_at <  '2026-10-01';

Output

txn_idposted_atamount
252026-09-30 15:30:00700.0

Meaning. This is the 30 September withdrawal at 15:30 that BETWEEN left out.

Ravindra Bagale's Tip

Say it as a rule: from the start date, up to but not including the next start date. It works for days, months and years when all dates share one format.