Truncates a DATE, TIME, or TIMESTAMP value to the specified precision. For example,
truncating a timestamp down to the quarter returns the timestamp corresponding
to midnight of the first day of the original timestamp’s quarter.
This function provides an alternative syntax for TRUNCATE, TRUNC by reversing the
two arguments.
Truncation is not the same as extraction. For example:
Truncating a timestamp down to the quarter using this function returns the timestamp corresponding
to midnight of the first day of the quarter for the input timestamp.
Extracting the quarter date part from a timestamp using the Extract function returns the
quarter number of the year in the timestamp.
When date_or_time_part is week (or any of its variations), the output is controlled
by the WEEK_START session parameter. For more details, including examples, see
Calendar weeks and weekdays.
For TIME values, you can’t specify a date_or_time_part that is outside the scope of the TIME type.
For example, you can truncate a TIMESTAMP value to a day, week, year, and so on because the TIMESTAMP type
encodes date/times with the required precision. However, trying to truncate a TIME value to a day, week, year,
and so on causes an error.
The following examples show date truncation. In all cases, the returned value
is of the same data type as the input value, but with zeros for the portions,
such as fractional seconds, that were truncated.
Truncate a date down to the year, month, and day:
SELECT mydate AS"DATE",DATE_TRUNC('year', mydate)AS"TRUNCATED TO YEAR",DATE_TRUNC('month', mydate)AS"TRUNCATED TO MONTH",DATE_TRUNC('week', mydate)AS"TRUNCATED TO WEEK",DATE_TRUNC('day', mydate)AS"TRUNCATED TO DAY"FROM test_date_trunc;
Truncate a TIMESTAMP down to the hour, minute, and second:
SELECT mytimestamp AS"TIMESTAMP",DATE_TRUNC('hour', mytimestamp)AS"TRUNCATED TO HOUR",DATE_TRUNC('minute', mytimestamp)AS"TRUNCATED TO MINUTE",DATE_TRUNC('second', mytimestamp)AS"TRUNCATED TO SECOND"FROM test_date_trunc;