# PostgreSQL Unused Sequences: How to Find Them, and Which Ones Are Safe to Drop

> The catalog answers half the question: a sequence attached to a column, used by a column default or by a `BEGIN ATOMIC` function cannot be dropped by accident, and PostgreSQL says so. A legacy default written as `nextval('s'::text)`, a function whose body is a string and application code record no dependency at all, so the drop succeeds and the next insert fails. Find those by searching defaults and function bodies, then watch `last_value` for a while before dropping anything.

Source: https://schemity.com/blog/postgres-find-unused-sequences/

You find unused sequences in PostgreSQL in two passes: the catalog tells you which sequences a column, a default or a function provably depends on, and a text search finds the callers the catalog never recorded. The second pass matters more than it looks. A sequence that no catalog query links to anything can still be the one every insert into a table needs, and dropping it succeeds without a word.

Everything below ran in throwaway containers on PostgreSQL 16.8, 17.5 and 18.3, with the same results on all three. The test database is a small billing schema of the kind a ten-year-old system accumulates: a `serial` key, an identity key, one document-number sequence shared by quotes and credit notes, a default left over from before PostgreSQL 8.1, and a few sequences nobody remembers creating.

```sql
CREATE TABLE invoices (id serial PRIMARY KEY, total numeric NOT NULL DEFAULT 0);
CREATE TABLE customers (id integer GENERATED ALWAYS AS IDENTITY PRIMARY KEY, name text NOT NULL DEFAULT '');
CREATE SEQUENCE doc_number_seq;
CREATE TABLE quotes (id serial PRIMARY KEY, number bigint NOT NULL DEFAULT nextval('doc_number_seq'));
CREATE TABLE credit_notes (id serial PRIMARY KEY, number bigint NOT NULL DEFAULT nextval('doc_number_seq'));
CREATE SEQUENCE legacy_ticket_seq;
CREATE TABLE tickets (id integer PRIMARY KEY DEFAULT nextval('legacy_ticket_seq'::text));
CREATE SEQUENCE app_batch_seq;
CREATE SEQUENCE old_import_seq;
CREATE SEQUENCE shipment_seq;
CREATE TABLE shipments (id bigint PRIMARY KEY);
ALTER SEQUENCE shipment_seq OWNED BY shipments.id;
CREATE SEQUENCE plpgsql_seq;
CREATE SEQUENCE atomic_seq;
CREATE FUNCTION next_ref() RETURNS bigint LANGUAGE plpgsql
  AS $$ BEGIN RETURN nextval('plpgsql_seq'); END $$;
CREATE FUNCTION next_ref2() RETURNS bigint LANGUAGE sql
  BEGIN ATOMIC SELECT nextval('atomic_seq'); END;
INSERT INTO quotes DEFAULT VALUES;
INSERT INTO quotes DEFAULT VALUES;
INSERT INTO credit_notes DEFAULT VALUES;
INSERT INTO tickets DEFAULT VALUES;
SELECT nextval('app_batch_seq');
```

## Which sequence uses does PostgreSQL record?

PostgreSQL records a sequence's attachment to a column, every column default, view and `BEGIN ATOMIC` function that calls it by name; it records nothing for a default written with a text cast, a function whose body is a string, or application code.

The record lives in `pg_depend`, and it is what makes PostgreSQL refuse a dangerous drop. Here is what each drop did on the test database:

| Sequence | How it is used | `DROP SEQUENCE` without `CASCADE` |
|---|---|---|
| `invoices_id_seq` | `serial`: attached to `invoices.id` and its default | Refused: "default value for column id of table invoices depends on sequence" |
| `customers_id_seq` | Identity column | Refused: "column id of table customers requires it" |
| `doc_number_seq` | Defaults on `quotes.number` and `credit_notes.number` | Refused, naming both columns |
| `atomic_seq` | Body of a `BEGIN ATOMIC` SQL function | Refused: "function next_ref2() depends on sequence" |
| `legacy_ticket_seq` | Default `nextval('legacy_ticket_seq'::text)` | **Dropped.** The next insert into `tickets` failed with `relation "legacy_ticket_seq" does not exist` |
| `plpgsql_seq` | Body of a PL/pgSQL function | **Dropped.** The next `SELECT next_ref()` failed the same way |
| `shipment_seq` | `OWNED BY shipments.id`, no default | Dropped; nothing in the database notices |
| `app_batch_seq`, `old_import_seq` | Nothing in the database | Dropped |

The two bold rows are the ones that hurt. The [CREATE FUNCTION manual](https://www.postgresql.org/docs/18/sql-createfunction.html) states the function half plainly: the `BEGIN ATOMIC` form "tracks dependencies between the function and objects used in the function body", while "the form using string literals may leave dangling functions". That covers any `AS $$ ... $$` body, not only PL/pgSQL: a `LANGUAGE sql` function written that way recorded nothing either. A `::text` default is the same problem in a column. The [object identifier types page](https://www.postgresql.org/docs/18/datatype-oid.html) says `nextval('my_seq'::text)` "does not create a dependency": the name is looked up on every call. A `::varchar` cast behaves the same. The [8.1 release notes](https://www.postgresql.org/docs/8.1/release-8-1.html) explain where most of these come from: before 8.1, sequence names in defaults "were stored as simple text strings", and dumps from those versions keep the text form when loaded into a newer server. The same notes give the cast as the way to keep run-time lookup on purpose, so some code writes it deliberately. Either way it survives every later dump: the test database's `pg_dump` writes `DEFAULT nextval(('legacy_ticket_seq'::text)::regclass)`.

## How do you find unused sequences in Postgres?

Run one catalog query for the uses PostgreSQL records, one text search for the uses it does not, and treat a sequence as unused only when both come back empty and its `last_value` stops moving.

The first query lists every sequence with the column it is attached to, the defaults and functions that depend on it, and its current value:

```sql
SELECT s.oid::regclass AS sequence,
       CASE own.deptype WHEN 'i' THEN 'identity' WHEN 'a' THEN 'owned by' END AS attached,
       own.refobjid::regclass || '.' || a.attname AS column,
       (SELECT string_agg(
                 CASE d.classid
                   WHEN 'pg_attrdef'::regclass THEN
                     (SELECT ad.adrelid::regclass || '.' || c.attname || ' default'
                        FROM pg_attrdef ad
                        JOIN pg_attribute c ON c.attrelid = ad.adrelid AND c.attnum = ad.adnum
                       WHERE ad.oid = d.objid)
                   WHEN 'pg_proc'::regclass THEN d.objid::regprocedure || ' body'
                   WHEN 'pg_rewrite'::regclass THEN
                     (SELECT r.ev_class::regclass || ' view' FROM pg_rewrite r WHERE r.oid = d.objid)
                   ELSE d.classid::regclass::text
                 END, ', ')
          FROM pg_depend d
         WHERE d.refobjid = s.oid AND d.deptype = 'n') AS used_by,
       pg_sequence_last_value(s.oid) AS last_value
FROM pg_class s
LEFT JOIN pg_depend own ON own.classid = 'pg_class'::regclass
     AND own.objid = s.oid AND own.deptype IN ('a', 'i')
LEFT JOIN pg_attribute a ON a.attrelid = own.refobjid AND a.attnum = own.refobjsubid
WHERE s.relkind = 'S'
  AND s.relnamespace NOT IN ('pg_catalog'::regnamespace, 'information_schema'::regnamespace)
ORDER BY s.oid::regclass::text;
```

On the test database it returned, leaving out the four `serial` and identity rows:

```text
 sequence          | attached | column       | used_by                                            | last_value
-------------------+----------+--------------+----------------------------------------------------+-----------
 app_batch_seq     |          |              |                                                    |          1
 atomic_seq        |          |              | next_ref2() body                                   |
 doc_number_seq    |          |              | quotes.number default, credit_notes.number default |          3
 legacy_ticket_seq |          |              |                                                    |          1
 old_import_seq    |          |              |                                                    |
 plpgsql_seq       |          |              |                                                    |
 shipment_seq      | owned by | shipments.id |                                                    |
```

`legacy_ticket_seq` and `plpgsql_seq` look exactly like `old_import_seq`, which really is unused. The second query finds the callers the catalog missed, in column defaults and in function bodies:

```sql
SELECT 'default' AS used_in, adrelid::regclass || '.' || attname AS name,
       pg_get_expr(adbin, adrelid) AS text
FROM pg_attrdef JOIN pg_attribute ON attrelid = adrelid AND attnum = adnum
WHERE pg_get_expr(adbin, adrelid) ~* 'nextval\(\(''[^'']+''::'
UNION ALL
SELECT 'function', p.oid::regprocedure::text, substring(p.prosrc from '(?i)nextval\([^)]*\)')
FROM pg_proc p
WHERE p.prosrc ~* 'nextval'
  AND p.pronamespace NOT IN ('pg_catalog'::regnamespace, 'information_schema'::regnamespace);
```

```text
 used_in  | name       | text
----------+------------+-----------------------------------------------
 default  | tickets.id | nextval(('legacy_ticket_seq'::text)::regclass)
 function | next_ref() | nextval('plpgsql_seq')
```

A function that builds the sequence name at run time (`nextval(tbl || '_seq')`) shows up in that search without the name, so read those bodies by hand. Application code is the last blind spot, and no query reaches it: search the codebase for each candidate's name, including ORM settings such as Hibernate's `@SequenceGenerator(sequenceName = ...)`.

## Can you tell from last_value whether a sequence is still called?

Only by comparing it over time: `last_value` says where the sequence stands, not when it last moved, and PostgreSQL keeps no count of `nextval` calls.

The `pg_sequences` documentation lists three reasons `last_value` reads as null: the sequence "has not been read from yet", the current user lacks `USAGE` or `SELECT` on it, or it is an unlogged sequence on a standby. So, run as the owner or a superuser, a null means the sequence has not been called since it was created or last reset with `ALTER SEQUENCE ... RESTART`. In the test database, `old_import_seq` was null and `app_batch_seq`, called once by hand, read 1. A non-null value can be years old. The statistics views for sequences, `pg_statio_all_sequences` and its user and system variants, count disk blocks read and buffer hits, not calls. The practical test is to save the query's output, run it again after a full business cycle (a week covers most jobs, a month covers month-end), and keep every sequence whose `last_value` moved.

## Which sequences are safe to drop?

A sequence is safe to drop when the catalog query, the text search and the codebase all come back empty and its `last_value` has not moved; everything else either fails loudly or breaks writes later.

| What you found | Drop it? | What happens if you do |
|---|---|---|
| Attached `owned by` a column, with a default | No | Refused while the default exists; it goes with the column or table |
| Identity | No | Refused; `ALTER COLUMN ... DROP IDENTITY` is the way to remove it |
| A default depends on it | No | Refused; with `CASCADE` the defaults go and inserts fail |
| A `BEGIN ATOMIC` function depends on it | No | Refused; with `CASCADE` the function goes too |
| Named in a `::text` default or a string function body | No | Dropped, then every insert or call that reaches it fails |
| Attached `owned by` a column with no default | Check the code | Dropped; whatever called it from outside fails |
| Nothing anywhere, `last_value` unchanged | Yes | Nothing |

`CASCADE` deserves its own line. `DROP SEQUENCE doc_number_seq CASCADE` succeeded with only a `NOTICE` that it had dropped the defaults on `quotes.number` and `credit_notes.number`. Both columns are `NOT NULL`, so the very next `INSERT INTO quotes DEFAULT VALUES` failed with `null value in column "number" of relation "quotes" violates not-null constraint`. Attachment works the other way round too. The `ALTER SEQUENCE` manual says an `OWNED BY` sequence is dropped automatically when its column or table is, which is why `DROP TABLE shipments` took `shipment_seq` with it. Attach a shared sequence to one of its users and dropping that table becomes the refusal: after `ALTER SEQUENCE doc_number_seq OWNED BY quotes.number`, `DROP TABLE quotes` failed because the default on `credit_notes.number` still depends on the sequence.

Two legacy fixes fall out of the inventory. Unless the late binding is deliberate, rewrite a `::text` default to the normal form, `ALTER TABLE tickets ALTER COLUMN id SET DEFAULT nextval('legacy_ticket_seq')`, which stores a `regclass` and records the dependency, so the catalog protects it from then on. And a `serial` column is often better as identity, which [serial vs identity](https://schemity.com/blog/postgres-serial-vs-identity/) covers along with the conversion.

## How does Schemity show which columns draw on a sequence?

Schemity reads each column's default from the live database exactly as PostgreSQL stores it, shows a sequence a column owns without drawing on it, and, from the next release, reports what a `DROP SEQUENCE` in a migration file breaks before it 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. [Reading a database](https://schemity.com/doc/reverse-engineer-database/) puts every default on its column, so `tickets.id` shows `nextval(('legacy_ticket_seq'::text)::regclass)` in its Field details, and `shipments.id` shows a Sequence row for `shipment_seq`, the one use of a sequence the default never reveals. That is the column half of the inventory, readable in the diagram rather than reconstructed from `pg_depend`, which is what it means to understand your schema before you clean it up.

![Schemity's Field details drawer for shipments.id on a PostgreSQL 18.3 diagram of the billing tables: type BIGINT, primary key, unique, not nullable, and a Sequence row reading shipment_seq, while the canvas shows shipments.id with no default and tickets.id with a nextval default](https://schemity.com/images/blog/postgres-find-unused-sequences/field-details-sequence.webp)

The cleanup itself usually arrives as a schema migration file. Writing this post found that Schemity's [impact analysis](https://schemity.com/doc/impact-analysis/) (a Schemity Pro feature) listed `DROP SEQUENCE` under Not analysed. In the next release it reads `DROP SEQUENCE` on PostgreSQL and reports, for each column whose default draws on the sequence, which way the drop goes: "Drops sequence doc_number_seq, which the default of quotes.number draws on: the database refuses the drop"; with `CASCADE`, that the default is removed and an insert that leaves `number` out then fails on `NOT NULL`; and for a `::text` default, that the database records no dependency, so the drop succeeds and the insert fails. The next release also adds a column's owned sequence to what an AI agent reads over MCP, so an agent asked to inventory sequences sees `shipment_seq` too.

![Schemity's SQL migration drawer on a PostgreSQL 18.3 diagram of the billing tables, reading three DROP SEQUENCE statements: 3 statements, 3 analysed, and three dependent-object findings, legacy_ticket_seq named as text by the default of tickets.id so the drop succeeds and an insert that leaves id out then fails, and doc_number_seq dropped with CASCADE removing the defaults of credit_notes.number and quotes.number so an insert that leaves number out then fails on NOT NULL](https://schemity.com/images/blog/postgres-find-unused-sequences/impact-drop-sequence.webp)

Preview changes draws what the file leaves: `credit_notes.number` and `quotes.number` lose their `nextval` default, and the planned migration sits above the same three findings.

![Schemity's change preview of the same migration file: credit_notes and quotes drawn with number as a plain BIGINT and no default, two planned changes marking both number columns altered, no lint findings, and the three impact findings listed below the planned DROP SEQUENCE statements](https://schemity.com/images/blog/postgres-find-unused-sequences/preview-drop-sequence-cascade.webp) A sequence used only by functions or application code is still outside what Schemity reads: that part of the search stays yours.

## Related reading

- [PostgreSQL DROP COLUMN: what it refuses and what it drops](https://schemity.com/blog/postgres-drop-column-what-it-drops/) covers what a column drop takes with it, and the PL/pgSQL trigger it breaks later, the same blind spot as above.
- [How to track schema changes in PostgreSQL](https://schemity.com/blog/postgres-track-schema-changes/) is the next step once the inventory exists: noticing when it changes.

## Frequently asked questions

### How do I find unused sequences in Postgres?

List every sequence with what `pg_depend` says holds it: a column it is attached to, and the column defaults and `BEGIN ATOMIC` functions that depend on it. Then search column defaults for a cast name such as `nextval('s'::text)` and function bodies for `nextval`, because neither records a dependency. A sequence with nothing in either list, and a `last_value` that does not move over a week or two, is a candidate to drop.

### Can I drop a sequence that a column default uses?

Not without `CASCADE`. PostgreSQL refuses `DROP SEQUENCE` while a default depends on the sequence and names each column in the error. `DROP SEQUENCE ... CASCADE` drops the defaults instead, reporting it only as a notice, so a `NOT NULL` column then refuses every insert that leaves it out.

### Does dropping a table drop its sequence?

Only a sequence attached to one of its columns with `OWNED BY`, which is what `serial` does and what an identity column does internally. A sequence the table only calls in a default is not dropped with it, and if another table's default also calls an owned sequence, PostgreSQL refuses the `DROP TABLE` until that default goes.
