38. The month that ends a day early

Debug the AIMediumBoundary trap

between · timestamps · date range · half-open interval · month end

Open in Colab
How the Colab notebook works

The notebook has the data, an answer cell and a check() function. You need a Google account; nothing is installed on your machine. Free Colab runs only two or three notebooks at a time, so end the session of a finished problem (Runtime > Disconnect and delete runtime) before opening the next one. "Mark as solved" is remembered in this browser only.

The situation

Finance closes the books every month from a daily payments table. An AI assistant wrote the query in the answer cell. It returns one row for each of the 31 days of March, and the days anyone spot-checked were right.

The month total is still short of the bank statement, and it has been short every month since the query went live.

Find the bug and fix it.

Input tables

payments

One row per payment. The table holds payments from mid February to mid April 2025.

Column Type Description
payment_id BIGINT Unique per payment.
paid_at TIMESTAMP_NTZ When the payment was made, to the microsecond.
amount DECIMAL(10,2) The amount paid. Never NULL.

Requirement

Return the daily totals for March 2025.

  • A payment belongs to March 2025 if paid_at is on or after 2025-03-01 00:00:00 and before 2025-04-01 00:00:00.
  • paid_date is the date part of paid_at.
  • payments is the number of payments on that date.
  • total is the sum of their amounts.
  • Payments outside March do not appear, not even as a row for another date.

Expected output

One row per date in March 2025 that has payments.

Column Type Description
paid_date DATE
payments BIGINT
total DECIMAL(14,2)

The AI-written code

-- Daily payment totals for March 2025
SELECT
    CAST(paid_at AS DATE) AS paid_date,
    COUNT(*) AS payments,
    CAST(SUM(amount) AS DECIMAL(14, 2)) AS total
FROM payments
WHERE paid_at BETWEEN '2025-03-01' AND '2025-03-31'
GROUP BY CAST(paid_at AS DATE)

Explanation

Show explanationGives the answer away. Try the problem first.

The bug

WHERE paid_at BETWEEN '2025-03-01' AND '2025-03-31'

paid_at is a timestamp. To compare it with the text '2025-03-31', Spark turns the text into a timestamp, and a date with no time is midnight at the start of that day: 2025-03-31 00:00:00. The plan shows the filter Spark actually runs:

paid_at >= 2025-03-01 00:00:00 AND paid_at <= 2025-03-31 00:00:00

So the range ends at the first moment of 31 March. Everything paid later that day is outside it.

Correct The buggy query
Rows 31 31
Payments 151 143
Total 367,776.80 352,490.52
31 March 9 payments, 17,928.24 1 payment, 2,641.96

Why it got through:

  • 30 of the 31 days are exactly right.
  • 31 March still has a row, because one payment was made at exactly 00:00:00, and BETWEEN includes its end points. The result has the right shape. Without that one payment the row would be missing, and someone might have counted to 30.
  • BETWEEN '2025-03-01' AND '2025-03-31' is correct when the column is a DATE. The query was probably written, or learned, against a date column.

The fix

A range of timestamps is half-open: it includes its start and excludes its end.

WHERE paid_at >= TIMESTAMP_NTZ '2025-03-01 00:00:00'
  AND paid_at <  TIMESTAMP_NTZ '2025-04-01 00:00:00'

"From the first moment of March up to, but not including, the first moment of April." No last-second arithmetic, no knowing how many days the month has, and consecutive months fit together with no gap and no overlap. Plain strings work too: paid_at >= '2025-03-01' AND paid_at < '2025-04-01'.

This is worth making a habit for every time range: >= start, < next start. BETWEEN on timestamps is almost never what you mean, because it includes both ends.

Common wrong answers

BETWEEN '2025-03-01' AND '2025-03-31 23:59:59'. The usual patch. paid_at has microseconds, and a payment at 23:59:59.500 is after 23:59:59. One payment is still missing, so 31 March shows 8 instead of 9.

... AND '2025-03-31 23:59:59.999'. Passes on this data. It still leaves the last 999 microseconds of the month uncovered, and now the query depends on the precision of the column. Chasing the last instant of a period is a losing game; name the first instant of the next one.

BETWEEN '2025-03-01' AND '2025-04-01'. Reaches the end of March, and one moment too far: BETWEEN includes the end, and there is a payment at exactly 2025-04-01 00:00:00. The result has a 32nd row, for 1 April.

paid_at > '2025-02-28'. Starting "after the last day of February" lets in almost all of 28 February, for the same reason as the original bug. 32 rows.

Other correct ways

Compare the date, not the timestamp.

WHERE CAST(paid_at AS DATE) BETWEEN '2025-03-01' AND '2025-03-31'

Now BETWEEN is comparing dates, where including both ends is right. In older engines a function wrapped around the column stops the filter from being used to skip files. Spark 4.1 rewrites it: the plan for this query shows paid_at >= 2025-03-01 00:00:00 AND paid_at < 2025-04-01 00:00:00, the same half-open range as the fix. Check the plan on the engine you use before relying on that.

YEAR(paid_at) = 2025 AND MONTH(paid_at) = 3. Correct. MONTH(paid_at) = 3 alone also passes here, because the table holds two months of one year. On a real table it returns every March there has ever been.

A PySpark detail

In the DataFrame API, do not build the boundaries from Python datetime objects without thinking about time zones. F.lit(datetime.datetime(2025, 3, 1)) is a timestamp in the driver's local time zone. On a laptop set to India time with a UTC session, that boundary is 2025-02-28 18:30:00, and the result gains a row for 28 February. F.lit("2025-03-01 00:00:00").cast("timestamp_ntz") means the same thing on every machine.

Edge cases in the data

Payment at Belongs to March? What it catches
2025-02-28 23:59:59 No A start that is too early.
2025-03-01 00:00:00 Yes A start with > instead of >=.
2025-03-31 00:00:00 Yes Keeps the 31 March row alive under the bug.
2025-03-31 23:59:59 Yes The original bug.
2025-03-31 23:59:59.500 Yes ... 23:59:59 as the end.
2025-04-01 00:00:00 No BETWEEN ... AND '2025-04-01'.