← Back to SQL, page 22

sql-0430 · Medium mid

Daily sales totals are wrong for users in India because timestamps are stored in UTC. How do you group by the local day?

Convert each UTC timestamp to the business's time zone before taking the date, then group. In SQLite that means applying the offset (or 'localtime' on a server set to that zone); in PostgreSQL use (ts AT TIME ZONE 'UTC') AT TIME ZONE 'Asia/Kolkata' or a timestamptz with AT TIME ZONE. Grouping by the UTC date shifts orders placed between midnight and 05:30 IST into the previous day.

Full answer
sql
CREATE TABLE sales_utc (id INTEGER PRIMARY KEY, ts TEXT, amount INTEGER);
INSERT INTO sales_utc VALUES (1, '2026-03-01 04:00:00', 100), (2, '2026-03-01 20:00:00', 50), (3, '2026-03-02 10:00:00', 70);

Grouping by the UTC date:

sql
SELECT date(ts) AS utc_day, SUM(amount) AS total FROM sales_utc GROUP BY utc_day ORDER BY utc_day;
utc_daytotal
2026-03-01150
2026-03-0270

Grouping by the India date (UTC+05:30, which has no daylight saving):

sql
SELECT date(ts, '+5 hours', '+30 minutes') AS ist_day, SUM(amount) AS total FROM sales_utc GROUP BY ist_day ORDER BY ist_day;
ist_daytotal
2026-03-01100
2026-03-02120

The order at 20:00 UTC on 1 March is 01:30 on 2 March in India, so it moves to the next day, and the totals change for both days. A fixed offset is safe for India; for zones with daylight saving, a fixed offset is wrong for part of the year, so PostgreSQL's named zones (AT TIME ZONE 'Europe/London') or conversion in the application are needed. Store instants in UTC, and decide explicitly which zone defines a 'business day' for each report.

sql
CREATE TABLE sales_utc (id INTEGER PRIMARY KEY, ts TEXT, amount INTEGER);
INSERT INTO sales_utc VALUES (1, '2026-03-01 04:00:00', 100), (2, '2026-03-01 20:00:00', 50), (3, '2026-03-02 10:00:00', 70);

SELECT date(ts) AS utc_day, SUM(amount) AS total FROM sales_utc GROUP BY utc_day ORDER BY utc_day;

SELECT date(ts, '+5 hours', '+30 minutes') AS ist_day, SUM(amount) AS total FROM sales_utc GROUP BY ist_day ORDER BY ist_day;

Checked on SQLite 3.46.1, run twice with identical output.

Key points

  • Convert to the business zone before taking the date
  • UTC dates misplace late-evening or early-morning orders
  • Fixed offsets only work without daylight saving
  • Use named zones in PostgreSQL
  • Define the reporting zone explicitly

Common mistakes

  • Grouping by date(ts) on UTC values for local reports
  • Hard-coding offsets for zones with daylight saving

Follow-ups

  • How would you report for several countries at once?
  • Why store UTC at all?

Tips

  • Show an order that changes day