Correct SQL Logic for Selecting Today's Records in PostgreSQL
The article explains why using a closed interval ending at 23:59:59 fails to capture the full day, and demonstrates the proper open‑closed interval technique—greater‑or‑equal to the day's start and less than the next day's start—using PostgreSQL examples.
In the original query
SELECT count(1) FROM odr WHERE odr.create_time >= '2012-09-03 00:00:00' AND odr.create_time <= '2012-09-03 23:59:59';the author noticed that the upper bound 23:59:59 excludes the last second of the day, which can lead to inaccurate daily statistics.
The discussion points out that "today" should be defined mathematically as the interval from the start of the day (inclusive) to the start of the next day (exclusive). Using a closed interval that ends at 23:59:59 omits any events occurring in the final second, which may cause subtle bugs in accounting or reporting.
To fix the logic, the query should be rewritten as
odr.create_time >= '2012-09-03 00:00:00' AND odr.create_time < '2012-09-04 00:00:00', employing an open‑closed interval that correctly captures all rows belonging to the target date.
For PostgreSQL, two equivalent ways are shown:
Timestamp‑string form:
create_time >= '2012-12-04 00:00:00' AND create_time < '2012-12-05 00:00:00'Symbolic form using date functions:
create_time >= current_date AND create_time < current_date + 1The article concludes with a brief author bio, noting the writer's extensive experience in search technology, distributed systems, and database research, and that the content originates from an internal Qunar wiki.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Qunar Tech Salon
Qunar Tech Salon is a learning and exchange platform for Qunar engineers and industry peers. We share cutting-edge technology trends and topics, providing a free platform for mid-to-senior technical professionals to exchange and learn.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
