Knowledge base / SQL

DATE_TRUNC in SQL: period starts, grouping and time zones

I show how to build a period key and why the type, time zone and database engine belong in the report definition.

Kajo RudzińskiPublished Updated 6 min read

Event cubes on a timeline assigned to the beginnings of separate reporting periods.

DATE_TRUNC assigns a date and time to the beginning of a chosen period. For monthly event summaries, I need a common key for all moments in the same month. A month number alone is insufficient: June in two different years should not accidentally enter one row of a continuous report.

This entry primarily uses PostgreSQL 18. I show typed literals, a small aggregation and time-zone considerations, then compare SQL Server, BigQuery and Oracle syntax. A shared function name does not make the entire query portable.

The period start rather than the nearest boundary

In PostgreSQL, I begin with an explicit input type:

SELECT DATE_TRUNC('day', TIMESTAMP '2024-06-12 14:34:56');

The result value is 2024-06-12 00:00:00. An afternoon time does not move the result into the following day. The function truncates smaller components to the beginning of the selected unit. Other units for the same timestamp give:

Unit Period start
hour 2024-06-12 14:00:00
month 2024-06-01 00:00:00
quarter 2024-04-01 00:00:00
year 2024-01-01 00:00:00

The PostgreSQL documentation describes forms for timestamp, timestamp with time zone and interval. I avoid leaving the second argument as an untyped string. TIMESTAMP identifies the intended type and helps prevent ambiguity when selecting the appropriate function overload.

A small monthly aggregation

Assume a synthetic orders table with ordered_at of type timestamp without time zone and numeric amount. These events belong to one agreed local calendar. This example does not convert them between zones.

ordered_at amount
2024-06-02 09:00:00 10
2024-06-30 18:00:00 20
2024-07-01 08:00:00 5
SELECT
    DATE_TRUNC('month', ordered_at) AS month_start,
    SUM(amount) AS total_amount
FROM orders
GROUP BY DATE_TRUNC('month', ordered_at)
ORDER BY month_start;

The first two records share key 2024-06-01 00:00:00, with a June total of 30. The third belongs to July, with key 2024-07-01 00:00:00 and total 5. The year remains part of the key, so June of another year would create a separate group. ORDER BY establishes result order; grouping alone does not promise it.

The function does not insert empty months. If August contains no records, this query does not automatically display August with zero. That requires a separate calendar and a decision about whether missing data really means zero. Missing ordered_at also needs a rule. In ordinary PostgreSQL grouping, those records can form a group with a NULL key rather than being silently assigned to a calendar period.

DATE_TRUNC and EXTRACT answer different questions

EXTRACT(MONTH FROM ordered_at) gives a month number. That can help when intentionally comparing seasonality across years. DATE_TRUNC('month', ordered_at) gives the beginning of a particular month including its year. For a continuous timeline, I would use the second key to avoid merging several Junes. Both operations can be valid, but they represent different questions.

Formatting a date as text is also separate from identifying its period. Prepare a display label after aggregation if the recipient needs one. Do not turn a key into text simply because its chart label should be shorter. The CAST entry explains type conversion and why presentation should not be confused with a value’s underlying type.

The reporting day includes a time zone

For timestamp with time zone, the beginning of a day depends on the zone. PostgreSQL uses the session’s TimeZone by default, but accepts an explicit third argument. For an occurred_at column of that type and a Polish reporting calendar, I can write:

SELECT
    DATE_TRUNC('day', occurred_at, 'Europe/Warsaw') AS day_start,
    COUNT(*) AS event_count
FROM events
GROUP BY DATE_TRUNC('day', occurred_at, 'Europe/Warsaw')
ORDER BY day_start;

The key still has type timestamp with time zone. Its displayed representation can depend on the session zone even though the boundary was calculated for Warsaw. Distinguish the zone used to determine the period from the presentation of the resulting instant. I would not silently change the session setting between two parts of the same report and expect the labels to explain themselves.

The third zone argument is not allowed for timestamp without time zone. First establish what those source values mean, then decide whether conversion is appropriate. I do not attach a guessed zone to data of unknown origin. Events close to midnight and clock changes deserve particular attention when agreeing reporting boundaries and reconciling outputs produced by different teams.

Two offset calendars, clocks and an event cube close to a day boundary

Weeks and range filters

In PostgreSQL, week starts on Monday. Do not extend that rule to every tool. A week can cross a month or year boundary, so its key need not fall in the same month as all its events. Establish how the report handles such periods before comparing it with another team’s weekly summary. A matching label does not by itself establish matching calendar definitions.

To select a month from a timestamp without time zone column, I can use an explicit range:

WHERE ordered_at >= TIMESTAMP '2024-06-01 00:00:00'
  AND ordered_at < TIMESTAMP '2024-07-01 00:00:00'

The lower boundary is inclusive and the upper boundary exclusive. This avoids guessing the final representable fraction of a second in June. For timestamptz, boundaries must correspond to the agreed reporting zone. Actual filter performance depends on the execution plan and indexes; I would not promise it from the visual appearance of the query alone.

Equivalents require their own syntax

Engine and example type Month-start expression
PostgreSQL 18, timestamp DATE_TRUNC('month', TIMESTAMP '2024-06-12 14:34:56')
SQL Server 2022+, date/time DATETRUNC(month, CAST('2024-06-12T14:34:56' AS datetime2))
BigQuery GoogleSQL, DATE DATE_TRUNC(DATE '2024-06-12', MONTH)
Oracle, DATE TRUNC(DATE '2024-06-12', 'MM')

SQL Server introduced DATETRUNC in 2022. The name has no underscore and the unit is not a quoted string. For weeks, it distinguishes week, affected by DATEFIRST, from Monday-based iso_week. I would not recommend FORMAT as an automatic substitute for date truncation.

The displayed BigQuery form takes the date first and unit second. Its default WEEK begins on Sunday; WEEK(MONDAY) can request Monday. Oracle TRUNC uses its own format models such as 'MM'. These examples illustrate differences rather than provide a complete catalogue of every database’s date functions.

An exercise at the boundary

Choose two synthetic events: one immediately before a month begins and one exactly at its beginning. Record the column type, zone and expected period key. Add the same month from another year and a month with no events. Explaining these cases gives you a useful basis for aggregation. A shorter date label on screen cannot replace a definition of the period that the report is supposed to describe.

Key takeaways

Does DATE_TRUNC round to the nearest day?

In PostgreSQL, it truncates to the beginning of the selected period. An afternoon event still receives the beginning of that same day.

Why use a typed TIMESTAMP literal?

An explicit type identifies the intended function form and helps avoid ambiguous overload resolution when the argument would otherwise be an untyped string.

Does SQL Server support this operation?

SQL Server 2022 introduced DATETRUNC, without an underscore and with its own syntax. Do not copy PostgreSQL expressions unchanged.

AI was used in an automated way while working on this article. If you want to learn how to do it too, check out this project.

Kajo Rudziński

Newsletter KajoData

Let’s keep in touch.

I write about data analysis, learning and changing careers. My newsletter and the sign-up form are in Polish. If that works for you, I’d be glad to see you there.