Open In App

PostgreSQL – DATE_TRUNC Function

Last Updated : 21 Oct, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Share
Report
News Follow

The PostgreSQL DATE_TRUNC() function is a powerful tool that helps us truncate a timestamp or interval to a specified level of precision. It is particularly useful when dealing with time-based data for effective data grouping and manipulation, making it ideal for reporting, analytics, and queries where time intervals matter.

In this article, we will get a better understanding of the DATE_TRUNC function, its syntax, and practical examples to help us understand how to utilize it effectively in PostgreSQL queries.

What is PostgreSQL DATE_TRUNC()?

The DATE_TRUNC() function in PostgreSQL is used to truncate or round down a timestamp, timestamp with time zone, or an interval value to a specified precision, such as year, month, day, or even down to the second or microsecond. This function plays an important role when handling time-related data, as it allows users to group or aggregate data at different time levels.

Syntax

date_trunc('datepart', field)

key terms

  • datepart’: The precision level to which the timestamp should be truncated. Examples include ‘hour‘, ‘day‘, ‘week‘, ‘month‘, ‘year‘, etc.
  • field: The source timestamp or interval we want to truncate.
  • time_zone (optional): The time zone to use when truncating. If omitted, it defaults to the current session time zone.

Supported ‘datepart’ Values for DATE_TRUNC()

The ‘datepart’ argument in the above syntax is used to truncate one of the fields. Here are some of the below-listed field types:

  • ‘millennium’
  • ‘century’
  • ‘decade’
  • ‘year’
  • ‘quarter’
  • ‘month’
  • ‘week’
  • ‘day’
  • ‘hour’
  • ‘minute’
  • ‘second’
  • ‘milliseconds’
  • ‘microseconds’

Examples of PostgreSQL DATE_TRUNC Function

Let us take a look at some of the examples of DATE_TRUNC Function in PostgreSQL to better understand the concept.

Example 1: Truncate Timestamp to the Nearest Hour

The following statement truncates a TIMESTAMP value to hour date part.

Query:

SELECT DATE_TRUNC('hour', TIMESTAMP '2020-03-17 02:09:30');

Output

PostgreSQL DATE_TRUNC Function Example

Explanation:

In this example, the DATE_TRUNC function truncates the timestamp to the start of the hour, discarding minutes and seconds.

Example 2: Truncate Timestamp to the Nearest Day

You can also use the DATE_TRUNC() function to truncate the timestamp down to the day level:

SELECT DATE_TRUNC('day', TIMESTAMP '2024-03-17 18:45:30');

Output

  date_trunc
---------------------
2024-03-17 00:00:00

Example 3: Count Rentals by Staff per Year

A common use case for the DATE_TRUNC() function is grouping data by specific time intervals. For example, let’s count the number of rentals per year from the rental table:

Query:

SELECT
staff_id,
date_trunc('year', rental_date) y,
COUNT (rental_id) rental
FROM
rental
GROUP BY
staff_id, y
ORDER BY
staff_id

Output

PostgreSQL DATE_TRUNC Function Example

Explanation:

This query groups the rentals by staff ID and year, providing a yearly rental count for each staff member.

Example 4: Truncate and Group by Week

We can also group data by week using the DATE_TRUNC() function. Here’s how we can count the rentals per week.

Query:

SELECT
DATE_TRUNC('week', rental_date) AS week,
COUNT(rental_id) AS total_rentals
FROM
rental
GROUP BY
week
ORDER BY
week;

Output

      week          | total_rentals
---------------+---------------
2024-03-10 | 500
2024-03-17 | 600

Explanation:

This query truncates the rental_date to the start of each week and groups the rental data accordingly.

Important Points About PostgreSQL DATE_TRUNC Function

  • The DATE_TRUNC function always truncates to the start of the specified period. For example, truncating to ‘month’ will set the day to the first of the month and the time to 00:00:00.
  • The DATE_TRUNC function respects the time zone of the input timestamp. If we are working with time zone-aware timestamps (TIMESTAMP WITH TIME ZONE), the truncation will consider the time zone in the calculation.
  • The DATE_TRUNC function can be used with INTERVAL types, not just TIMESTAMP types.
  • The DATE_TRUNC function is often used in conjunction with aggregation functions like COUNT, SUM, and AVG to group data by time periods.

Alternative Functions to DATE_TRUNC in PostgreSQL

While DATE_TRUNC() is the most common function for truncating time data, alternatives like EXTRACT() and TO_CHAR() can also be used for retrieving or formatting specific parts of a date. However, these serve different purposes:

  • EXTRACT() retrieves specific fields like the year, month, or day from a date.
  • TO_CHAR() formats dates into a desired text output.

Conclusion

The PostgreSQL DATE_TRUNC() function is an essential tool when working with time-based data. It allows us to truncate timestamps and intervals to a specified precision, making it easier to group, analyze, and report on data. Whether we are truncating by hour, day, or month, this function simplifies the process of working with temporal data.

By understanding and leveraging DATE_TRUNC(), we can efficiently manage and analyze our PostgreSQL time data, optimizing your queries for performance and clarity.

FAQs

What is the function of DATE_TRUNC in Postgres?

The DATE_TRUNC function in PostgreSQL is used to truncate a timestamp or date to a specified precision, such as truncating to the nearest hour, day, week, or month.

What does DATE_TRUNC function do?

The DATE_TRUNC function removes finer time units from a timestamp, returning the date or time truncated to the precision specified, like truncating a timestamp to the start of a day or month.

What is the alternative to DATE_TRUNC in PostgreSQL?

An alternative to DATE_TRUNC is using EXTRACT or TO_CHAR functions, though they serve different purposes like extracting specific parts of a date or formatting dates



Similar Reads

three90RightbarBannerImg