PostgreSQL DATE_TRUNC() Function
Summary: This tutorial shows you how to use the PostgreSQL DATE_TRUNC()
function to truncate a timestamp or interval to a specified precision.
Introduction to the PostgreSQL DATE_TRUNC() function
The DATE_TRUNC()
function truncates a TIMESTAMP
, a TIMESTAMP WITH TIME ZONE
, or an INTERVAL
value to a specified precision.
Here’s the basic syntax of the DATE_TRUNC
function:
In this syntax:
source
source
is a value or an expression of type timestamp, timestamp with time zone, or interval. If you use a value of the date or time type, the function will cast it automatically to timestamp or interval respectively.
field
field
specifies the to which precision to truncate the source
.
Here are the valid values for the field
:
- millennium
- century
- decade
- year
- quarter
- month
- week
- day
- hour
- minute
- second
- milliseconds
- microseconds
time_zone
time_zone
specifies the time zone in which the function will perform the truncation. The time_zone
argument is the default.
If you omit the time_zone
, the function will truncate the source
based on the current time zone setting.
The DATE_TRUNC
function returns a TIMESTAMP
or an INTERVAL
value.
PostgreSQL DATE_TRUNC() function examples
Let’s explore some examples of using the DATE_TRUNC()
function.
1) Basic PostgreSQL DATE_TRUNC() function example
The following example uses the DATE_TRUNC()
function to truncate a TIMESTAMP
value to hour
part:
Output:
In this example, the DATE_TRUNC()
function returns a timestamp with the hour precision.
If you want to truncate a TIMESTAMP
value to a minute, you use the 'minute'
field as shown in the following example:
The function returns a TIMESTAMP
with the precision is minute:
2) Using PostgreSQL DATE_TRUNC() function with table data
See the following rental
table in the sample database:
The following example uses the DATE_TRUNC()
function to retrieve the number of rentals by month from the rental table:
Output:
This query retrieves the month of each rental date and counts the number of rentals each month from the rental
table. It then groups the counts by month and sorts the result set by month.
If you want to count the rentals by week, you can pass the week to the DATE_TRUNC() function as follows:
Output:
The following example uses the DATE_TRUNC()
function to count the number of rentals by staff per year:
Output:
Summary
- Use the PostgreSQL
DATE_TRUNC
function to truncate a timestamp or an interval value to a specified level of precision