# TimescaleDB Foreign Keys and Hypertables: Which Directions Work, and Which One Breaks Retention

> A hypertable can reference a plain table, a plain table can reference a hypertable, and a hypertable cannot reference a hypertable, itself included. The middle case is the trap: the key is accepted, and then `drop_chunks` and the retention policy refuse to drop chunks, even when no row points into them. Point the key at the plain entity table, such as `devices`, and keep the reading time as an ordinary column.

Source: https://schemity.com/blog/timescaledb-foreign-key-to-hypertable-retention/

A TimescaleDB hypertable can reference a plain table, and a plain table can reference a hypertable, but only the first direction works with a retention policy. A foreign key into a hypertable is accepted, and in every fresh database we tested, `drop_chunks` and the retention policy then refused to drop chunks, because TimescaleDB stores the key as one constraint per chunk and a chunk table cannot be dropped while a constraint depends on it.

Everything below ran on TimescaleDB 2.32.1 on PostgreSQL 18.7, in throwaway containers from the official `timescale/timescaledb` image. The schema is the usual one for sensor data: a plain `devices` table and a `readings` hypertable, partitioned into 7-day chunks.

```sql
CREATE EXTENSION IF NOT EXISTS timescaledb;
CREATE TABLE devices (
  id bigint PRIMARY KEY,
  name text NOT NULL
);
CREATE TABLE readings (
  device_id bigint NOT NULL REFERENCES devices (id),
  time timestamptz NOT NULL,
  temperature double precision NOT NULL,
  PRIMARY KEY (device_id, time)
);
SELECT create_hypertable('readings', by_range('time', INTERVAL '7 days'));
INSERT INTO devices VALUES (1, 'boiler');
INSERT INTO readings
SELECT 1, t, 70 FROM generate_series(TIMESTAMPTZ '2026-01-01', '2026-11-20', INTERVAL '1 hour') t;
```

That is 7,753 rows in 47 chunks.

## TimescaleDB foreign key to hypertable: which directions are allowed?

Two of the four cases are accepted, and only a key whose both ends are hypertables is refused outright.

| Referencing table | Referenced table | Result |
|---|---|---|
| Hypertable `readings` | Plain `devices` | Works, and checks every insert into every chunk |
| Plain `incidents` | Hypertable `readings` | Accepted since TimescaleDB 2.16, then blocks dropping chunks |
| Hypertable `alerts` | Hypertable `readings` | Refused: `hypertables cannot be used as foreign key references of hypertables` |
| Hypertable `events` | Itself | Refused with the same error |

The first row is the ordinary case: a reading for a device that does not exist is refused with `violates foreign key constraint "readings_device_id_fkey"`, raised on the chunk the row would land in. The second row is newer: the [TimescaleDB changelog](https://github.com/timescale/timescaledb/blob/main/CHANGELOG.md) for 2.16.0 says you can now add foreign keys from regular tables towards hypertables. The refused rows cannot be worked around by ordering the steps either: a plain table created with the key and then passed to `create_hypertable` failed with the same error.

## What happens to drop_chunks when a table references a hypertable?

It fails on the first chunk it tries to drop, whether or not any row references that chunk.

Add an `incidents` table that points at the reading that triggered it, which is a natural thing to model:

```sql
CREATE TABLE incidents (
  id bigint PRIMARY KEY,
  device_id bigint NOT NULL,
  reading_time timestamptz NOT NULL,
  FOREIGN KEY (device_id, reading_time) REFERENCES readings (device_id, time)
);
```

With the table still empty, `SELECT drop_chunks('readings', older_than => TIMESTAMPTZ '2026-03-01');` returned, exactly as printed:

```
ERROR:  cannot drop table _timescaledb_internal._hyper_1_1_chunk because other objects depend on it
DETAIL:  constraint incidents_device_id_reading_time_fkey on table incidents depends on table _timescaledb_internal._hyper_1_1_chunk
HINT:  Use DROP ... to drop the dependent objects.
```

The reason is in `pg_constraint`. The one key on `incidents` is stored as the key itself plus one child constraint per chunk, 47 of them for 47 chunks, each depending on its chunk table. `drop_chunks` drops chunks as tables, so every chunk is pinned by its own constraint. Declaring the key `ON DELETE CASCADE` changed nothing, because the refusal is about the chunk table as an object, and `ON DELETE` only governs rows deleted from it. Dropping the key and running the same `drop_chunks` again removed the eight chunks older than 2026-03-01.

The retention policy fails in the background, where it is easy to miss. With `add_retention_policy('readings', drop_after => INTERVAL '180 days')` and the job started by the scheduler, `timescaledb_information.job_stats` recorded the run as `Failed`, the same `cannot drop table` message was in `timescaledb_information.job_errors`, and all 21 chunks that were older than 180 days on the day of the test stayed on disk. Nothing failed in the application. The table just stopped shrinking. We built eight fresh databases for this post and the drop failed in each of them; in one database we had altered back and forth, a later retention run went through, and we could not reproduce that, so check your own job history rather than trusting either outcome.

## Do the workarounds keep the foreign key?

No: both routes that drop the chunk with the key in place give up the key's guarantee without an error.

The HINT points at `DROP TABLE ... CASCADE`. On the chunk, it printed one line, `NOTICE:  drop cascades to constraint incidents_device_id_reading_time_fkey on table incidents`, and removed the whole foreign key, not only the chunk's part of it: `incidents` was left with no key at all, and an incident for a reading that no longer exists then went in without complaint. `detach_chunk`, available in recent versions, behaved differently and just as quietly: it detached a chunk that an `incidents` row still pointed into, and left that row pointing at a reading `readings` no longer had. Neither is a fix; both turn a refusal into silent orphans.

## Should you add a foreign key that references a hypertable?

Not on a hypertable whose chunks you will ever drop; point the key at the plain entity table instead.

| Option | Integrity | Retention | Use when |
|---|---|---|---|
| `incidents.device_id REFERENCES devices (id)`, `reading_time` as a plain column | The device is enforced, the reading is not | Works | Almost always: the device is the entity, the reading is an event |
| Key into the hypertable, no retention | Full | None: chunks are never dropped | The hypertable is small and kept forever |
| Make the referenced data a plain table | Full | Not available on that table | The referenced rows are few and not time series |
| No key, check in a trigger or the application | As good as the code | Works | You need the link and drop chunks, and accept that old incidents will point at dropped readings |

The first row matches what the data means. An incident belongs to a device; the reading that raised it is evidence, and evidence older than the retention window is supposed to disappear. A foreign key would say the opposite, that the reading must exist as long as the incident does, which is exactly the promise a retention policy breaks. If the incident must keep the value it was raised on, copy it into the incident row, `temperature` included, rather than pointing at a row that will be dropped.

## How to find foreign keys that already point into a hypertable

One query over the catalog lists every key that will stop `drop_chunks`, and a second shows whether a retention job has already failed.

```sql
SELECT conrelid::regclass AS referencing_table,
       conname,
       confrelid::regclass AS hypertable
FROM pg_constraint
WHERE contype = 'f'
  AND confrelid IN (
    SELECT format('%I.%I', hypertable_schema, hypertable_name)::regclass
    FROM timescaledb_information.hypertables
  );
```

On the test database it returned one row, `incidents`, `incidents_device_id_reading_time_fkey`, `readings`, and not the 47 per-chunk children, which point at chunk tables rather than at the hypertable. For the jobs:

```sql
SELECT job_id, finish_time, err_message
FROM timescaledb_information.job_errors
WHERE proc_name = 'policy_retention'
ORDER BY finish_time DESC;
```

Run both after any migration that adds a foreign key, and drop a key into a hypertable on purpose, with `ALTER TABLE ... DROP CONSTRAINT`, before the retention job needs to run.

## How Schemity shows the problem before the migration runs

Schemity's impact analysis names the hypertable a new foreign key points into, and says what that does to its chunks, before any SQL runs.

Schemity is database design software that reads your live database, shows the impact of every schema change before it runs, and keeps the diagram as a file in Git. Connected to a PostgreSQL database with the TimescaleDB extension, [impact analysis](https://schemity.com/doc/impact-analysis/), part of Schemity Pro, knows which tables are hypertables. A key between two of them is reported under Storage engine as "Adds a foreign key referencing readings, which TimescaleDB refuses: both tables are hypertables", in place of the usual foreign key finding, since the statement never runs. From the next release, a key from a plain table into a hypertable is reported under Storage engine as "Adds a foreign key referencing readings, a hypertable: `drop_chunks` and retention policies then refuse to drop its chunks", alongside the usual Can fail on existing data finding for rows with no match. The same release lets you draw that key on the columns `incidents` already has: dragging a relation from `readings` to `incidents` offers `device_id` and `reading_time` themselves, and the planned migration is the single `ALTER TABLE "incidents" ADD CONSTRAINT ... FOREIGN KEY ("device_id", "reading_time") REFERENCES "readings" ("device_id", "time")`, with no new column.

![Schemity's Impact drawer after drawing a relation from readings to alerts on alerts' device_id and reading_time columns, both tables hypertables: under Storage engine, the one finding reads Adds a foreign key referencing readings, which TimescaleDB refuses: both tables are hypertables](https://schemity.com/images/blog/timescaledb-foreign-key-to-hypertable-retention/impact-fk-between-hypertables.webp)

![Schemity's Impact drawer on a TimescaleDB 2.32.1 database after drawing a relation from readings to incidents on incidents' existing device_id and reading_time columns: under Can fail on existing data, Adds a foreign key on incidents, fails if orphan rows exist, with Show on canvas and Count exactly; under Storage engine, Adds a foreign key referencing readings, a hypertable: drop_chunks and retention policies then refuse to drop its chunks](https://schemity.com/images/blog/timescaledb-foreign-key-to-hypertable-retention/impact-fk-into-hypertable.webp)

![Schemity's Preview changes for the same relation: the planned migration is one statement, ALTER TABLE incidents ADD CONSTRAINT incidents_device_id_reading_time_fkey FOREIGN KEY (device_id, reading_time) REFERENCES readings (device_id, time), the planned changes list one added foreign key, and Impact lists the same two findings](https://schemity.com/images/blog/timescaledb-foreign-key-to-hypertable-retention/preview-fk-on-existing-columns.webp)

The analysis also takes a hypertable's row count from TimescaleDB's `approximate_row_count()`, because the hypertable's own `reltuples` reads 0 even after `ANALYZE`. It reads a schema migration file an ORM or an AI agent wrote the same way, so the key on `incidents` shows up while it is still a pull request, which is what it means to see the impact of every change before it runs.

## Which direction should a TimescaleDB foreign key point?

From the hypertable to plain tables; into a hypertable only when its chunks are never dropped.

Other foreign key decisions with a cost that only shows later: [ON DELETE SET NULL vs CASCADE](https://schemity.com/blog/postgres-on-delete-set-null-vs-cascade/), and [whether to use foreign key constraints at all](https://schemity.com/blog/should-you-use-foreign-key-constraints/).

## Frequently asked questions

### Can two TimescaleDB hypertables reference each other with a foreign key?

No. Adding the key fails with `hypertables cannot be used as foreign key references of hypertables`, including a hypertable referencing itself, and so does converting a plain table that already holds such a key with `create_hypertable`. A hypertable referencing a plain table works, and a plain table referencing a hypertable is accepted since TimescaleDB 2.16.

### Why does `drop_chunks` fail with cannot drop table because other objects depend on it?

Because a table has a foreign key into the hypertable. TimescaleDB stores that key as one constraint per chunk, and dropping a chunk table is refused while a constraint depends on it. In our tests it happened with no referencing rows at all and with `ON DELETE CASCADE`, and the background retention policy failed the same way.

### How do I find foreign keys that point into a hypertable?

Query `pg_constraint` for `contype = 'f'` where `confrelid` is one of the tables in `timescaledb_information.hypertables`. Each row is a key that stops `drop_chunks` on that hypertable. Dropping the key on purpose is the clean fix; the `CASCADE` route the error message suggests drops the whole key without asking.
