PostgreSQL – DATE_TRUNC Function
In PostgreSQL, the DATE_TRUNC
function is used to truncate a date, time, or timestamp value to a specified precision. Truncation means setting specific parts of the date or time to zero or a default value while keeping the more significant parts unchanged.
The basic syntax of the DATE_TRUNC
function is as shown below:
DATE_TRUNC(precision, source);
where precision
is the precision to which you want to truncate the date or time (e.g., ‘year’, ‘quarter’, ‘month’, ‘day’, ‘hour’, ‘minute’, ‘second’, etc.). The precision parameter is case-insensitive.
and source
is the date, time, or timestamp that you want to truncate.
Here are some examples of using the DATE_TRUNC
function:
- Truncating a timestamp to the beginning of the month:
SELECT DATE_TRUNC('month', TIMESTAMP '2023-08-06 15:30:45') AS truncated_timestamp;
This query will return 2023-08-01 00:00:00
, effectively setting the day and time components to the beginning of the month.
- Truncating a date to the beginning of the year:
SELECT DATE_TRUNC('year', '2023-08-06') AS truncated_date;
This query will return 2023-01-01
, setting the month and day components to the beginning of the year.
- Truncating a timestamp to the beginning of the hour:
SELECT DATE_TRUNC('hour', TIMESTAMP '2023-08-06 15:30:45') AS truncated_timestamp;
This query will return 2023-08-06 15:00:00
, setting the minutes and seconds components to zero.
The DATE_TRUNC
function is useful when you need to aggregate or group data by specific time periods (e.g., months, years) or perform calculations based on a particular time resolution. It allows you to normalize timestamps and dates, making them easier to work with.
The result of the DATE_TRUNC
function will have the same data type as the source value. If the source is a timestamp, the truncated value will be a timestamp as well. Similarly, if the source is a date, the truncated value will be a date. The time zone information is retained when using DATE_TRUNC
with timestamps.