CACHE in CREATE/ALTER SEQUENCE defines how many sequence values PostgreSQL pre-allocates in memory, reducing disk I/O and speeding inserts.
CACHE tells PostgreSQL to reserve a block of sequence numbers in shared memory. When a session calls nextval, values are served from memory until the cache is exhausted, then the next block is written to disk. Larger caches reduce disk writes but risk value loss after crashes.
High-insert tables like Orders often benefit. If you batch-insert thousands of rows per second, a cache of 100–1000 can remove sequence bottlenecks. Measure WAL and disk I/O before and after.
Use CREATE SEQUENCE with the CACHE clause. Choose a size that balances speed and durability. Example below creates a 100-value cache for order IDs.
ALTER SEQUENCE lets you modify cache without recreating. The change is instantaneous and applies to the next write-back.
No. PostgreSQL ensures each value is handed out once. Crash can skip cached but unissued numbers, yet gaps are already expected in surrogate keys.
Start with CACHE 1 for low-traffic tables. Raise gradually while monitoring WAL volume and autovacuum. Avoid very large caches on sequences that matter for audit trails, as bigger gaps appear after restart.
The example query shows creating an Orders table with a high-cache sequence and demonstrates the performance gain.
Yes—set CACHE 1. This forces every increment to hit disk, maximizing durability at the cost of speed.
No. Each value is still unique. A crash only skips unused cached numbers.
No. CACHE is a sequence property, not a run-time parameter. Use ALTER SEQUENCE to change it.
Yes. PostgreSQL writes the next cached value to disk; interim values are served from memory.