---
title: "Use TimescaleDB for Time-Series Data"
description: "Use TimescaleDB hypertables and time_bucket on Exoscale Managed PostgreSQL, within the limits of its Apache license."
url: https://community.exoscale.com/product/dbaas/service-specific/postgresql/how-to/use-timescaledb/
product: "PostgreSQL"
section: product
last_updated: 2026-11-10
---
> For AI agents: the documentation index is at https://community.exoscale.com/llms.txt. Every page is available as markdown at `<page URL>index.md` or with `Accept: text/markdown`.

# Use TimescaleDB for Time-Series Data

Enable TimescaleDB on Managed PostgreSQL, turn a table into a hypertable, query it with `time_bucket()`, and automate retention with `pg_cron`.

## What Is Available

Managed PostgreSQL ships the Apache-licensed edition of TimescaleDB. Check it after creating the
extension:

```sql
SHOW timescaledb.license;
```

The value is `apache`. Hypertables, chunks, `time_bucket()`, `first()`, `last()`,
`histogram()`, `show_chunks()` and `drop_chunks()` work.

The features of the Timescale License (TSL) do not. They fail with an error such as
`function "add_retention_policy" is not supported under the current "apache" license`, or
`functionality not supported under the current "apache" license`:

- Policies and jobs: `add_retention_policy()`, `add_compression_policy()`,
  `add_columnstore_policy()`, `add_job()`, `alter_job()`, `delete_job()`.
- Compression and columnstore: `ALTER TABLE ... SET (timescaledb.compress)`.
- Continuous aggregates: `CREATE MATERIALIZED VIEW ... WITH (timescaledb.continuous)`.
- Gap filling: `time_bucket_gapfill()`, `locf()`, `interpolate()`.

The TSL edition cannot be selected: `exo dbaas update` with `--pg-variant timescale` is refused
with ``Invalid value `timescale` at 'variant': should be one of aiven``.

Replacements on Managed PostgreSQL:

- **Retention**: schedule `drop_chunks()` with `pg_cron`, see
  [Automate Retention with pg_cron](#automate-retention-with-pg_cron).
- **Rollups**: a plain materialized view over a `time_bucket()` query, refreshed by `pg_cron`.
  The refresh recomputes the whole view, so keep its time window bounded.
- **Gap filling**: join the aggregate onto a `generate_series()` of buckets, see
  [Fill Empty Buckets](#fill-empty-buckets).

## Enable the Extension

Connect as `avnadmin` (see
[Connect with psql](https://community.exoscale.com/product/dbaas/service-specific/postgresql/how-to/connect-with-psql/index.md)) to the
database that holds your time-series tables:

```sql
CREATE EXTENSION timescaledb;
```

```sql
SELECT extname, extversion FROM pg_extension WHERE extname = 'timescaledb';
```

Run `CREATE EXTENSION timescaledb` as the first statement of a new session. If the session has
already loaded another version of the library, it fails with
`extension "timescaledb" has already been loaded with another version` and asks you to start a
new session.

## Create a Hypertable

A hypertable is split into chunks, one per time range. Queries that filter on time only read the
chunks they need.

```sql
CREATE TABLE sensor_data (
    recorded_at  timestamptz      NOT NULL,
    device_id    text             NOT NULL,
    temperature  double precision NOT NULL,
    humidity     double precision,
    battery_pct  smallint,
    PRIMARY KEY (recorded_at, device_id)
);
```

```sql
SELECT create_hypertable(
    'sensor_data',
    'recorded_at',
    chunk_time_interval => INTERVAL '1 day',
    if_not_exists       => true
);
```

Primary keys and unique constraints must include the time column. A table with
`id bigserial PRIMARY KEY` is refused with
`cannot create a unique index without the column "recorded_at" (used in partitioning)`.

A table that already holds rows is refused with `table "..." is not empty`, unless you ask for the
data to be moved. The move rewrites the data and locks the table meanwhile:

```sql
SELECT create_hypertable(
    'sensor_data',
    'recorded_at',
    chunk_time_interval => INTERVAL '1 day',
    migrate_data        => true
);
```

Add ordinary indexes for your filters:

```sql
CREATE INDEX ON sensor_data (device_id, recorded_at DESC);
```

```sql
SELECT hypertable_name, num_dimensions, num_chunks
FROM timescaledb_information.hypertables;
```

## Query with time_bucket

`time_bucket()` groups rows into intervals of any width:

```sql
SELECT
    time_bucket(INTERVAL '1 hour', recorded_at) AS bucket,
    device_id,
    avg(temperature) AS avg_temperature,
    max(temperature) AS max_temperature,
    count(*)         AS samples
FROM sensor_data
WHERE recorded_at >= now() - INTERVAL '24 hours'
GROUP BY bucket, device_id
ORDER BY bucket DESC;
```

Always filter on the time column, so that TimescaleDB can skip chunks.

`first()` and `last()` return a value at the earliest or latest time, for example the latest
reading per device:

```sql
SELECT
    device_id,
    first(temperature, recorded_at) AS first_temperature,
    last(temperature, recorded_at)  AS last_temperature
FROM sensor_data
WHERE recorded_at >= now() - INTERVAL '1 hour'
GROUP BY device_id;
```

Combined with `time_bucket()`, they downsample a series:

```sql
SELECT
    time_bucket(INTERVAL '15 minutes', recorded_at) AS bucket,
    device_id,
    last(battery_pct, recorded_at) AS battery_pct
FROM sensor_data
WHERE recorded_at >= now() - INTERVAL '6 hours'
GROUP BY bucket, device_id
ORDER BY bucket DESC;
```

`histogram()` counts values in equal-width bins between two bounds:

```sql
SELECT device_id, histogram(temperature, 0, 40, 10) AS distribution
FROM sensor_data
WHERE recorded_at >= now() - INTERVAL '7 days'
GROUP BY device_id;
```

The array has the 10 requested bins plus one element for values below the lower bound and one
for values above the upper bound.

### Fill Empty Buckets

Generate the buckets with `generate_series()` and join the data onto them:

```sql
SELECT g AS bucket, avg(s.temperature) AS avg_temperature
FROM generate_series(time_bucket(INTERVAL '1 hour', now() - INTERVAL '6 hours'),
                     now(), INTERVAL '1 hour') AS g
LEFT JOIN sensor_data s
       ON time_bucket(INTERVAL '1 hour', s.recorded_at) = g
GROUP BY g
ORDER BY g;
```

Buckets without rows return `NULL`.

## Inspect Chunks

Chunks that are too large reduce the benefit of partitioning; chunks that are too small add
planning overhead. A common target is that the most recent chunk and its indexes fit in memory.

```sql
SELECT show_chunks('sensor_data');
```

```sql
SELECT chunk_name, range_start, range_end
FROM timescaledb_information.chunks
WHERE hypertable_name = 'sensor_data'
ORDER BY range_start DESC;
```

List the chunks older than a threshold, which is also what `drop_chunks()` would remove:

```sql
SELECT show_chunks('sensor_data', older_than => INTERVAL '90 days');
```

Change the interval for new chunks; existing chunks keep their range:

```sql
SELECT set_chunk_time_interval('sensor_data', INTERVAL '2 days');
```

Estimate the row count from statistics, which are as fresh as the last `ANALYZE`:

```sql
SELECT approximate_row_count('sensor_data');
```

## Automate Retention with pg_cron

Dropping a chunk removes its rows and frees its disk space at once, unlike `DELETE`. A chunk is
dropped only when its whole time range is older than the threshold.

Drop old chunks once:

```sql
SELECT drop_chunks('sensor_data', older_than => INTERVAL '90 days');
```

To repeat it every night, create [pg_cron](https://community.exoscale.com/product/dbaas/service-specific/postgresql/how-to/use-pg-cron/index.md)
in `defaultdb`, the only database that accepts it:

```sql
CREATE EXTENSION pg_cron;
```

Then, still in `defaultdb`, schedule the call in the database that holds the hypertable:

```sql
SELECT cron.schedule_in_database(
    'sensor-data-retention',
    '0 3 * * *',
    $$SELECT drop_chunks('public.sensor_data', older_than => INTERVAL '90 days')$$,
    'DATABASE_NAME'
);
```

Parameters:

- `DATABASE_NAME`: database with the hypertable and the `timescaledb` extension. If the
  hypertable is in `defaultdb`, use `cron.schedule()` with the first three arguments.

Check the runs:

```sql
SELECT d.status, d.return_message, d.start_time, d.end_time
FROM cron.job_run_details d
JOIN cron.job j USING (jobid)
WHERE j.jobname = 'sensor-data-retention'
ORDER BY d.start_time DESC
LIMIT 5;
```

> [!WARNING]
> The job deletes data without asking. Test the threshold with `show_chunks()` first. Getting
> dropped data back means creating a new service from a point in time before the drop, see
> [Fork a service](https://community.exoscale.com/product/dbaas/service-specific/postgresql/how-to/fork-a-service/index.md).

A rollup view is refreshed the same way. `REFRESH ... CONCURRENTLY` needs a unique index on the
view and keeps it readable during the refresh:

```sql
CREATE MATERIALIZED VIEW public.sensor_data_hourly AS
SELECT time_bucket(INTERVAL '1 hour', recorded_at) AS bucket,
       device_id,
       avg(temperature) AS avg_temperature
FROM sensor_data
WHERE recorded_at > now() - INTERVAL '30 days'
GROUP BY bucket, device_id;

CREATE UNIQUE INDEX ON public.sensor_data_hourly (bucket, device_id);
```

```sql
SELECT cron.schedule_in_database(
    'sensor-data-hourly-refresh',
    '5 * * * *',
    $$REFRESH MATERIALIZED VIEW CONCURRENTLY public.sensor_data_hourly$$,
    'DATABASE_NAME'
);
```

## TimescaleDB Service Settings

The number of TimescaleDB background workers is a service setting, separate from `--pg-settings`.
Read its range in the settings catalog:

```bash
exo api get-dbaas-settings-pg -q 'settings.timescaledb'
```

Change it with:

```bash
exo dbaas update SERVICE_NAME -z ZONE -f --pg-timescaledb-settings '{"max_background_workers":8}'
```

Parameters:

- `SERVICE_NAME`: name of the service.
- `ZONE`: zone of the service, for example `ch-gva-2`.

The change restarts the service. Check the value with `SHOW timescaledb.max_background_workers;`.

## Related Pages

- [Use pg_cron to schedule jobs](https://community.exoscale.com/product/dbaas/service-specific/postgresql/how-to/use-pg-cron/index.md)
- [Use pg_partman to partition tables](https://community.exoscale.com/product/dbaas/service-specific/postgresql/how-to/use-pg-partman/index.md)
- [Manage extensions](https://community.exoscale.com/product/dbaas/service-specific/postgresql/how-to/manage-extensions/index.md)
- [Configure PostgreSQL settings](https://community.exoscale.com/product/dbaas/service-specific/postgresql/how-to/configure-settings/index.md)
- [TimescaleDB documentation](https://docs.timescale.com/) ↗

