Smart Systems for Home

Plain how-to guides for smart home, security and home Wi-Fi

PostgreSQL date_trunc Function: Usage and Examples

· 5 min read · Home Tech

In this article
  1. What You'll Need
  2. Step-by-Step
  3. Common Mistakes
  4. Tips
  5. Troubleshooting
  6. Frequently Asked Questions

The date_trunc function in PostgreSQL is used to truncate a timestamp or interval to a specified level of precision, effectively "rounding down" the date to the start of the nearest year, month, day, hour, or other designated unit. This is primarily achieved by setting all fields smaller than the specified precision to their minimum values. For example, truncating a timestamp to 'month' will keep the year and month but reset the day to 01 and the time to 00:00:00.

What You'll Need

  • A PostgreSQL database instance (any modern version).
  • A SQL client or interface (such as pgAdmin, psql, or DBeaver) to execute queries.
  • A table containing timestamp, timestamptz, or interval data types.

Step-by-Step

  1. Identify your target precision. Before writing the query, decide which time unit you want to group or truncate by. PostgreSQL accepts several field strings, including:
    • 'year': Truncates to January 1st of the current year.
    • 'quarter': Truncates to the first day of the current quarter.
    • 'month': Truncates to the first day of the current month.
    • 'week': Truncates to the Monday of the current week.
    • 'day': Truncates to the start of the current day (midnight).
    • 'hour': Truncates to the start of the current hour.
    • 'minute': Truncates to the start of the current minute.
    • 'second': Truncates to the start of the current second.
  2. Construct the basic function call. The syntax for the function is date_trunc('field', source). For a simple test using the current time, you can run:
    SELECT date_trunc('month', now());
    This will return the first day of the current month at midnight.
  3. Apply the function to a table column. To use this in a real-world scenario, replace the now() function with your column name. If you have a table called orders with a column created_at, use:
    SELECT date_trunc('day', created_at) FROM orders;
  4. Use date_trunc for data aggregation. The most common use case for date_trunc is creating reports. To count how many orders were placed per month, combine date_trunc with a GROUP BY clause:
    SELECT date_trunc('month', created_at) AS order_month, count(*) 
        FROM orders 
        GROUP BY order_month 
        ORDER BY order_month DESC;
    This groups all timestamps within the same month into a single bucket, allowing the count(*) function to calculate totals for that specific month.
  5. Cast the result for cleaner output. date_trunc always returns a timestamp or interval. If you only need the date (without the 00:00:00 time), cast the result to a date type using the ::date syntax:
    SELECT date_trunc('month', created_at)::date FROM orders;
  6. Filter data using truncated ranges. You can use the function in a WHERE clause to find records that fall within a specific truncated window. For example, to find all records from the current month:
    SELECT * FROM orders 
        WHERE date_trunc('month', created_at) = date_trunc('month', now());

Common Mistakes

One of the most frequent errors is passing the precision field as a column identifier rather than a string literal. You must wrap the field (e.g., 'day', 'month') in single quotes. Writing date_trunc(month, created_at) will cause PostgreSQL to look for a column named month, resulting in an "undefined column" error.

Another common mistake is confusing date_trunc with date_part or extract. While extract(month from created_at) returns an integer (e.g., 5 for May), date_trunc('month', created_at) returns a full timestamp representing the start of that month (e.g., 2023-05-01 00:00:00). If you use extract for grouping, you will merge May 2022 and May 2023 into the same group, whereas date_trunc keeps them separate by preserving the year.

Users also often forget that date_trunc('week', ... ) always defaults to Monday as the start of the week. If your business logic requires Sunday as the start of the week, date_trunc cannot do this natively; you will need to subtract one day from the timestamp before truncating or add logic to adjust the result.

Tips

To optimize performance when using date_trunc in a WHERE clause on large datasets, be aware that wrapping a column in a function usually prevents the database from using a standard B-tree index on that column. This leads to a full table scan. To fix this, create a function-based index. For example: CREATE INDEX idx_orders_month ON orders (date_trunc('month', created_at));. This allows PostgreSQL to store the truncated values in the index, making your monthly reports significantly faster.

When working with time zones, prefer using timestamptz (timestamp with time zone). date_trunc respects the current timezone setting of your database session. If you need to truncate based on a specific time zone regardless of the server setting, use the AT TIME ZONE construct: date_trunc('day', created_at AT TIME ZONE 'UTC').

For highly dynamic reporting where the user chooses the granularity (day, week, month), you can pass a variable or a parameter into the first argument of date_trunc. This makes your SQL queries reusable across different reporting views without rewriting the logic.

Troubleshooting

If you receive a "function date_trunc(unknown, timestamp without time zone) does not exist" error, double-check your quotes. Ensure the first argument is a string in single quotes. If the error persists, verify that the second argument is actually a timestamp or interval type. If you are passing a string that looks like a date, you must cast it first: date_trunc('day', '2023-01-01'::timestamp).

If your GROUP BY results are not aggregating as expected (e.g., you see multiple entries for the same month), check if your column contains time zone offsets that are pushing some records into the previous or next month. Use SELECT created_at, date_trunc('month', created_at) FROM orders LIMIT 10; to inspect the raw data alongside the truncated result to identify discrepancies.

If the query is running extremely slowly, check the execution plan using EXPLAIN ANALYZE. If you see a "Seq Scan" on a large table, it is likely because date_trunc is being used in the WHERE clause without a corresponding function-based index. Implementing the index mentioned in the Tips section is the primary solution for this performance bottleneck.

Frequently Asked Questions

Does date_trunc round to the nearest unit or always round down?

It always rounds down (truncates). For example, date_trunc('hour', '2023-01-01 12:59:59') will return 2023-01-01 12:00:00, not 13:00:00.

Can I use date_trunc with the interval data type?

Yes, date_trunc works with intervals. If you truncate an interval of '13 hours 45 minutes' to 'hour', the result will be '13 hours'.

What is the difference between date_trunc and date_bin?

date_trunc uses predefined calendar units (month, year). date_bin (introduced in PostgreSQL 14) allows you to truncate to arbitrary intervals, such as every 15 minutes or every 2 hours.

How do I truncate to the start of the current year?

Use date_trunc('year', now()). This will return January 1st of the current year at 00:00:00.

Can date_trunc be used in a VIEW?

Yes, it is very common to use date_trunc within a View to provide a simplified, pre-aggregated reporting layer for BI tools that cannot handle complex SQL logic.