// SQL snippet

List sequences and their current values

Integer keys have a ceiling, and a sequence racing toward it is an outage you can see coming. This recipe lists every sequence with its last value and increment.

Main statement
PostgreSQL
Также охватывает
SQL Server MySQL SQLite

The task

An int key is partway to 2.1 billion and you need to know how much runway every sequence has left before planning a migration to bigint.

The snippet

Written for PostgreSQL. Versions for SQL Server, MySQL and SQLite are under Variations.

PostgreSQL
SELECT schemaname, sequencename,
       last_value, start_value, increment_by, max_value
FROM pg_sequences
ORDER BY sequencename;

Как это работает

pg_sequences reports each sequence's last value without calling nextval. last_value is NULL for a sequence that has never been used, and with a CACHE setting above 1 it runs ahead of the ids actually stored, because each session reserves a block of values up front. Comparing last_value with max_value shows how much room is left; serial and integer identity columns get a max_value of 2147483647.

Variations

MySQL

MySQL
-- auto_increment is the NEXT value. MySQL 8 caches these stats
-- for information_schema_stats_expiry (24h by default), so run
-- ANALYZE TABLE first or SET information_schema_stats_expiry = 0
SELECT table_name, auto_increment
FROM information_schema.tables
WHERE table_schema = 'mydb' AND auto_increment IS NOT NULL
ORDER BY auto_increment DESC;

SQL Server

SQL Server
-- sequence objects only; IDENTITY columns are tracked in
-- sys.identity_columns (see find-identity-columns)
SELECT name, current_value, start_value, increment, maximum_value
FROM sys.sequences
ORDER BY name;

SQLite

SQLite
-- exists once any table is declared with AUTOINCREMENT;
-- one row per such table: name, seq (largest id used)
SELECT name, seq FROM sqlite_sequence;

Questions that come up

How close is my table to overflowing int ids?

Divide last_value (or auto_increment) by 2147483647 for a signed 32-bit int column. Past roughly half, plan the move to bigint: changing the type of a key column rewrites the table and every index that contains it, and foreign key columns in other tables have to change with it.

Keep reading

// snippets are better with a schema brain

Run these with autocomplete that knows your tables

SQLly is a native SQL workbench for macOS, Windows and Linux. Paste a snippet into a live connection and you get schema-aware IntelliSense, a plan viewer and guards against unsafe edits.