icon Join with us for Oracle DBA Training Live Session ENROLL NOW

Easy PostgreSQL Time Bins: Generating Reportable Charts with date_bin()

Breadcrumb Abstract Shape
Breadcrumb Abstract Shape
Breadcrumb Abstract Shape
Breadcrumb Abstract Shape
Breadcrumb Abstract Shape
Breadcrumb Abstract Shape
PostgreSQL date_bin time binning example showing timestamp data grouped into reportable time intervals for charts and dashboards
  • 25 Nov, 2026
  • 0 Comments
  • 14 Mins Read

Easy PostgreSQL Time Bins: Generating Reportable Charts with date_bin()

Easy PostgreSQL Time Bins: Generating Reportable Charts with date_bin()

Modern applications generate enormous amounts of timestamped data: application logs, API requests, transactions, IoT measurements, user activity, system metrics, and more. A common reporting requirement is to turn this raw timestamp data into consistent time intervals such as 5-minute, 15-minute, hourly, or daily buckets.

PostgreSQL provides several ways to group data by time. Traditionally, developers have relied on functions such as date_trunc(), timestamp arithmetic, or custom expressions. These approaches work well for calendar-based periods, but they become less convenient when you need arbitrary fixed-width intervals.

This is where PostgreSQL’s date_bin() function becomes particularly useful.

With date_bin(), you can take raw timestamps such as:

10:03
10:07
10:12
10:19
10:24

and place them into predictable intervals:

10:00–10:05
10:05–10:10
10:10–10:15
10:15–10:20
10:20–10:25

The result is much easier to aggregate and send to reporting tools, dashboards, charts, and analytics applications.

What Is date_bin() in PostgreSQL?

date_bin() is a PostgreSQL function designed to bin timestamps into specified intervals.

Its basic syntax is:

date_bin(stride, source, origin)

Where:

  • stride defines the size of each bucket.
  • source is the timestamp that you want to bucket.
  • origin defines the reference point from which PostgreSQL calculates the buckets.

For example:

SELECT date_bin(
    '15 minutes',
    TIMESTAMP '2026-11-25 10:23:45',
    TIMESTAMP '2026-11-25 00:00:00'
);

The result is:

2026-11-25 10:15:00

The timestamp 10:23:45 falls into the 15-minute bucket beginning at 10:15:00.

Why Time Binning Matters for Reporting

Suppose an application records every API request:

timestamp response_time_ms
10:01:12 120
10:02:44 145
10:03:21 180
10:07:18 220
10:08:55 190
10:13:02 250

Displaying every individual event on a dashboard would not be very useful.

Instead, you might want:

Time bucket Requests Avg response
10:00 3 148
10:05 2 205
10:10 1 250

This transformation is called time bucketing or time binning.

date_bin() makes this process straightforward.

date_bin() vs date_trunc()

One of the most important questions is:

Why use date_bin() when PostgreSQL already has date_trunc()?

The answer is that they solve slightly different problems.

date_trunc()

date_trunc() works with predefined calendar units.

For example:

SELECT date_trunc('hour', created_at)
FROM orders;

This produces hourly buckets.

You can also use:

date_trunc('day', created_at)
date_trunc('month', created_at)
date_trunc('year', created_at)

This is excellent when your reporting requirement is based on calendar boundaries.

date_bin()

date_bin() is useful when the interval itself is the important part.

For example:

date_bin('15 minutes', created_at, TIMESTAMP '2026-01-01')

or:

date_bin('30 minutes', created_at, TIMESTAMP '2026-01-01')

or:

date_bin('2 hours', created_at, TIMESTAMP '2026-01-01')

This gives you more flexibility for arbitrary fixed-width intervals.

Simple comparison

Requirement Recommended
Calendar day date_trunc()
Calendar month date_trunc()
Calendar year date_trunc()
5-minute buckets date_bin()
15-minute buckets date_bin()
45-minute buckets date_bin()
2-hour buckets date_bin()
Custom fixed intervals date_bin()

Creating Sample Data

Let’s create a simple table for demonstration.

CREATE TABLE api_requests (
    id BIGSERIAL PRIMARY KEY,
    endpoint TEXT NOT NULL,
    requested_at TIMESTAMP NOT NULL,
    response_time_ms INTEGER NOT NULL
);

Insert some sample data:

INSERT INTO api_requests
(endpoint, requested_at, response_time_ms)
VALUES
('/api/users', '2026-11-25 10:01:12', 120),
('/api/users', '2026-11-25 10:02:44', 145),
('/api/orders', '2026-11-25 10:03:21', 180),
('/api/users', '2026-11-25 10:07:18', 220),
('/api/orders', '2026-11-25 10:08:55', 190),
('/api/orders', '2026-11-25 10:13:02', 250),
('/api/users', '2026-11-25 10:17:40', 175),
('/api/orders', '2026-11-25 10:19:22', 310);

Now we can start building reports.

Creating 5-Minute Time Bins

The following query groups requests into five-minute intervals:

SELECT
    date_bin(
        '5 minutes',
        requested_at,
        TIMESTAMP '2026-11-25 00:00:00'
    ) AS time_bucket,
    COUNT(*) AS request_count
FROM api_requests
GROUP BY time_bucket
ORDER BY time_bucket;

The output will look conceptually like:

time_bucket request_count
10:00 3
10:05 2
10:10 1
10:15 2

The important point is that date_bin() returns the start of the bucket.

So:

10:03 → 10:00
10:07 → 10:05
10:08 → 10:05
10:13 → 10:10
10:17 → 10:15

This makes the result easy to group and chart.

Calculating Average Response Time

Time bins become much more useful when combined with aggregate functions.

SELECT
    date_bin(
        '5 minutes',
        requested_at,
        TIMESTAMP '2026-11-25 00:00:00'
    ) AS time_bucket,
    COUNT(*) AS request_count,
    ROUND(AVG(response_time_ms), 2) AS avg_response_time
FROM api_requests
GROUP BY time_bucket
ORDER BY time_bucket;

Now the report can show:

Time bucket Requests Average response
10:00 3 148.33
10:05 2 205.00
10:10 1 250.00
10:15 2 242.50

Generating Multiple Metrics in the Same Query

A single time-bucket query can calculate several metrics.

SELECT
    date_bin(
        '5 minutes',
        requested_at,
        TIMESTAMP '2026-11-25 00:00:00'
    ) AS time_bucket,

    COUNT(*) AS total_requests,

    ROUND(AVG(response_time_ms), 2) AS avg_response_time,

    MIN(response_time_ms) AS min_response_time,

    MAX(response_time_ms) AS max_response_time,

    COUNT(*) FILTER (
        WHERE response_time_ms > 500
    ) AS slow_requests

FROM api_requests

GROUP BY time_bucket

ORDER BY time_bucket;

This creates a much richer report.

Bucket Requests Avg Min Max Slow
10:00 3 148 120 180 0
10:05 2 205 190 220 0
10:10 1 250 250 250 0
10:15 2 243 175 310 0

Creating 15-Minute Reporting Buckets

Changing the interval is simple.

SELECT
    date_bin(
        '15 minutes',
        requested_at,
        TIMESTAMP '2026-11-25 00:00:00'
    ) AS time_bucket,
    COUNT(*) AS requests
FROM api_requests
GROUP BY time_bucket
ORDER BY time_bucket;

Now the buckets become:

10:00
10:15
10:30
10:45
11:00

This is useful when your dashboard needs fewer points.

Creating Hourly Buckets

You can also use:

SELECT
    date_bin(
        '1 hour',
        requested_at,
        TIMESTAMP '2026-11-25 00:00:00'
    ) AS hour_bucket,
    COUNT(*) AS requests
FROM api_requests
GROUP BY hour_bucket
ORDER BY hour_bucket;

For larger reports, hourly aggregation can significantly reduce the number of rows returned to the application.

Creating 30-Minute Buckets

For operational dashboards, 30-minute intervals can be useful:

SELECT
    date_bin(
        '30 minutes',
        requested_at,
        TIMESTAMP '2026-11-25 00:00:00'
    ) AS time_bucket,
    COUNT(*) AS requests
FROM api_requests
GROUP BY time_bucket
ORDER BY time_bucket;

Using date_bin() with Different Origins

The third argument of date_bin() is important.

Consider:

date_bin(
    '15 minutes',
    requested_at,
    TIMESTAMP '2026-11-25 00:00:00'
)

The origin establishes the alignment of the bins.

This means PostgreSQL calculates the buckets relative to midnight.

You can choose another origin if your business reporting period starts at a different point.

For example:

date_bin(
    '15 minutes',
    requested_at,
    TIMESTAMP '2026-11-25 00:07:00'
)

The bucket boundaries are now aligned relative to 10:07, rather than midnight.

This is useful when your application has custom reporting boundaries.

Building a Report for a Specific Time Range

A practical report should normally filter the source data before aggregation.

For example:

SELECT
    date_bin(
        '15 minutes',
        requested_at,
        TIMESTAMP '2026-11-25 00:00:00'
    ) AS time_bucket,

    COUNT(*) AS requests,

    ROUND(AVG(response_time_ms), 2) AS avg_response_time

FROM api_requests

WHERE requested_at >= TIMESTAMP '2026-11-25 09:00:00'
  AND requested_at <  TIMESTAMP '2026-11-25 12:00:00'

GROUP BY time_bucket

ORDER BY time_bucket;

This is a common pattern for dashboard APIs.

Time Bins for Different API Endpoints

Suppose you want to compare endpoint performance.

You can include the endpoint in the grouping:

SELECT
    date_bin(
        '15 minutes',
        requested_at,
        TIMESTAMP '2026-11-25 00:00:00'
    ) AS time_bucket,

    endpoint,

    COUNT(*) AS request_count,

    ROUND(AVG(response_time_ms), 2) AS avg_response_time

FROM api_requests

GROUP BY
    time_bucket,
    endpoint

ORDER BY
    time_bucket,
    endpoint;

The output becomes something like:

Time Endpoint Requests Avg response
10:00 /api/users 2 132.5
10:00 /api/orders 1 180
10:05 /api/users 1 220
10:05 /api/orders 1 190

This structure can be directly consumed by many charting libraries.

Creating Chart-Ready Data

One of the biggest benefits of time binning is that the database can return chart-ready data.

For example:

SELECT
    date_bin(
        '15 minutes',
        requested_at,
        TIMESTAMP '2026-11-25 00:00:00'
    ) AS time_bucket,

    COUNT(*) AS requests,

    ROUND(AVG(response_time_ms), 2) AS avg_latency

FROM api_requests

WHERE requested_at >= TIMESTAMP '2026-11-25 00:00:00'
  AND requested_at <  TIMESTAMP '2026-11-26 00:00:00'

GROUP BY time_bucket

ORDER BY time_bucket;

Your application could transform this into:

[
  {
    "time": "10:00",
    "requests": 125,
    "avg_latency": 142.5
  },
  {
    "time": "10:15",
    "requests": 148,
    "avg_latency": 155.2
  },
  {
    "time": "10:30",
    "requests": 172,
    "avg_latency": 161.8
  }
]

A frontend can then use these values for:

  • line charts
  • bar charts
  • monitoring dashboards
  • KPI reports
  • operational analytics
  • performance graphs

The Missing Bucket Problem

There is an important issue with time-based reporting.

Suppose there were no requests between:

10:15

and:

10:30

A normal GROUP BY query may simply omit the 10:15 or 10:30 bucket.

For a chart, this can be problematic.

You might want:

10:00 → 25 requests
10:05 → 32 requests
10:10 → 18 requests
10:15 → 0 requests
10:20 → 27 requests

instead of:

10:00 → 25
10:05 → 32
10:10 → 18
10:20 → 27

To generate continuous reporting intervals, PostgreSQL’s generate_series() is extremely useful.

Combining date_bin() with generate_series()

First, generate the expected time buckets:

SELECT generate_series(
    TIMESTAMP '2026-11-25 10:00:00',
    TIMESTAMP '2026-11-25 11:00:00',
    INTERVAL '5 minutes'
) AS time_bucket;

This produces:

10:00
10:05
10:10
10:15
10:20
10:25
10:30
10:35
10:40
10:45
10:50
10:55
11:00

Now we can join those buckets with our aggregated data.

WITH buckets AS (
    SELECT generate_series(
        TIMESTAMP '2026-11-25 10:00:00',
        TIMESTAMP '2026-11-25 11:00:00',
        INTERVAL '5 minutes'
    ) AS time_bucket
),

aggregated AS (
    SELECT
        date_bin(
            '5 minutes',
            requested_at,
            TIMESTAMP '2026-11-25 00:00:00'
        ) AS time_bucket,
        COUNT(*) AS request_count
    FROM api_requests
    WHERE requested_at >= TIMESTAMP '2026-11-25 10:00:00'
      AND requested_at <  TIMESTAMP '2026-11-25 11:00:00'
    GROUP BY time_bucket
)

SELECT
    b.time_bucket,
    COALESCE(a.request_count, 0) AS request_count
FROM buckets b
LEFT JOIN aggregated a
    ON a.time_bucket = b.time_bucket
ORDER BY b.time_bucket;

Now empty buckets can appear as zero.

This is extremely useful for charting.

Why COALESCE() Matters

Consider:

COALESCE(a.request_count, 0)

If there are no matching rows, the LEFT JOIN produces NULL.

But for a chart, you usually want:

NULL

to become:

0

That’s exactly what COALESCE() does.

Building a Time-Based Performance Dashboard

A practical PostgreSQL dashboard might contain:

Requests per interval

COUNT(*)

Average latency

AVG(response_time_ms)

Maximum latency

MAX(response_time_ms)

Slow requests

COUNT(*) FILTER (
    WHERE response_time_ms > 500
)

A single query can produce all of these:

SELECT
    date_bin(
        '15 minutes',
        requested_at,
        TIMESTAMP '2026-11-25 00:00:00'
    ) AS time_bucket,

    COUNT(*) AS total_requests,

    ROUND(AVG(response_time_ms), 2) AS avg_latency,

    MAX(response_time_ms) AS max_latency,

    COUNT(*) FILTER (
        WHERE response_time_ms > 500
    ) AS slow_requests

FROM api_requests

WHERE requested_at >= TIMESTAMP '2026-11-25 00:00:00'
  AND requested_at <  TIMESTAMP '2026-11-26 00:00:00'

GROUP BY time_bucket

ORDER BY time_bucket;

This gives the frontend almost everything it needs for a performance dashboard.

date_bin() with timestamptz

Real-world applications frequently store timestamps as:

TIMESTAMPTZ

rather than:

TIMESTAMP

For example:

CREATE TABLE events (
    id BIGSERIAL PRIMARY KEY,
    event_time TIMESTAMPTZ NOT NULL,
    event_type TEXT NOT NULL
);

You can use date_bin() with timezone-aware timestamps as well:

SELECT
    date_bin(
        '15 minutes',
        event_time,
        TIMESTAMPTZ '2026-11-25 00:00:00+00'
    ) AS time_bucket,
    COUNT(*)
FROM events
GROUP BY time_bucket
ORDER BY time_bucket;

This is especially important for applications serving users across different time zones.

Time Zone Considerations

Time zones can become complicated in reporting systems.

Imagine an application storing events in UTC:

2026-11-25 04:30 UTC

A user in India sees:

2026-11-25 10:00 IST

If your reporting requirement is based on the user’s local day, simply grouping UTC timestamps may produce unexpected results.

For consistent analytics, decide whether your reporting buckets should represent:

  • UTC time
  • server time
  • business time zone
  • user-specific local time

This decision should be made before designing the reporting query.

date_bin() for IoT Data

Time binning is particularly useful for IoT systems.

Suppose sensors generate readings every few seconds:

timestamp              temperature
10:00:01               24.2
10:00:05               24.4
10:00:12               24.1
10:00:17               24.7
...

Instead of returning thousands of readings, you could generate five-minute summaries:

SELECT
    date_bin(
        '5 minutes',
        measured_at,
        TIMESTAMP '2026-11-25 00:00:00'
    ) AS time_bucket,

    ROUND(AVG(temperature), 2) AS avg_temperature,

    MIN(temperature) AS min_temperature,

    MAX(temperature) AS max_temperature

FROM sensor_readings

GROUP BY time_bucket

ORDER BY time_bucket;

The result is much more manageable for charts.

date_bin() for Financial Transactions

Consider a payments table:

CREATE TABLE payments (
    id BIGSERIAL PRIMARY KEY,
    paid_at TIMESTAMPTZ NOT NULL,
    amount NUMERIC(12,2) NOT NULL
);

You could generate hourly transaction reports:

SELECT
    date_bin(
        '1 hour',
        paid_at,
        TIMESTAMPTZ '2026-11-25 00:00:00+00'
    ) AS hour_bucket,

    COUNT(*) AS transaction_count,

    SUM(amount) AS total_amount,

    AVG(amount) AS average_transaction

FROM payments

GROUP BY hour_bucket

ORDER BY hour_bucket;

This is useful for:

  • payment monitoring
  • transaction dashboards
  • revenue reporting
  • fraud analysis
  • operational monitoring

date_bin() for Application Monitoring

Application logs often contain timestamps and response metrics.

For example:

SELECT
    date_bin(
        '1 minute',
        created_at,
        TIMESTAMP '2026-11-25 00:00:00'
    ) AS minute_bucket,

    COUNT(*) AS requests,

    AVG(duration_ms) AS avg_duration,

    COUNT(*) FILTER (
        WHERE status_code >= 500
    ) AS server_errors

FROM application_logs

WHERE created_at >= NOW() - INTERVAL '1 hour'

GROUP BY minute_bucket

ORDER BY minute_bucket;

This can produce a real-time monitoring dataset such as:

Minute     Requests    Avg Duration    5xx Errors
10:00      1,250       145 ms          2
10:01      1,310       151 ms          4
10:02      1,420       162 ms          8
10:03      1,560       190 ms          21

A sudden increase in errors or latency becomes easy to visualize.

Performance Considerations

Time-binning queries can process large amounts of data.

If your table contains millions or billions of rows, filtering the data first is important.

Prefer:

WHERE requested_at >= ...
  AND requested_at < ...

before aggregation.

For example:

SELECT
    date_bin(
        '15 minutes',
        requested_at,
        TIMESTAMP '2026-11-25 00:00:00'
    ) AS time_bucket,
    COUNT(*)
FROM api_requests
WHERE requested_at >= TIMESTAMP '2026-11-25 00:00:00'
  AND requested_at <  TIMESTAMP '2026-11-26 00:00:00'
GROUP BY time_bucket;

rather than retrieving the entire table and filtering later in application code.

Indexing the Timestamp Column

For large datasets, an index on the timestamp column can help the time-range filter:

CREATE INDEX idx_api_requests_requested_at
ON api_requests(requested_at);

Then a query containing:

WHERE requested_at >= ...
  AND requested_at < ...

can potentially use the index to locate the relevant time range efficiently.

The exact execution plan depends on table size, data distribution, statistics, query shape, and PostgreSQL’s planner decisions.

Always verify with:

EXPLAIN ANALYZE

when performance matters.

A Common Mistake: Grouping by Raw Timestamp

This query is usually not useful for time-series reporting:

SELECT
    requested_at,
    COUNT(*)
FROM api_requests
GROUP BY requested_at;

If every event has a different timestamp, almost every timestamp becomes its own group.

Instead:

SELECT
    date_bin(
        '15 minutes',
        requested_at,
        TIMESTAMP '2026-11-25 00:00:00'
    ) AS time_bucket,
    COUNT(*)
FROM api_requests
GROUP BY time_bucket
ORDER BY time_bucket;

Now thousands of individual timestamps can be reduced to manageable reporting intervals.

Another Common Mistake: Using the Wrong Interval

If your dashboard needs 15-minute reporting but you use:

date_bin('1 hour', ...)

you lose information.

Conversely, if you use:

date_bin('1 second', ...)

for millions of events, you may create far too many buckets.

Choose the interval based on the reporting requirement.

Use case Suggested bucket
Real-time API monitoring 1–5 minutes
Application metrics 5–15 minutes
Operational dashboard 15–30 minutes
Hourly reports 1 hour
Daily analytics 1 day
Long-term trend 1 week/month depending on requirement

These are design choices rather than strict rules.

A Reusable Reporting Query

You can build a reusable pattern around date_bin():

SELECT
    date_bin(
        INTERVAL '15 minutes',
        event_time,
        TIMESTAMP '2026-01-01 00:00:00'
    ) AS bucket,

    COUNT(*) AS event_count,

    AVG(metric_value) AS average_value,

    MIN(metric_value) AS minimum_value,

    MAX(metric_value) AS maximum_value

FROM events

WHERE event_time >= $1
  AND event_time <  $2

GROUP BY bucket

ORDER BY bucket;

Here:

$1 = report start time
$2 = report end time

This makes the query easy to use from application code.

date_bin() and Window Functions

Time bins can also be combined with PostgreSQL window functions.

For example, first aggregate the data:

WITH bucketed AS (
    SELECT
        date_bin(
            '15 minutes',
            requested_at,
            TIMESTAMP '2026-11-25 00:00:00'
        ) AS bucket,
        COUNT(*) AS requests
    FROM api_requests
    GROUP BY bucket
)

SELECT
    bucket,
    requests,
    SUM(requests) OVER (
        ORDER BY bucket
    ) AS cumulative_requests
FROM bucketed
ORDER BY bucket;

Now you can generate:

Bucket Requests Cumulative
10:00 20 20
10:15 35 55
10:30 40 95
10:45 25 120

This can be useful for cumulative charts and operational reports.

Dynamic Bucket Sizes

In some applications, users can select:

5 minutes
15 minutes
1 hour
6 hours
1 day

Your application can pass the selected interval into the query.

For example, conceptually:

date_bin($1, requested_at, $2)

where:

$1 = bucket interval
$2 = origin

The application can then dynamically generate different reporting resolutions.

However, the allowed values should be validated by the application rather than accepting arbitrary untrusted SQL fragments.

When Should You Use date_bin()?

date_bin() is a strong choice when you need:

  • fixed-width time intervals
  • custom bucket sizes
  • time-series aggregation
  • chart-ready datasets
  • monitoring dashboards
  • API performance reports
  • IoT summaries
  • transaction aggregation
  • application analytics
  • consistent time buckets

For simple calendar-based grouping such as month, quarter, or year, date_trunc() may be more natural.

Best Practices

When using date_bin() in production reporting queries:

1. Filter before aggregating

Use a timestamp range:

WHERE event_time >= $1
AND event_time < $2

2. Choose the right bucket size

Don’t create thousands of unnecessary buckets for a dashboard that only needs hourly data.

3. Use an appropriate origin

Make sure your bucket boundaries align with the business reporting requirement.

4. Handle empty buckets

Use generate_series() when continuous chart intervals are required.

5. Use COALESCE()

Convert missing aggregate values to zero when appropriate.

6. Index timestamp columns

For large tables, an index on the timestamp column can help range filtering.

7. Check execution plans

Use:

EXPLAIN ANALYZE

to verify query performance.

8. Consider time zones carefully

Decide whether reports should be based on UTC or a specific business/user time zone.

Conclusion

PostgreSQL’s date_bin() provides a clean and flexible way to convert raw timestamp data into meaningful reporting intervals.

Instead of manually calculating time boundaries, you can write:

date_bin(
    '15 minutes',
    event_time,
    TIMESTAMP '2026-11-25 00:00:00'
)

and immediately turn individual events into predictable time buckets.

Combined with:

COUNT()
AVG()
MIN()
MAX()
FILTER
generate_series()
COALESCE()

you can build powerful time-series reports directly inside PostgreSQL.

The real advantage is that the database can return structured, aggregated, chart-ready data, allowing dashboards and applications to focus on visualization rather than performing complicated timestamp calculations themselves.

For PostgreSQL developers and database administrators, date_bin() is therefore a valuable tool for building cleaner time-series queries, operational dashboards, monitoring reports, and analytics APIs.

 

lets talk - learnomate helpdesk

Book a Free Demo

lets talk - learnomate helpdesk

Book a Free Demo