skip to content

A daily sales report for users in several time zones shows a short last day each month, and its buckets shift by an hour twice a year; how do you diagnose and fix it in SQL?

level: seniorimportance: should knowfreq 48%

answer

  1. two symptoms, probably two causes
  2. what instant is the upper bound
  3. half-open range, in which zone
  4. does the zone follow clock changes
  5. 23-hour and 25-hour days

basics

~20 s

A short last day and shifting buckets are usually two bugs. An inclusive or UTC upper bound cuts the day, so use a half-open range in the report's zone. Fixed offsets shift buckets, so use a named zone.

solid answer

~50 s

I'd treat these as two bugs and reproduce each on one boundary day before changing anything. For the short last day, I'd look for `BETWEEN` or `<=` with a date upper bound on a timestamp column, which stops at midnight, and for a `23:59:59` patch, which still loses fractional seconds. I'd also check whether the bounds are UTC midnights, since those end a New York month during its last evening. The fix is a half-open range with both bounds converted from the report's zone. For the hour shift, I'd look for a fixed offset or rollups cut at UTC midnight, because neither follows the clock change. The fix is to bucket with a named zone, `(created_at AT TIME ZONE 'America/New_York')::date` on PostgreSQL. Then I'd verify on the transition days, which should span 23 and 25 hours, and check that the daily totals add up to the raw month count.

code

sql · 9 lines
sql
SELECT d::date AS local_day,
       (d + INTERVAL '1 day') AT TIME ZONE 'America/New_York'
         - d AT TIME ZONE 'America/New_York' AS day_length
FROM (VALUES (TIMESTAMP '2024-03-09'),
             (TIMESTAMP '2024-03-10'),
             (TIMESTAMP '2024-11-03')) AS v(d);
-- 2024-03-09 | 1 day
-- 2024-03-10 | 23:00:00
-- 2024-11-03 | 1 day 01:00:00

go deeper

for a junior

Recall that a timestamp upper bound written as a date means midnight at the start of that day. Then write a half-open range with greater-or-equal and strictly-less-than from memory.

for a middle

Explain why a fixed offset fails across a clock change, and why the bounds and the bucket expression need the same named zone. Be able to work out a local midnight as a UTC instant.

for a senior

Reproduce each symptom on one boundary day, print the real bounds, and reconcile the buckets against a raw count. Finish with a regression test on transition days, since this bug returns whenever someone rewrites the query.

for a principal

Treat recurring bucket bugs as a sign the zone was never decided. Standardise one helper or view for a business day, so that report authors no longer write zone conversions and range bounds by hand.

## Separate the two symptoms The report has two symptoms on different schedules: one appears monthly and one appears twice a year. That points to two causes, so diagnose them one at a time rather than rewriting the query at once: 1. **Pin one failing bucket.** Take the last day of a short month and count raw rows between two explicit instants, written with their offsets. 2. **Read the query's real bounds.** Print each bound as an instant, because a date literal compared with a timestamp becomes midnight in some zone. 3. **Find what defines a day.** Look at the `GROUP BY` expression, the session's `TimeZone` and any rollup job, and ask which zone each one uses. 4. **Check the column.** Confirm whether it holds instants or plain readings, and in which zone, since that limits what any fix can do. ## Why the last day is short Three different bugs cause this, and the third is easy to miss because the range looks correct: - **An inclusive date bound on a timestamp.** `created_at BETWEEN DATE '2024-03-01' AND DATE '2024-03-31'` stops at midnight at the start of 31 March, so nearly the whole day is lost. - **The `23:59:59` patch.** `created_at <= '2024-03-31 23:59:59'` still drops a row stamped 23:59:59.5 when the column keeps fractional seconds. The patch also ties the query to one column precision. - **A correct-looking range in the wrong zone.** `created_at < '2024-04-01 00:00+00'` is half-open, but that instant is 20:00 on 31 March in New York, so the evening's sales fall out. At the other end, `'2024-03-01 00:00+00'` is 19:00 on 29 February in New York, so a small stray February bucket appears. The fix for all three is a **half-open range**: greater than or equal to the period's start, and strictly less than the next period's start, with both bounds computed in the report's zone. Adjacent periods then share one boundary value, so no row falls between them and none is counted twice, whatever precision the column has. For a pure `DATE` column an inclusive range is correct, since no time of day exists to lose. Oracle's `DATE` holds a time of day, so the timestamp rules apply there. ## Why buckets shift by an hour | Cause in the query | Why it shifts | Where to look | |---|---|---| | Fixed offset, such as `INTERVAL '-05:00'` | correct in one season, an hour off in the other | the bucket expression | | Rollups cut at UTC midnight | a UTC day starts at a different local hour after each change | the rollup job | | Buckets built by adding 24 hours | the grid slips when a local day has 23 or 25 hours | the date-grid query | | Hand-written seasonal correction | dates for clock changes vary by year and by country | a `CASE` on the month | If the session zone is left to chance, you get a different symptom: results that change with the connection rather than with the season. It is still worth fixing in the same pass by naming the zone in the query. ## The corrected query On PostgreSQL, with `created_at` as a `timestamp with time zone`: ```sql SELECT (created_at AT TIME ZONE 'America/New_York')::date AS sales_day, SUM(amount) AS revenue FROM sales WHERE created_at >= TIMESTAMP '2024-03-01 00:00' AT TIME ZONE 'America/New_York' AND created_at < TIMESTAMP '2024-04-01 00:00' AT TIME ZONE 'America/New_York' GROUP BY (created_at AT TIME ZONE 'America/New_York')::date ORDER BY sales_day; ``` The `WHERE` bounds turn local midnights into instants, and the `GROUP BY` turns each instant into a local date. Both must use the same zone, or the first and last buckets come out partial. PostgreSQL's `date_trunc('day', created_at, 'America/New_York')` gives the same grouping, as a `timestamptz` at each local midnight. ## Verify on the transition days Run the test on days that used to fail, not on an ordinary Tuesday. For New York in 2024: | Local day | Starts at (UTC) | Length | |---|---|---| | 9 March | 05:00 | 24 hours | | 10 March | 05:00 | 23 hours | | 3 November | 04:00 | 25 hours | - **Reconcile.** The daily totals must add up to a raw count over the month's half-open range. - **Expect uneven days.** A 23-hour day has less time to sell, so a dashboard comparing day to day should divide by the actual hours before anyone reads a dip as a real change. - **Keep a test.** A fixture with rows either side of a local midnight and a clock change stops the bug coming back. ## Users in several zones The report also has to say **whose day** it shows. One reporting zone gives one total per day. Bucketing by each customer's zone, `created_at AT TIME ZONE u.time_zone` with a joined column and a cast to `date` gives each customer's own date, so a late sale in Los Angeles lands on a different date from the same instant in Berlin. Neither is a bug, but the two sets of daily totals will not match, so label the zone on the report. ## When the column holds local readings If `created_at` is a plain `timestamp` written in New York time, the query can only approximate the truth. Each November the hour from 01:00 to 02:00 occurs twice, and those rows cannot be told apart afterwards. New writes should store instants; the old rows stay ambiguous for that hour, so say so rather than presenting them as exact.

  • Why do per-hour rates look wrong on the two transition days, and how do you correct them?
    A rate that divides by 24 uses the wrong denominator on a 23-hour or 25-hour local day, so one day reads high and the other low. Compute each day's length as the next local midnight minus this one, converted to instants, and divide by that.
  • What can you do when created_at is a plain timestamp holding New York local time?
    Convert it with `created_at AT TIME ZONE 'America/New_York'`, and accept that readings in the repeated November hour map to a single instant, so one hour's rows cannot be separated. Fix new writes to store instants and record which rows predate the change. Do not present the old hour as exact.
  • On PostgreSQL, does date_trunc with a third argument replace the date cast in this report?
    It can. `date_trunc('day', created_at, 'America/New_York')` truncates in that zone and returns a `timestamp with time zone` marking local midnight, so grouping matches the date cast. It prints in the session's zone, though, so the value can look like a non-midnight time unless you convert it for display.

  • Extending the upper bound to 23:59:59 fully fixes a timestamp range.
  • A day always has 24 hours, so adding 24 hours is a safe way to build day buckets.
  • Once the GROUP BY uses local time, the WHERE bounds can stay at UTC midnight.
  • A half-open range is correct in any zone, so its bounds need no conversion.
  • Adding one hour in the summer months is a sound fix for the shifting buckets.