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.
Code
-- 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
PostgreSQL EXPLAIN AnalyzerAnalyze PostgreSQL EXPLAIN ANALYZE text or FORMAT JSON plans locally to flag Seq Scans, slow nodes, row misestimates, disk sorts, and index hints.SQL DDL to TypeScript ConverterConvert SQL CREATE TABLE DDL statements into strict TypeScript interfaces with nullable, array, enum, JSONB, and Date or ISO string column mappings.Multi-Mode Escape & Unescape CodecEscape and unescape strings safely across JSON, JavaScript, SQL single-quoted literals, POSIX shell single quotes, and RFC 4180 CSV cells in your browser.SemVer Range CheckerCheck whether a semantic version satisfies an npm-style range such as caret, tilde, comparison sets, wildcards, or hyphen ranges.
FAQ
- Which objects does the SQL touch?
- The references are `orders`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.