Today I learned: Using BETWEEN with SQL dates

August 10, 2018

Key takeaway: When you filter a timestamp column by day, compare against the start of the next day with < instead of using BETWEEN.

In PostgreSQL, BETWEEN '2018-08-01' AND '2018-08-07' includes all of August 7 for a date column and misses nearly all of it for a timestamp column.

BETWEEN is inclusive on both ends. For a date column, this query returns everything from August 1 through August 7, like you’d expect:

SELECT * FROM articles
WHERE created_at BETWEEN '2018-08-01'::DATE AND '2018-08-07'::DATE

Run the same query against a timestamp column and the comments from August 7 are missing:

SELECT * FROM comments
WHERE created_at BETWEEN '2018-08-01'::TIMESTAMP AND '2018-08-07'::TIMESTAMP

A colleague put it this way: “Your target column will be inclusive of that type.” The upper bound '2018-08-07' is read as 2018-08-07 00:00:00. As a date, every row from that day equals it. As a timestamp, a comment created at 2018-08-07 04:13:47 is after midnight, so it falls outside the range.

|           |          2018-08-07 | 2018-08-07 04:13:47 | <= 2018-08-07::DATE | <= 2018-08-07::TIMESTAMP |
|-----------|---------------------|---------------------|---------------------|--------------------------|
| date      |          2018-08-07 | 2018-08-07          | true                | true                     |
| timestamp | 2018-08-07 00:00:00 | 2018-08-07 04:13:47 | true                | false                    |