SQL Dojo
Pitfall

BETWEEN on timestamps loses the last day

On a timestamp, BETWEEN '2025-06-01' AND '2025-06-30' stops at midnight on the 30th and loses the last day; a half-open range keeps it.

It happens as soon as you filter a period on a column that holds a time, not only a date: a month of orders, last week's events. BETWEEN '2025-06-01' AND '2025-06-30' stops at 00:00 on the 30th, and the whole last day disappears without an error.

SELECT COUNT(*) AS orders
FROM orders
WHERE ordered_at >= '2025-06-01'
  AND ordered_at <  '2025-07-01';

The lower bound is included; the upper bound is the first moment you do not want. The range is right for dates and timestamps, whatever the length of the month, and two consecutive periods never overlap.

The trap. Patching the bound with '2025-06-30 23:59:59' still loses 23:59:59.5, and the symptom stays: a month that adds up to less than its days. CAST(ordered_at AS DATE) BETWEEN … is right, but a function on the column can keep the engine from skipping partitions or using an index: compare the bare column with >= start AND < next start.

On your warehouse. BigQuery will not compare a TIMESTAMP with a DATE: write the bounds as strings, or convert them, ordered_at < TIMESTAMP(CURRENT_DATE()). And a period built on CURRENT_DATE ("since yesterday") depends on which day it is: UTC on BigQuery and Databricks, the session's time zone on Snowflake and Postgres.

The trap

SELECT COUNT(*) AS orders
FROM orders
WHERE ordered_at BETWEEN '2025-06-01' AND '2025-06-30';
orders
97
Try it in Randori

The fix

SELECT COUNT(*) AS orders
FROM orders
WHERE ordered_at >= '2025-06-01' AND ordered_at < '2025-07-01';
orders
101
Try it in Randori