Half Open Timestamp Range Filtering

Filter month and day windows with >= start AND < end because BETWEEN reads the upper bound as midnight and drops the remainder of that day.

SqlData Fetching

Code

snippet
-- BETWEEN 的上限会被解释成当天 00:00:00:
-- 按自然月写 BETWEEN '2026-05-01' AND '2026-05-31',
-- 5 月 31 日白天(零点之后)的订单全部漏掉
SELECT COUNT(*) AS between_month_rows
FROM orders
WHERE created_at BETWEEN TIMESTAMP '2026-05-01 00:00:00'
                     AND TIMESTAMP '2026-05-31 00:00:00';

-- 半开区间 [start, end) 精确覆盖整个自然月,两端写法一致
SELECT COUNT(*) AS half_open_month_rows
FROM orders
WHERE created_at >= TIMESTAMP '2026-05-01 00:00:00'
  AND created_at <  TIMESTAMP '2026-06-01 00:00:00';

-- 按天取数同样适用:[当天, 次日)
SELECT COUNT(*) AS may_14_rows
FROM orders
WHERE created_at >= TIMESTAMP '2026-05-14 00:00:00'
  AND created_at <  TIMESTAMP '2026-05-15 00:00:00';

-- 对 created_at 上的 btree 索引,这是连续范围条件,两端都能命中索引
CREATE INDEX orders_created_at_idx ON orders (created_at);

How the snippet works

The file runs SELECT / CREATE statements, touching orders.

Breaking the statements into their working parts: a WHERE clause narrowing which rows one statement affects; COUNT aggregation.

Applying it

The orders table is the working surface here.

Statements that matter

SELECT COUNT(*) AS half_open_month_rows
FROM orders
WHERE created_at >= TIMESTAMP '2026-05-01 00:00:00'
AND created_at <  TIMESTAMP '2026-06-01 00:00:00';
SELECT COUNT(*) AS may_14_rows
FROM orders
WHERE created_at >= TIMESTAMP '2026-05-14 00:00:00'
AND created_at <  TIMESTAMP '2026-05-15 00:00:00';
SELECT COUNT(*) AS between_month_rows
FROM orders
WHERE created_at BETWEEN TIMESTAMP '2026-05-01 00:00:00'
AND TIMESTAMP '2026-05-31 00:00:00';

Interactive Tools for This Topic

FAQ

Which objects does the SQL touch?
The references are `orders`.