TechBuzzPro

Postgres Between Times: Date/Time Filtering

· 6 min read · Apps & Browsers

In this article
  1. How BETWEEN Works with Dates and Timestamps
  2. Why the Last Day Disappears
  3. Correct Patterns for Full-Day Ranges
  4. Using BETWEEN with timestamptz and Time Zones
  5. Common Mistakes and How to Avoid Them
  6. Alternatives to BETWEEN for Date Ranges
  7. Performance Considerations
  8. Frequently Asked Questions

The PostgreSQL BETWEEN operator is a concise way to filter rows where a column’s value falls within a specified range, and when used with timestamp or date columns it includes both endpoints. However, the common mistake of using BETWEEN with a date-only lower bound and a date-only upper bound against a timestamp column silently excludes the final day’s data. This article explains exactly how BETWEEN behaves with dates and timestamps, why the last day often goes missing, and the correct patterns to capture full days, months, or custom ranges.

How BETWEEN Works with Dates and Timestamps

In PostgreSQL, BETWEEN is shorthand for >= and <=. For a timestamp column, the comparison is done at microsecond precision. If you write:

SELECT * FROM events WHERE created_at BETWEEN '2024-01-01' AND '2024-01-31';

PostgreSQL implicitly casts the string literals to timestamp with a time of 00:00:00. So the query becomes:

WHERE created_at >= '2024-01-01 00:00:00' AND created_at <= '2024-01-31 00:00:00';

Any event that occurred after midnight on January 31st — say at 09:15 — is excluded. This is the classic “off-by-one-day” bug. The same issue appears with date columns only if you mix types, but for pure date columns BETWEEN works as expected because the entire day is a single value.

Why the Last Day Disappears

The root cause is that a timestamp includes a time component, and BETWEEN treats the upper bound as exactly midnight. If you store created_at as timestamptz (timestamp with time zone), the same problem occurs, but time zone conversions can make it even more confusing. For example, a user in UTC+2 sees “January 31” as a local date, but the stored UTC timestamp for 23:00 local is 21:00 UTC — still before midnight UTC, so it might appear in the range, while 01:00 local on February 1st is 23:00 UTC January 31st, which would be included when you didn’t intend it.

The fix is to use a half-open interval: >= the start and < the day after the end. This is the standard SQL pattern and avoids boundary ambiguity entirely.

Correct Patterns for Full-Day Ranges

To include all of January 2024, use one of these equivalent methods:

  • WHERE created_at >= '2024-01-01' AND created_at < '2024-02-01'
  • WHERE created_at::date BETWEEN '2024-01-01' AND '2024-01-31' — casting the timestamp to a date, but this prevents index usage on the timestamp column unless you create an expression index.
  • WHERE created_at >= '2024-01-01' AND created_at < '2024-01-01'::date + interval '1 month' — useful for variable month lengths.

For a single day, the pattern is created_at >= '2024-01-15' AND created_at < '2024-01-16'. This is the most reliable and index-friendly approach.

Using BETWEEN with timestamptz and Time Zones

When your column is timestamptz, PostgreSQL stores the value in UTC internally. The comparison with a string literal uses the session’s time zone setting. If you run a query from a client in New York (UTC-5) and write BETWEEN '2024-01-01' AND '2024-01-31', the bounds are interpreted as New York midnight, then converted to UTC for comparison. That means the actual range is 2024-01-01 05:00 UTC to 2024-01-31 05:00 UTC. If your data was inserted from a different time zone, you may see unexpected inclusions or exclusions.

Best practice: always specify the time zone explicitly in the literal, e.g., '2024-01-31 23:59:59+00', or better, use the half-open interval with an explicit time zone: created_at >= '2024-01-01' AT TIME ZONE 'UTC' AND created_at < '2024-02-01' AT TIME ZONE 'UTC'. This makes the query deterministic regardless of session settings.

Common Mistakes and How to Avoid Them

  • Using BETWEEN with dates and timestamps interchangeably: Always check the column type. If it’s timestamp, add the time component or use the exclusive upper bound.
  • Assuming BETWEEN includes the entire upper day: It does not; it includes only up to midnight.
  • Using <= with a date literal on a timestamp column: Same problem as BETWEEN.
  • Forgetting that now() includes the current time: If you filter created_at BETWEEN '2024-01-01' AND now(), you get everything up to the exact second the query runs, which is usually fine but can surprise you if you expected midnight.
  • Ignoring index usage: Casting a column to date in the WHERE clause prevents a standard B-tree index from being used. Instead, use the half-open interval to keep the index effective.

Alternatives to BETWEEN for Date Ranges

PostgreSQL offers several other ways to filter date ranges:

  • Range types: tsrange or tstzrange with the @> operator. This is useful when you store ranges as a single value, but overkill for simple filtering.
  • EXTRACT: WHERE EXTRACT(YEAR FROM created_at) = 2024 — but this prevents index usage and is slower on large tables.
  • date_trunc: WHERE date_trunc('month', created_at) = '2024-01-01' — also prevents index usage unless you have an expression index.
  • Generate_series: Useful for filling gaps in reporting, not for filtering.

For most queries, the half-open interval with >= and < is the most performant and clear.

Performance Considerations

When you use BETWEEN with a timestamp column and a date literal, PostgreSQL can still use an index on that column, but the range is narrower than you think. That means you might get fewer rows than expected, but the query plan is fine. The real performance killer is casting the column: created_at::date forces a full scan unless you have an expression index. If you frequently filter by date, consider creating an index on (created_at::date) or better, store the date separately if you only care about the day.

Another subtle point: when using BETWEEN with timestamptz, the planner must convert the bounds to UTC, which is a constant expression and still index-friendly. However, if you write created_at AT TIME ZONE 'America/New_York' BETWEEN ..., that prevents index usage because the expression is not immutable.

Frequently Asked Questions

Does BETWEEN include the endpoints in PostgreSQL?

Yes, BETWEEN is inclusive of both lower and upper bounds. For a timestamp column, that means the upper bound is exactly midnight of that date if you only provide a date. So the last day’s data after midnight is excluded.

How do I select all rows from a specific day in PostgreSQL?

Use WHERE created_at >= '2024-01-15' AND created_at < '2024-01-16'. This includes everything from midnight on the 15th up to but not including midnight on the 16th.

What’s the difference between BETWEEN and using >= and <=?

Nothing functionally — BETWEEN is exactly equivalent to >= AND <=. The difference is readability. However, with timestamps, the “exclusive upper bound” pattern using < is not possible with BETWEEN because it’s always inclusive.

Why does my BETWEEN query miss the last day’s data?

Because the upper bound is midnight of that day. If you have any timestamps after 00:00:00 on the last day, they are excluded. Use < 'next day' instead.

Should I use BETWEEN or range types for date filtering?

For simple filtering, BETWEEN or the half-open interval is fine. Range types are better when you need to store a range as a value, check for overlaps, or perform set operations. For a single query, they add complexity without benefit.

How do I handle time zones with BETWEEN?

Always specify the time zone in the string literal, e.g., '2024-01-31 23:59:59+00', or use AT TIME ZONE to make the bounds explicit. Avoid relying on the session time zone, as it can change between connections.