Sub topic 9
Choosing smallint, integer or bigint
This chapter assumes you know how to create tables and insert rows. It also assumes you know what a primary key is and how a GENERATED AS IDENTITY column is declared. The column type you pick for an identity column decides how many IDs you can ever hand out. It also affects index size and the cost of changing your mind later.
The type sets the ceiling
An identity column is backed by a sequence, and the sequence uses the same integer type as the column. PostgreSQL uses that type to set the sequence's maximum value. If you declare smallint, the sequence stops at 32,767. If you declare integer, it stops at 2,147,483,647.
| Type | Storage | Range | Largest identity value |
|---|---|---|---|
| `smallint` | 2 bytes | -32,768 to 32,767 | 32,767 |
| `integer` | 4 bytes | -2,147,483,648 to 2,147,483,647 | 2,147,483,647 |
| `bigint` | 8 bytes | -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 | 9,223,372,036,854,775,807 |
An identity sequence starts at 1 by default and counts upward. Only the positive half of each range is used, so the usable capacity is about half of what the type can store. You can start a sequence at a negative number if you want the full range. Few people do, because negative IDs confuse people and tools.
What happens at the limit
When the sequence reaches its maximum, the next insert fails. The sequence does not wrap around, because CYCLE is off by default. The following example starts a smallint identity two values below its limit so you can see the failure.
CREATE TABLE small_demo (
id smallint GENERATED ALWAYS AS IDENTITY (START WITH 32766) PRIMARY KEY,
note text NOT NULL
);
INSERT INTO small_demo (note) VALUES ('a') RETURNING id; -- 32766
INSERT INTO small_demo (note) VALUES ('b') RETURNING id; -- 32767
INSERT INTO small_demo (note) VALUES ('c') RETURNING id;
-- ERROR: nextval: reached maximum value of sequence "small_demo_id_seq" (32767)The error comes from the sequence, not from the table. Every insert into the table fails from that point on until you change the type or the sequence. In production this is an outage that starts without warning. The sequence is exhausted the moment the last value is handed out.
You can check what the sequence allows with the pg_sequences view:
SELECT sequencename, data_type, max_value, last_value
FROM pg_sequences
WHERE sequencename = 'small_demo_id_seq';The data_type column shows smallint, which confirms that the sequence follows the column type.
Estimating how long a type lasts
To size a column, divide the maximum value by the number of IDs you consume per day. Count every value the sequence hands out, not only the rows that remain. Rolled-back inserts, failed INSERT ... ON CONFLICT attempts and cached values lost in a crash all use up numbers. The earlier chapter on gaps covers why.
| Insert rate | `integer` lasts about | `bigint` lasts about |
|---|---|---|
| 10 per second | 6.8 years | 29 billion years |
| 1,000 per second | 25 days | 292 million years |
| 50,000 per second | 12 hours | 5.8 million years |
A table that looks small today can burn through IDs faster than its row count suggests. A queue table, an event log or a table with heavy upserts may hold a few thousand rows while the sequence advances millions of times a day. Estimate from the sequence's growth, not from count(*).
The following query shows how much of each sequence's range is used. It is a useful monitoring check.
SELECT schemaname,
sequencename,
data_type,
last_value,
max_value,
round(100.0 * last_value / max_value, 2) AS pct_used
FROM pg_sequences
WHERE last_value IS NOT NULL
ORDER BY pct_used DESC
LIMIT 10;Alert when pct_used passes a threshold such as 50 percent. Changing a large integer column takes time, so you want months of warning, not hours.
A decision path
smallint: rarely the right choice
smallint fits reference data that you control and that will never grow, such as a list of 12 order statuses or 50 country regions. Even then, the saving is small. Two bytes per row does not matter on a table with a few dozen rows.
Be careful with smallint when the column is also a foreign key target. Every referencing table must use a compatible type, and a later change touches all of them.
integer: fine until it is not
integer holds about 2.1 billion IDs. That is plenty for many business tables, such as customers or products, where inserts are slow and steady. It saves 4 bytes per row in the table and in every index that includes the column. It saves another 4 bytes in every foreign key column that references it.
The risk is that integer is easy to outgrow, and the problems show up late. Common causes are:
- A bulk import that inserts billions of rows.
- An application that retries failed inserts in a loop, burning one ID per attempt.
- A product that grows faster than planned.
- A table that began as a log, and now gets many writes.
bigint: the safe default
For most tables, use bigint. The ceiling is so high that exhaustion is not a practical concern. The cost is 4 extra bytes per row and per index entry compared with integer.
That cost is smaller than it looks. PostgreSQL aligns column values to their natural boundaries. A lone 4-byte integer next to an 8-byte column such as a timestamptz or bigint often gets padded to 8 bytes anyway. In those tables, bigint costs little or nothing in the heap. Index entries are also padded to 8-byte multiples on most platforms, so a single-column integer index often takes the same space as a bigint one.
The extra cost shows up mainly in foreign key columns, in tables with many narrow rows, and in indexes with several integer columns together.
CREATE TABLE events (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
kind text NOT NULL,
created_at timestamptz NOT NULL DEFAULT now()
);Matching types across tables
A foreign key column should have the same type as the key it references. PostgreSQL will accept a foreign key from an integer column to a bigint key, because the types are compatible. Comparisons across the two types can still prevent some index and join optimizations, and the mismatch makes later migrations harder.
Pick the type once, and use it for the key and for every column that points to it.
Converting integer to bigint later
You can widen a column with ALTER TABLE ... ALTER COLUMN ... TYPE:
ALTER TABLE orders ALTER COLUMN id TYPE bigint;Check what this does before you run it on a live system:
- It rewrites the whole table and rebuilds its indexes. The statement takes an
ACCESS EXCLUSIVElock, which blocks reads and writes for the duration. On a large table, that can mean minutes or hours. - Every foreign key column that references
idshould also be widened. Each of those tables is rewritten too. - For an identity column, PostgreSQL also updates the sequence's data type and its maximum. Confirm this with
pg_sequencesafter the change. Ifmax_valuestill shows 2,147,483,647, raise it yourself withALTER SEQUENCE ... AS bigint.
Do not fix overflow with CYCLE
You can set CYCLE on an identity sequence so it wraps back to its minimum after reaching the maximum. This is almost never what you want for a primary key. The sequence will start issuing numbers that already exist, and inserts will fail with unique violations as soon as it meets an existing row. It can also make data look valid when it is not, if the column lacks a unique constraint.
Summary of the trade-offs
- Choose
bigintunless you can show a reason not to. - Choose
integeronly when the table is bounded, the savings matter, and you monitor sequence usage. - Choose
smallintfor small, fixed lookup tables. - Estimate from sequence growth, not from row counts.
- Monitor
pg_sequencesand alert well before the limit.
Exercise
A table receives 400 inserts per second, and about 25 percent of them fail and roll back. The id column is an integer identity. Roughly how many days until the sequence is exhausted, and what should you check first?
Show answer
Every attempt consumes a sequence value, including rolled-back ones, so the sequence advances 400 times per second. 2,147,483,647 / 400 is about 5.4 million seconds, which is roughly 62 days. The failed inserts do not help, because they burn IDs as well. Check pgsequences for lastvalue and max_value to see how much of the range is already used, then plan to widen the column to bigint.
Exercise
You declare a column as smallint GENERATED ALWAYS AS IDENTITY with no other options. What is the largest ID it can hand out, and what happens on the next insert after that?
Show answer
The largest ID is 32,767. The next insert fails with an error like "nextval: reached maximum value of sequence ... (32767)", because the sequence does not cycle by default.