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
- Run the first example, which uses BETWEEN.
- Run the second example, which uses >= and <.
- Compare the counts: the safe version finds one more row.
- 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_id | posted_at | amount |
|---|---|---|
| 25 | 2026-09-30 15:30:00 | 700.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.
Ravindra Bagale's Tip – मराठी
हा नियम लक्षात ठेवा: सुरुवातीच्या date पासून, पुढच्या सुरुवातीच्या date च्या आधीपर्यंत. सगळ्या dates एकाच format मध्ये असतील तर हे दिवस, महिने आणि वर्षं सगळ्यांसाठी चालतं.
Ravindra Bagale's Tip – हिंदी
इसे नियम की तरह याद रखिए: शुरुआती date से, अगली शुरुआती date से पहले तक। सारी dates एक ही format में हों तो यह दिन, महीने और साल सबके लिए चलता है।